diff --git a/.agents/skills/create-feed/SKILL.md b/.agents/skills/create-feed/SKILL.md index 4bac95d..9d9de9a 100644 --- a/.agents/skills/create-feed/SKILL.md +++ b/.agents/skills/create-feed/SKILL.md @@ -13,8 +13,10 @@ Use this skill when adding or updating a Feed route in RSSBook, migrating route 2. Create the Source at `pkgs/rssbook/src/routers/feeds/{category}/{slug}/index.ts`; use `bun source:new` when scaffolding from an existing template is useful. 3. Register it in `pkgs/rssbook/src/routers/feeds/{category}/index.ts`. 4. Use RSSBook utilities from the handler context instead of importing alternate fetch/parser stacks. -5. Add one explicit route test per Feed route. -6. Run formatting and TypeScript. Run source route tests with `bun source:test` or `bun source:test:all` only when route network checks are intended. +5. In `route_handler`, prefer predefined errors from `@/utils/error` over `new Error(...)` so the global handler can map `status`, `code`, and `retryable` consistently. +6. When a route fails because of invalid input, missing upstream content, browser availability, cache misses, or parse/render issues, choose the closest existing `RSSBookError` subclass first; add a new one in `@/utils/error` only when no existing code fits. +7. Add one explicit route test per Feed route. +8. Run formatting and TypeScript. Run source route tests with `bun source:test` or `bun source:test:all` only when route network checks are intended. ## Feed Development Checklist @@ -34,6 +36,8 @@ Read only the references needed for the task: - New Source structure, route migration patterns, metadata naming, and route testing: [references/feed-routes.md](references/feed-routes.md) - RSSBook utility APIs (`cache`, `date`, `ofetch`, `load`, `formatHTML`, feed transforms): [references/utils.md](references/utils.md) +- Browser routes, bounded page concurrency, lifecycle, cookies, response waits, resource filtering, and fingerprint consistency: [references/browser.md](references/browser.md) +- RSSBook error catalog and where to use each error: [references/errors.md](references/errors.md) ## Source Shape @@ -118,6 +122,7 @@ The handler function receives these properties: - **Metadata**: `meta` (source metadata including `slug`, `title`, `description`, `domain`, `config`), `lang` (request language) - **Request**: `params` (route parameters), `query` (query parameters), `headers` (request headers) - **Utilities**: `cache`, `date`, `ofetch`, `load`, `formatHTML`, `toAbsoluteURL`, `parse`, `logger`, `uuid`, `config` +- **Browser**: `browser` for routes whose Feed metadata declares `browser: true`; read [references/browser.md](references/browser.md) before using it ## Metadata Rules diff --git a/.agents/skills/create-feed/references/browser.md b/.agents/skills/create-feed/references/browser.md new file mode 100644 index 0000000..d362c25 --- /dev/null +++ b/.agents/skills/create-feed/references/browser.md @@ -0,0 +1,183 @@ +# Browser Routes + +Use the browser only when the upstream page requires JavaScript, browser cookies, or an API response that cannot be reproduced reliably with `ofetch`. Prefer `ofetch` and `load` for static pages. + +RSSBook exposes an app-scoped `Browser` pool backed by Puppeteer-compatible APIs. A route receives `browser` after its Feed metadata declares `browser: true`. + +```typescript +export default new Source({ + description: "Rendered feed example.", + domain: "example.com", + slug: "rendered-example", + title: "Rendered Example", +}).feed( + { + browser: true, + description: "Fetch content rendered by the browser.", + title: "Rendered Example", + }, + (app) => app.get("/latest", async ({ browser }) => { + // Browser route implementation + }), +); +``` + +## Single Page Lifecycle + +Use `browser.acquirePage()` for a single isolated page. It consumes one context and one page slot. Always close the lease in `finally`; closing the page lease also closes its private context. + +```typescript +const lease = await browser.acquirePage(); + +try { + const { page } = lease; + await page.goto(link, { waitUntil: "domcontentloaded" }); + return await page.content(); +} finally { + await lease.close(); +} +``` + +RSSBook calls `browser.deinit()` when the application stops. That shutdown hook is a final cleanup boundary, not a replacement for closing route-owned leases. + +## Concurrency Model + +The Browser instance has three fixed capacity properties: + +- `maxBrowsers`: maximum physical local browser processes or remote browser sessions. +- `maxContextsPerBrowser`: maximum isolated contexts in each physical browser. +- `maxPagesPerContext`: maximum tracked pages, including popups, in each context. + +When capacity is full, `acquireContext()` and `acquirePage()` wait until another lease releases capacity. Pass an `AbortSignal` when the wait must follow a request timeout or cancellation. + +```typescript +const controller = new AbortController(); +const timeout = setTimeout(() => controller.abort(new Error("Browser acquisition timed out")), 15_000); + +try { + const lease = await browser.acquirePage({ signal: controller.signal }); + try { + await lease.page.goto(link, { waitUntil: "domcontentloaded" }); + } finally { + await lease.close(); + } +} finally { + clearTimeout(timeout); +} +``` + +`browser.acquirePage()` creates a private context for every page. Therefore its maximum concurrent page count is constrained by context capacity. Use it for isolated tasks and unrelated requests. + +Use `browser.acquireContext()` when pages need to share cookies, local storage, or login state. Pages within one context may run concurrently, but the route must bound workers to `browser.maxPagesPerContext`. + +```typescript +const contextLease = await browser.acquireContext(); + +try { + const results = new Array(links.length); + const concurrency = Math.min(links.length, browser.maxPagesPerContext); + + await Promise.all( + Array.from({ length: concurrency }, async (_, workerIndex) => { + for (let index = workerIndex; index < links.length; index += concurrency) { + const pageLease = await contextLease.acquirePage(); + try { + await pageLease.page.goto(links[index], { waitUntil: "domcontentloaded" }); + results[index] = await pageLease.page.content(); + } finally { + await pageLease.close(); + } + } + }), + ); + + return results; +} finally { + await contextLease.close(); +} +``` + +Do not acquire an unbounded list of page leases with `Promise.all` and hold every acquired page until all acquisitions finish. If the list exceeds `maxPagesPerContext`, the remaining acquisitions wait while completed acquisitions retain the capacity they need, causing a deadlock. Use bounded workers and close each page before acquiring the next one. + +## Browser Utilities + +Browser utilities are exported from `@/utils`. They operate on Puppeteer `Page` or `BrowserContext` objects and remain separate from the Browser pool. + +### Block Resources + +Images, media, and fonts are blocked by default when no resource types are supplied. + +```typescript +import { blockResources } from "@/utils"; + +await blockResources(page); +await page.goto(link, { waitUntil: "domcontentloaded" }); +``` + +Use `allowResources(page, { resourceTypes: [...] })` when only a small set should load. Configure interception before navigation. + +### Wait For A Response + +`waitForResponse()` registers the response listener before navigation or interaction, avoiding a race with fast responses. + +```typescript +import { waitForResponse } from "@/utils"; + +const response = await waitForResponse( + page, + (response) => response.url().includes("/api/items") && response.status() === 200, + () => page.goto(link, { waitUntil: "domcontentloaded" }), + { timeout: 15_000 }, +); +const data = await response.json(); +``` + +### Preserve Cookies + +Cookies belong to a BrowserContext. Reuse the same context for pages that must share a session. Routes control persistence themselves; RSSBook does not provide a global browser state store. + +```typescript +import { getCookieHeader, setCookieHeader } from "@/utils"; + +await setCookieHeader(contextLease.context, configuredCookie, "https://example.com"); +const cookieHeader = await getCookieHeader(contextLease.context); +``` + +Store a returned Cookie header with the route's chosen cache or configuration mechanism only when that behavior is required. Do not share unrelated users' authenticated state. + +### Keep Fingerprints Consistent + +Use native Puppeteer methods together with RSSBook helpers before the first navigation. Treat the values as one coherent device profile; do not randomize fields independently or change only the User-Agent. + +```typescript +import { + setColorDepth, + setDeviceMemory, + setHardwareConcurrency, + setLanguages, +} from "@/utils"; + +await page.setUserAgent({ + platform: "Win32", + userAgent: + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36", +}); +await page.setViewport({ width: 1920, height: 1080, deviceScaleFactor: 1 }); +await page.emulateTimezone("America/New_York"); +await setLanguages(page, ["en-US", "en"]); +await setHardwareConcurrency(page, 8); +await setDeviceMemory(page, 8); +await setColorDepth(page, 24); +``` + +The User-Agent, platform, languages, timezone, screen size, hardware concurrency, device memory, and color depth must describe a plausible single machine. Puppeteer and the browser already provide `navigator.vendor`, plugins, permissions, and Chrome APIs; overriding them independently is likely to make the fingerprint less consistent. + +## Route Checklist + +- Declare `browser: true` in Feed metadata. +- Acquire through `browser.acquirePage()` or `browser.acquireContext()`; do not launch Puppeteer inside a route. +- Configure cookies, interception, response waits, and fingerprint values before navigation. +- Bound multi-page work to `browser.maxPagesPerContext`. +- Close every page or context lease in `finally`. +- Prefer one context when pages must share a session; prefer private page leases for isolated tasks. +- Wrap expensive browser work in `cache.tryGet()` when the result can be reused safely. diff --git a/.agents/skills/create-feed/references/errors.md b/.agents/skills/create-feed/references/errors.md new file mode 100644 index 0000000..b37b84a --- /dev/null +++ b/.agents/skills/create-feed/references/errors.md @@ -0,0 +1,53 @@ +# RSSBook Error Reference + +Use `@/utils/error` for route handlers, utilities, and the global Elysia error handler. Prefer the narrowest error that matches the failure mode. + +## Browser + +- `BrowserUnavailableError`: route was declared with `browser: true`, but the app was created without browser support. +- `BrowserClosedError`: a browser instance was already deinitialized and cannot be reused. +- `BrowserInitializationError`: browser startup returned a non-browser or otherwise failed before the browser became usable. +- `BrowserEndpointError`: CDP/WebSocket endpoint resolution failed or returned an invalid browser description. +- `UnsupportedProtocolError`: browser endpoint URL uses an unsupported protocol. + +## Cache And Fetch + +- `CacheMissError`: a cache lookup was required, but no fetcher was provided. +- `FetchHtmlError`: HTML fetch or HTML parsing for a page scrape failed. +- `SourceFetchError`: a feed source could not fetch or parse any upstream feed data. + +## Input And Validation + +- `InvalidUrlError`: a URL string cannot be parsed. +- `InvalidProtocolError`: a URL is not `http:` or `https:`. +- `LocalAddressError` and `LocalIpAddressError`: local addresses and IP literals are rejected. +- `InvalidDomainSuffixError` and `InvalidDomainNameError`: the host is not an allowed public domain. +- `InvalidRoutePathError`: a dispatch path does not start with `/`. +- `InvalidSourceSlugError`: a source slug does not match the allowed slug format. +- `DuplicateRouteTitleError` and `DuplicateSourceError`: route or source registration collides with an existing one. + +## Feed Parsing And Rendering + +- `ParseError`: raw JSON parsing or feed parsing failed. +- `DataValidationError`: parsed feed data did not satisfy the `Data` schema. +- `InvalidFeedFormatError` and `FeedFormatError`: the requested feed format is invalid or unsupported. +- `FeedRenderError`: feed serialization failed after validation. + +## Route Utilities + +- `InvalidOverrideJsonError`: a utility route override payload is invalid JSON. +- `UnionFeedError`, `IntersectionFeedError`, `FilterFeedError`, `SortFeedError`, `TransformFeedError`: combine, intersect, filter, sort, or transform route logic failed after upstream work started. +- `InvalidRankingTypeError`: the requested source-specific ranking type is not supported. +- `FeedNotFoundError`: an upstream source page, author, tag, or user could not be found. + +## Status Guidance + +- Use `400` for client input and validation failures. +- Use `404` for missing upstream resources. +- Use `502` for upstream fetch or endpoint resolution failures. +- Use `503` when the failure is caused by unavailable runtime capabilities. +- Use `500` for internal or invariant violations. + +## Skill Rule + +When adding a new route handler, start by checking this reference and use an existing error class if one matches. Add a new error only when the failure mode has a stable meaning that will be reused elsewhere. diff --git a/HOSTS b/HOSTS index 6d9fb17..4eb0bd5 100644 --- a/HOSTS +++ b/HOSTS @@ -1,2 +1,4 @@ url,description,online -https://rssbook.htu.me,Official RSSBook Website,true +https://rssbook.vercel.app,Official RSSBook Instance on Vercel,true +https://rssbook.niapya.deno.net,Official RSSBook Instance on Deno,true +https://rssbook.htu.me,Official RSSBook Instance on Cloudflare,true diff --git a/README.EN.md b/README.EN.md index d9875db..56c89b0 100644 --- a/README.EN.md +++ b/README.EN.md @@ -390,6 +390,6 @@ This project would not be possible without the support and help of all contribut [![Github Contributors](https://contrib.rocks/image?repo=HackHTU/RSSBook)](https://github.com/HackHTU/RSSBook/graphs/contributors) This project's inspiration comes from RSSHub and RSSWorker. -This project's development relies on Bun, Cheerio, dayjs, ElysiaJS, Kita/html, ofetch, sanitize-html, unstorage and other excellent open-source projects. +This project's development relies on Bun, Cheerio, dayjs, ElysiaJS, Kita/html, lru-cache, ofetch, sanitize-html, and other excellent open-source projects. This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. diff --git a/README.md b/README.md index 7cd9f3c..66427eb 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,6 @@ RSSBook 本身只负责「生成 Feed」,但由于输出的就是标准 RSS 2. [![Github Contributors](https://contrib.rocks/image?repo=HackHTU/RSSBook)](https://github.com/HackHTU/RSSBook/graphs/contributors) 本项目的灵感离不开 RSSHub 和 RSSWorker 项目。 -本项目的开发离不开 Bun, Cheerio, dayjs, ElysiaJS, Kita/html, ofetch, sanitize-html, unstorage 优秀的开源项目。 +本项目的开发离不开 Bun, Cheerio, dayjs, ElysiaJS, Kita/html, lru-cache, ofetch, sanitize-html 等优秀的开源项目。 本项目采用 MIT 许可证,详情请查看 [LICENSE](LICENSE) 文件。 diff --git a/biome.jsonc b/biome.jsonc index 75292a9..3ef9680 100644 --- a/biome.jsonc +++ b/biome.jsonc @@ -16,18 +16,13 @@ "./pkgs/*/package.json", "./pkgs/*/tsconfig.json", "./pkgs/*/src/**", - "./platform/*/index.ts", - "./platform/*/package.json", - "./platform/*/tsconfig.json", - "./platform/cloudflare/wrangler.jsonc", - "./platform/deno/deno.json", - "./platform/netlify/netlify.toml", - "./platform/vercel/vercel.json", + "./platform/**", "./scripts/**", "./biome.jsonc", "./package.json", "./tsconfig.json", - "./tsconfig.base.json" + "./tsconfig.base.json", + "!**/worker-configuration.d.ts" ] }, "formatter": { diff --git a/bun.lock b/bun.lock index 9fb777f..b2346ff 100644 --- a/bun.lock +++ b/bun.lock @@ -29,9 +29,10 @@ "domhandler": "^5.0.3", "elysia": "^1.4.29", "feed": "^5.2.1", + "lru-cache": "^11.5.1", "ofetch": "^1.5.1", + "puppeteer-core": "^25.3.0", "sanitize-html": "^2.17.5", - "unstorage": "1.17.5", "uuid": "^13.0.2", }, "devDependencies": { @@ -42,21 +43,29 @@ "name": "utils-feed-helper", "version": "1.0.50", "dependencies": { - "@elysiajs/html": "catalog:", - "@kitajs/html": "catalog:", - "@kitajs/ts-html-plugin": "catalog:", + "@elysiajs/static": "catalog:", "elysia": "catalog:", + "react": "^19", + "react-dom": "^19", }, "devDependencies": { - "bun-types": "catalog:", + "@types/bun": "catalog:", + "@types/react": "^19", + "@types/react-dom": "^19", }, }, "platform/cloudflare": { "name": "@rssbook/platform-cloudflare", "dependencies": { + "@cloudflare/puppeteer": "^1.1.0", "elysia": "^1.4.29", "rssbook": "workspace:*", - "unstorage": "^1.17.5", + }, + }, + "platform/deno": { + "name": "@rssbook/platform-deno", + "dependencies": { + "rssbook": "workspace:*", }, }, "platform/node": { @@ -72,7 +81,9 @@ "platform/vercel": { "name": "@rssbook/platform-vercel", "dependencies": { + "@sparticuz/chromium-min": "149.0.0", "elysia": "^1.4.29", + "puppeteer-core": "25.3.0", "rssbook": "workspace:*", }, }, @@ -100,7 +111,6 @@ "sanitize-html": "^2.17.5", "tsup": "^8.5.1", "tsx": "latest", - "unstorage": "1.17.5", "uuid": "^13.0.2", }, "packages": { @@ -124,6 +134,8 @@ "@borewit/text-codec": ["@borewit/text-codec@0.2.2", "", {}, "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ=="], + "@cloudflare/puppeteer": ["@cloudflare/puppeteer@1.1.0", "", { "dependencies": { "@puppeteer/browsers": "2.2.4", "debug": "^4.3.5", "devtools-protocol": "0.0.1299070", "ws": "^8.18.0" } }, "sha512-lN10En49avRDQvz8Gpv/WiIoGvjjDiP6P+v2y9bA6rfPT5WHfnlg2O6MwjHc1POm8A9LXf1sMdgrsdW8xWapOw=="], + "@elysiajs/eden": ["@elysiajs/eden@1.4.9", "", { "peerDependencies": { "elysia": ">=1.4.19" } }, "sha512-3CKVD4ycVjB8nCNssfmhnUuq3SzSHkUES3v5PNCFr9LxIrx39/HVRAZ8z2sLxrFqzUs48dCBZaxoZzJ5UUVHDA=="], "@elysiajs/html": ["@elysiajs/html@1.4.2", "", { "dependencies": { "@kitajs/html": "^4.1.0", "@kitajs/ts-html-plugin": "^4.0.1" }, "peerDependencies": { "elysia": ">= 1.4.0" } }, "sha512-Db7dmbkN7gptckMpU0/Fq9Qi3QuhQr/CH60A+8rs+RT+74NUC8sONs5nkfMm5oL+6kCUWCv19uUwOjBP7zsjYQ=="], @@ -202,6 +214,8 @@ "@nodable/entities": ["@nodable/entities@2.2.0", "", {}, "sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg=="], + "@puppeteer/browsers": ["@puppeteer/browsers@2.2.4", "", { "dependencies": { "debug": "^4.3.5", "extract-zip": "^2.0.1", "progress": "^2.0.3", "proxy-agent": "^6.4.0", "semver": "^7.6.2", "tar-fs": "^3.0.6", "unbzip2-stream": "^1.4.3", "yargs": "^17.7.2" }, "bin": { "browsers": "lib/cjs/main-cli.js" } }, "sha512-BdG2qiI1dn89OTUUsx2GZSpUzW+DRffR1wlMJyKxVHYrhnKoELSDxDd+2XImUkuWPEKk76H5FcM/gPFrEK1Tfw=="], + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.2", "", { "os": "android", "cpu": "arm" }, "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg=="], "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.2", "", { "os": "android", "cpu": "arm64" }, "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw=="], @@ -256,38 +270,72 @@ "@rssbook/platform-cloudflare": ["@rssbook/platform-cloudflare@workspace:platform/cloudflare"], + "@rssbook/platform-deno": ["@rssbook/platform-deno@workspace:platform/deno"], + "@rssbook/platform-node": ["@rssbook/platform-node@workspace:platform/node"], "@rssbook/platform-vercel": ["@rssbook/platform-vercel@workspace:platform/vercel"], "@sinclair/typebox": ["@sinclair/typebox@0.34.49", "", {}, "sha512-brySQQs7Jtn0joV8Xh9ZV/hZb9Ozb0pmazDIASBkYKCjXrXU3mpcFahmK/z4YDhGkQvP9mWJbVyahdtU5wQA+A=="], + "@sparticuz/chromium-min": ["@sparticuz/chromium-min@149.0.0", "", { "dependencies": { "tar-fs": "^3.1.2" } }, "sha512-/+QWJ6jDQnm/U7BITWVVcoe1CbuyW13pjonFpfBY67ZxePbaY/j4Ho+//n82AoGwugdkVVOYGY00KzMJzfYQdg=="], + "@tokenizer/inflate": ["@tokenizer/inflate@0.4.1", "", { "dependencies": { "debug": "^4.4.3", "token-types": "^6.1.1" } }, "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA=="], "@tokenizer/token": ["@tokenizer/token@0.3.0", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="], + "@tootallnate/quickjs-emscripten": ["@tootallnate/quickjs-emscripten@0.23.0", "", {}, "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA=="], + "@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], "@types/node": ["@types/node@26.1.0", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-O0A1G3xPGy4w7AgQdAQYUlQ+BKk2Oovw8eRpofyp5KdBZULnbe+WqaOVNrm705SHphCiG4XHsACrSmPu1f+Kgw=="], + "@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], + + "@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="], + "@types/sanitize-html": ["@types/sanitize-html@2.16.1", "", { "dependencies": { "htmlparser2": "^10.1" } }, "sha512-n9wjs8bCOTyN/ynwD8s/nTcTreIHB1vf31vhLMGqUPNHaweKC4/fAl4Dj+hUlCTKYgm4P3k83fmiFfzkZ6sgMA=="], + "@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="], + "acorn": ["acorn@8.17.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg=="], + "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + "ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], "ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], - "anymatch": ["anymatch@3.1.3", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="], - "anynum": ["anynum@1.0.1", "", {}, "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A=="], + "ast-types": ["ast-types@0.13.4", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w=="], + + "b4a": ["b4a@1.8.1", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw=="], + + "bare-events": ["bare-events@2.9.1", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg=="], + + "bare-fs": ["bare-fs@4.7.4", "", { "dependencies": { "bare-events": "^2.5.4", "bare-path": "^3.0.0", "bare-stream": "^2.6.4", "bare-url": "^2.2.2", "fast-fifo": "^1.3.2" }, "peerDependencies": { "bare-buffer": "*" }, "optionalPeers": ["bare-buffer"] }, "sha512-y1kC+ffIx/tPLdTE693uNjHfzTfr+ravR5tvWlMXe25nELbkqV400S71qHDwbkAQ1FVEZobB1NFRzFbCCcyBCQ=="], + + "bare-path": ["bare-path@3.1.1", "", {}, "sha512-JprUlveX3QjApC1cTpsUOiscADftCGVWkzitbHsRqv84hzYwYHw2mbluddsq5TvI8mH/8Ov1f4BiMAdcB0oYnQ=="], + + "bare-stream": ["bare-stream@2.13.3", "", { "dependencies": { "b4a": "^1.8.1", "streamx": "^2.25.0", "teex": "^1.0.1" }, "peerDependencies": { "bare-abort-controller": "*", "bare-buffer": "*", "bare-events": "*" }, "optionalPeers": ["bare-abort-controller", "bare-buffer", "bare-events"] }, "sha512-Kc+brLqvEqGkjyfiwJmImAOqLZL7OsoLKuavx+hJjgVV3nLTOjloJyPMFxjUPerGGHrNH0fLU06jjykMLWrERQ=="], + + "bare-url": ["bare-url@2.4.5", "", { "dependencies": { "bare-path": "^3.0.0" } }, "sha512-K+y9xF1tN+CdPu4qWwr0QiK1Al07eFPGYK5M2pDXcmHdMdgC/tT/bpmMe1hrmRHaidKLkXrC+cRNYf3XVDUhSQ=="], + + "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], + + "basic-ftp": ["basic-ftp@5.3.1", "", {}, "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw=="], + "boolbase": ["boolbase@1.0.0", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="], + "buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="], + + "buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="], + "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], "bundle-require": ["bundle-require@5.1.0", "", { "dependencies": { "load-tsconfig": "^0.2.3" }, "peerDependencies": { "esbuild": ">=0.18" } }, "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA=="], @@ -300,10 +348,16 @@ "cheerio-select": ["cheerio-select@2.1.0", "", { "dependencies": { "boolbase": "^1.0.0", "css-select": "^5.1.0", "css-what": "^6.1.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.0.1" } }, "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g=="], - "chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], + "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + + "chromium-bidi": ["chromium-bidi@16.0.1", "", { "dependencies": { "mitt": "^3.0.1", "zod": "^3.24.1" }, "peerDependencies": { "devtools-protocol": "*" } }, "sha512-J63PGu/9PpeCwLIcKYyzWP6yaVL5pxuBc0shlYCYM8BaAkmlwiQboXO1iNbOgSDbVklEyYFfNEcHD8oOAWacUA=="], "cliui": ["cliui@9.0.1", "", { "dependencies": { "string-width": "^7.2.0", "strip-ansi": "^7.1.0", "wrap-ansi": "^9.0.0" } }, "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w=="], + "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + "commander": ["commander@4.1.1", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="], "confbox": ["confbox@0.1.8", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="], @@ -312,8 +366,6 @@ "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], - "cookie-es": ["cookie-es@1.2.3", "", {}, "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw=="], - "crossws": ["crossws@0.4.9", "", { "peerDependencies": { "srvx": ">=0.11.5" }, "optionalPeers": ["srvx"] }, "sha512-iWx+1OMSG2aOHpjyf9AESOzkwsVdS49cXM9dVrI2PDhxU5l2RIWE/KG56gk4BbAnsMoycvniJ9OnOxO9LRzHVA=="], "css-select": ["css-select@5.2.2", "", { "dependencies": { "boolbase": "^1.0.0", "css-what": "^6.1.0", "domhandler": "^5.0.2", "domutils": "^3.0.1", "nth-check": "^2.0.1" } }, "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw=="], @@ -322,16 +374,20 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "data-uri-to-buffer": ["data-uri-to-buffer@6.0.2", "", {}, "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw=="], + "dayjs": ["dayjs@1.11.21", "", {}, "sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA=="], "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "deepmerge": ["deepmerge@4.3.1", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="], - "defu": ["defu@6.1.7", "", {}, "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="], + "degenerator": ["degenerator@5.0.1", "", { "dependencies": { "ast-types": "^0.13.4", "escodegen": "^2.1.0", "esprima": "^4.0.1" } }, "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ=="], "destr": ["destr@2.0.5", "", {}, "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA=="], + "devtools-protocol": ["devtools-protocol@0.0.1299070", "", {}, "sha512-+qtL3eX50qsJ7c+qVyagqi7AWMoQCBGNfoyJZMwm/NSXVqLYbuitrWEEIzxfUmTNy7//Xe8yhMmQ+elj3uAqSg=="], + "dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="], "domelementtype": ["domelementtype@2.3.0", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="], @@ -346,6 +402,8 @@ "encoding-sniffer": ["encoding-sniffer@0.2.1", "", { "dependencies": { "iconv-lite": "^0.6.3", "whatwg-encoding": "^3.1.1" } }, "sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw=="], + "end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="], + "entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="], "esbuild": ["esbuild@0.28.1", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.1", "@esbuild/android-arm": "0.28.1", "@esbuild/android-arm64": "0.28.1", "@esbuild/android-x64": "0.28.1", "@esbuild/darwin-arm64": "0.28.1", "@esbuild/darwin-x64": "0.28.1", "@esbuild/freebsd-arm64": "0.28.1", "@esbuild/freebsd-x64": "0.28.1", "@esbuild/linux-arm": "0.28.1", "@esbuild/linux-arm64": "0.28.1", "@esbuild/linux-ia32": "0.28.1", "@esbuild/linux-loong64": "0.28.1", "@esbuild/linux-mips64el": "0.28.1", "@esbuild/linux-ppc64": "0.28.1", "@esbuild/linux-riscv64": "0.28.1", "@esbuild/linux-s390x": "0.28.1", "@esbuild/linux-x64": "0.28.1", "@esbuild/netbsd-arm64": "0.28.1", "@esbuild/netbsd-x64": "0.28.1", "@esbuild/openbsd-arm64": "0.28.1", "@esbuild/openbsd-x64": "0.28.1", "@esbuild/openharmony-arm64": "0.28.1", "@esbuild/sunos-x64": "0.28.1", "@esbuild/win32-arm64": "0.28.1", "@esbuild/win32-ia32": "0.28.1", "@esbuild/win32-x64": "0.28.1" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw=="], @@ -354,14 +412,30 @@ "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], + "escodegen": ["escodegen@2.1.0", "", { "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", "esutils": "^2.0.2" }, "optionalDependencies": { "source-map": "~0.6.1" }, "bin": { "esgenerate": "bin/esgenerate.js", "escodegen": "bin/escodegen.js" } }, "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w=="], + + "esprima": ["esprima@4.0.1", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="], + + "estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="], + + "esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="], + + "events-universal": ["events-universal@1.0.1", "", { "dependencies": { "bare-events": "^2.7.0" } }, "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw=="], + "exact-mirror": ["exact-mirror@0.2.7", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-+MeEmDcLA4o/vjK2zujgk+1VTxPR4hdp23qLqkWfStbECtAq9gmsvQa3LW6z/0GXZyHJobrCnmy1cdeE7BjsYg=="], + "extract-zip": ["extract-zip@2.0.1", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="], + "fast-decode-uri-component": ["fast-decode-uri-component@1.0.1", "", {}, "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg=="], + "fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="], + "fast-xml-builder": ["fast-xml-builder@1.2.1", "", { "dependencies": { "path-expression-matcher": "^1.5.0", "xml-naming": "^0.1.0" } }, "sha512-tPb5TTWfgfVx5BNSi2xV0eLr89POeXXn0dXIsCJ9m1narrWxeIyx6je9d7Rce/3NyXLbvuQmLkxq+RuxMWejvw=="], "fast-xml-parser": ["fast-xml-parser@5.9.3", "", { "dependencies": { "@nodable/entities": "^2.2.0", "fast-xml-builder": "^1.2.0", "is-unsafe": "^1.0.1", "path-expression-matcher": "^1.5.0", "strnum": "^2.4.1", "xml-naming": "^0.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-brCNCeScma/kqa54J4PIDriSSSLssRkuYaUCpvHJulGc3HGI/xxKUCTDcYkAdqJsyb//ydpbxecjC3hB9+tb/g=="], + "fd-slicer": ["fd-slicer@1.1.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="], + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "feed": ["feed@5.2.1", "", { "dependencies": { "xml-js": "^1.6.11" } }, "sha512-jTynzYPWs9ALjro0GW8j7sv9y7cJBeOdD4Y88kVqYy/eyusIX3g+499JiTDIlD9Ge/unebx57T4Uzo6vpYvMtA=="], @@ -376,17 +450,25 @@ "get-east-asian-width": ["get-east-asian-width@1.6.0", "", {}, "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="], - "h3": ["h3@1.15.11", "", { "dependencies": { "cookie-es": "^1.2.3", "crossws": "^0.3.5", "defu": "^6.1.6", "destr": "^2.0.5", "iron-webcrypto": "^1.2.1", "node-mock-http": "^1.0.4", "radix3": "^1.1.2", "ufo": "^1.6.3", "uncrypto": "^0.1.3" } }, "sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg=="], + "get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="], + + "get-uri": ["get-uri@6.0.5", "", { "dependencies": { "basic-ftp": "^5.0.2", "data-uri-to-buffer": "^6.0.2", "debug": "^4.3.4" } }, "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg=="], "html-entities": ["html-entities@2.6.0", "", {}, "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ=="], "htmlparser2": ["htmlparser2@10.1.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.2.2", "entities": "^7.0.1" } }, "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ=="], + "http-proxy-agent": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="], + + "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + "iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], "ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], - "iron-webcrypto": ["iron-webcrypto@1.2.1", "", {}, "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg=="], + "ip-address": ["ip-address@10.2.0", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="], + + "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], "is-plain-object": ["is-plain-object@5.0.0", "", {}, "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q=="], @@ -410,19 +492,21 @@ "memoirist": ["memoirist@0.4.0", "", {}, "sha512-zxTgA0mSYELa66DimuNQDvyLq36AwDlTuVRbnQtB+VuTcKWm5Qc4z3WkSpgsFWHNhexqkIooqpv4hdcqrX5Nmg=="], + "mitt": ["mitt@3.0.1", "", {}, "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="], + "mlly": ["mlly@1.8.2", "", { "dependencies": { "acorn": "^8.16.0", "pathe": "^2.0.3", "pkg-types": "^1.3.1", "ufo": "^1.6.3" } }, "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA=="], + "modern-tar": ["modern-tar@0.7.6", "", {}, "sha512-sweCIVXzx1aIGTCdzcMlSZt1h8k5Tmk08VNAuRk3IU28XamGiOH5ypi11g6De2CH7PhYqSSnGy2A/EFhbWnVKg=="], + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="], "nanoid": ["nanoid@3.3.15", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA=="], - "node-fetch-native": ["node-fetch-native@1.6.7", "", {}, "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q=="], - - "node-mock-http": ["node-mock-http@1.0.4", "", {}, "sha512-8DY+kFsDkNXy1sJglUfuODx1/opAGJGyrTuFqEoN90oRc2Vk0ZbD4K2qmKXBBEhZQzdKHIVfEJpDU8Ak2NJEvQ=="], + "netmask": ["netmask@2.1.1", "", {}, "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA=="], - "normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="], + "node-fetch-native": ["node-fetch-native@1.6.7", "", {}, "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q=="], "nth-check": ["nth-check@2.1.1", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="], @@ -430,8 +514,14 @@ "ofetch": ["ofetch@1.5.1", "", { "dependencies": { "destr": "^2.0.5", "node-fetch-native": "^1.6.7", "ufo": "^1.6.1" } }, "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA=="], + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], + "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], + "pac-proxy-agent": ["pac-proxy-agent@7.2.0", "", { "dependencies": { "@tootallnate/quickjs-emscripten": "^0.23.0", "agent-base": "^7.1.2", "debug": "^4.3.4", "get-uri": "^6.0.1", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.6", "pac-resolver": "^7.0.1", "socks-proxy-agent": "^8.0.5" } }, "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA=="], + + "pac-resolver": ["pac-resolver@7.0.1", "", { "dependencies": { "degenerator": "^5.0.0", "netmask": "^2.0.2" } }, "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg=="], + "parse-srcset": ["parse-srcset@1.0.2", "", {}, "sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q=="], "parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="], @@ -444,9 +534,11 @@ "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + "pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="], + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], - "picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], "pirates": ["pirates@4.0.7", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="], @@ -456,9 +548,23 @@ "postcss-load-config": ["postcss-load-config@6.0.1", "", { "dependencies": { "lilconfig": "^3.1.1" }, "peerDependencies": { "jiti": ">=1.21.0", "postcss": ">=8.0.9", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["jiti", "postcss", "tsx", "yaml"] }, "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g=="], - "radix3": ["radix3@1.1.2", "", {}, "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA=="], + "progress": ["progress@2.0.3", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="], + + "proxy-agent": ["proxy-agent@6.5.0", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.6", "lru-cache": "^7.14.1", "pac-proxy-agent": "^7.1.0", "proxy-from-env": "^1.1.0", "socks-proxy-agent": "^8.0.5" } }, "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A=="], + + "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], + + "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], - "readdirp": ["readdirp@5.0.0", "", {}, "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ=="], + "puppeteer-core": ["puppeteer-core@25.3.0", "", { "dependencies": { "@puppeteer/browsers": "3.0.6", "chromium-bidi": "16.0.1", "devtools-protocol": "0.0.1638949", "typed-query-selector": "^2.12.2", "webdriver-bidi-protocol": "0.4.2", "ws": "^8.21.0" } }, "sha512-fm+wpUr2oigH1PXZvwgATrM2tYWHMDG8ASzTEe9uukCye4X5Ldx1K5BTHPFKITrIWvQQAQ256d1NpbEveBcKjA=="], + + "react": ["react@19.2.7", "", {}, "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ=="], + + "react-dom": ["react-dom@19.2.7", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.7" } }, "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ=="], + + "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + + "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], "resolve-from": ["resolve-from@5.0.0", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="], @@ -472,12 +578,24 @@ "sax": ["sax@1.6.0", "", {}, "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA=="], + "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], + + "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + + "smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="], + + "socks": ["socks@2.8.9", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw=="], + + "socks-proxy-agent": ["socks-proxy-agent@8.0.5", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" } }, "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw=="], + "source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], "srvx": ["srvx@0.11.21", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-GWTHjKMeekX8CwJf4VU9Oo6mJpSGaflGMddbCvR+Cmmh9sslRMiGbAoqqZacE0r1ncARh6buCEETr2W52F8b1w=="], + "streamx": ["streamx@2.28.0", "", { "dependencies": { "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" } }, "sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw=="], + "string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], "strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], @@ -488,10 +606,20 @@ "sucrase": ["sucrase@3.35.1", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", "tinyglobby": "^0.2.11", "ts-interface-checker": "^0.1.9" }, "bin": { "sucrase": "bin/sucrase", "sucrase-node": "bin/sucrase-node" } }, "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw=="], + "tar-fs": ["tar-fs@3.1.3", "", { "dependencies": { "pump": "^3.0.0", "tar-stream": "^3.1.5" }, "optionalDependencies": { "bare-fs": "^4.0.1", "bare-path": "^3.0.0" } }, "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ=="], + + "tar-stream": ["tar-stream@3.2.0", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg=="], + + "teex": ["teex@1.0.1", "", { "dependencies": { "streamx": "^2.12.5" } }, "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg=="], + + "text-decoder": ["text-decoder@1.2.7", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ=="], + "thenify": ["thenify@3.3.1", "", { "dependencies": { "any-promise": "^1.0.0" } }, "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw=="], "thenify-all": ["thenify-all@1.6.0", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="], + "through": ["through@2.3.8", "", {}, "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg=="], + "tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], @@ -508,30 +636,36 @@ "tsx": ["tsx@4.23.0", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-eUdUIaCr963q2h5u3+QwvYp0+eqPvn+egeqZUm0hwERCqqx1E3kK5ehbGCvqSE5MQAULr67ww0cA3jKc3YkM1w=="], + "typed-query-selector": ["typed-query-selector@2.12.2", "", {}, "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ=="], + "typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], "ufo": ["ufo@1.6.4", "", {}, "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA=="], "uint8array-extras": ["uint8array-extras@1.5.0", "", {}, "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A=="], - "uncrypto": ["uncrypto@0.1.3", "", {}, "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q=="], + "unbzip2-stream": ["unbzip2-stream@1.4.3", "", { "dependencies": { "buffer": "^5.2.1", "through": "^2.3.8" } }, "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg=="], "undici": ["undici@7.28.0", "", {}, "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA=="], "undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], - "unstorage": ["unstorage@1.17.5", "", { "dependencies": { "anymatch": "^3.1.3", "chokidar": "^5.0.0", "destr": "^2.0.5", "h3": "^1.15.10", "lru-cache": "^11.2.7", "node-fetch-native": "^1.6.7", "ofetch": "^1.5.1", "ufo": "^1.6.3" }, "peerDependencies": { "@azure/app-configuration": "^1.8.0", "@azure/cosmos": "^4.2.0", "@azure/data-tables": "^13.3.0", "@azure/identity": "^4.6.0", "@azure/keyvault-secrets": "^4.9.0", "@azure/storage-blob": "^12.26.0", "@capacitor/preferences": "^6 || ^7 || ^8", "@deno/kv": ">=0.9.0", "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0", "@planetscale/database": "^1.19.0", "@upstash/redis": "^1.34.3", "@vercel/blob": ">=0.27.1", "@vercel/functions": "^2.2.12 || ^3.0.0", "@vercel/kv": "^1 || ^2 || ^3", "aws4fetch": "^1.0.20", "db0": ">=0.2.1", "idb-keyval": "^6.2.1", "ioredis": "^5.4.2", "uploadthing": "^7.4.4" }, "optionalPeers": ["@azure/app-configuration", "@azure/cosmos", "@azure/data-tables", "@azure/identity", "@azure/keyvault-secrets", "@azure/storage-blob", "@capacitor/preferences", "@deno/kv", "@netlify/blobs", "@planetscale/database", "@upstash/redis", "@vercel/blob", "@vercel/functions", "@vercel/kv", "aws4fetch", "db0", "idb-keyval", "ioredis", "uploadthing"] }, "sha512-0i3iqvRfx29hkNntHyQvJTpf5W9dQ9ZadSoRU8+xVlhVtT7jAX57fazYO9EHvcRCfBCyi5YRya7XCDOsbTgkPg=="], - "utils-feed-helper": ["utils-feed-helper@workspace:pkgs/utils-feed-helper"], "uuid": ["uuid@13.0.2", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-vzi9uRZ926x4XV73S/4qQaTwPXM2JBj6/6lI/byHH1jOpCzb0zDbfytgA9LcN/hzb2l7WQSQnxITOVx5un/wGw=="], + "webdriver-bidi-protocol": ["webdriver-bidi-protocol@0.4.2", "", {}, "sha512-VSV+fzfChirL3e7jay2yUC7B4HQCGtEWEg/MSSQbK+qWbqeGlRLlXTzPpYr3XGUvbpDHumWZBJxgesg4N7dbtA=="], + "whatwg-encoding": ["whatwg-encoding@3.1.1", "", { "dependencies": { "iconv-lite": "0.6.3" } }, "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ=="], "whatwg-mimetype": ["whatwg-mimetype@4.0.0", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="], "wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="], + "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], + + "ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], + "xml-js": ["xml-js@1.6.11", "", { "dependencies": { "sax": "^1.2.4" }, "bin": { "xml-js": "./bin/cli.js" } }, "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g=="], "xml-naming": ["xml-naming@0.1.0", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="], @@ -542,21 +676,31 @@ "yargs-parser": ["yargs-parser@22.0.0", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="], - "dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], + "yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="], + + "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], - "fdir/picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + "@puppeteer/browsers/yargs": ["yargs@17.7.3", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="], - "h3/crossws": ["crossws@0.3.5", "", { "dependencies": { "uncrypto": "^0.1.3" } }, "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA=="], + "dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], + + "escodegen/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], "parse5/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], - "tinyglobby/picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + "proxy-agent/lru-cache": ["lru-cache@7.18.3", "", {}, "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA=="], + + "puppeteer-core/@puppeteer/browsers": ["@puppeteer/browsers@3.0.6", "", { "dependencies": { "modern-tar": "^0.7.6", "yargs": "^18.0.0" }, "peerDependencies": { "proxy-agent": ">=8.0.1", "yauzl": "^2.10.0 || ^3.4.0" }, "optionalPeers": ["proxy-agent", "yauzl"], "bin": { "browsers": "lib/main-cli.js" } }, "sha512-B/gKoqlFkzhvzsI6jo9K1cZz9o5ypviVv/xu8CwA4grZzyVwN+XfkT+tu8T1zrauuEXv6VhS2oGX+6NL95WcKA=="], - "tsup/chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + "puppeteer-core/devtools-protocol": ["devtools-protocol@0.0.1638949", "", {}, "sha512-mXwg4Fqnv0WR4iuAT/gYUmctNkjILwXFHyZ+m7Ty1dfr0ezZt2U3gnrrJTfRobJTHoXf+IbuFvFITzLrLFjwJA=="], "tsup/esbuild": ["esbuild@0.27.7", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.7", "@esbuild/android-arm": "0.27.7", "@esbuild/android-arm64": "0.27.7", "@esbuild/android-x64": "0.27.7", "@esbuild/darwin-arm64": "0.27.7", "@esbuild/darwin-x64": "0.27.7", "@esbuild/freebsd-arm64": "0.27.7", "@esbuild/freebsd-x64": "0.27.7", "@esbuild/linux-arm": "0.27.7", "@esbuild/linux-arm64": "0.27.7", "@esbuild/linux-ia32": "0.27.7", "@esbuild/linux-loong64": "0.27.7", "@esbuild/linux-mips64el": "0.27.7", "@esbuild/linux-ppc64": "0.27.7", "@esbuild/linux-riscv64": "0.27.7", "@esbuild/linux-s390x": "0.27.7", "@esbuild/linux-x64": "0.27.7", "@esbuild/netbsd-arm64": "0.27.7", "@esbuild/netbsd-x64": "0.27.7", "@esbuild/openbsd-arm64": "0.27.7", "@esbuild/openbsd-x64": "0.27.7", "@esbuild/openharmony-arm64": "0.27.7", "@esbuild/sunos-x64": "0.27.7", "@esbuild/win32-arm64": "0.27.7", "@esbuild/win32-ia32": "0.27.7", "@esbuild/win32-x64": "0.27.7" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w=="], - "tsup/chokidar/readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + "@puppeteer/browsers/yargs/cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], + + "@puppeteer/browsers/yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "@puppeteer/browsers/yargs/yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], "tsup/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="], @@ -609,5 +753,19 @@ "tsup/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.27.7", "", { "os": "win32", "cpu": "ia32" }, "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw=="], "tsup/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.7", "", { "os": "win32", "cpu": "x64" }, "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg=="], + + "@puppeteer/browsers/yargs/cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "@puppeteer/browsers/yargs/cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], + + "@puppeteer/browsers/yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "@puppeteer/browsers/yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "@puppeteer/browsers/yargs/cliui/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "@puppeteer/browsers/yargs/cliui/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "@puppeteer/browsers/yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], } } diff --git a/package.json b/package.json index 73318be..097c5cf 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,6 @@ "sanitize-html": "^2.17.5", "tsup": "^8.5.1", "tsx": "latest", - "unstorage": "1.17.5", "uuid": "^13.0.2" }, "devDependencies": { diff --git a/pkgs/rssbook/package.json b/pkgs/rssbook/package.json index 95f3ff4..62f3da3 100644 --- a/pkgs/rssbook/package.json +++ b/pkgs/rssbook/package.json @@ -16,9 +16,10 @@ "domhandler": "^5.0.3", "elysia": "^1.4.29", "feed": "^5.2.1", + "lru-cache": "^11.5.1", "ofetch": "^1.5.1", + "puppeteer-core": "^25.3.0", "sanitize-html": "^2.17.5", - "unstorage": "1.17.5", "uuid": "^13.0.2" }, "devDependencies": { @@ -50,5 +51,5 @@ }, "type": "module", "types": "./dist/index.d.ts", - "version": "1.1.1" + "version": "1.2.0" } diff --git a/pkgs/rssbook/src/app.ts b/pkgs/rssbook/src/app.ts index 6a0f4b1..2aab758 100644 --- a/pkgs/rssbook/src/app.ts +++ b/pkgs/rssbook/src/app.ts @@ -2,6 +2,7 @@ import { serverTiming } from "@elysiajs/server-timing"; import { Elysia, type ElysiaAdapter } from "elysia"; import { bookPlugin } from "@/books"; import type { ThemeName } from "@/books/themes"; +import type { Browser } from "@/browser"; import { assetsPlugin, errorHandlerPlugin, @@ -99,6 +100,15 @@ const RSSBOOK_APP_ENV = { */ export interface RSSBookAppConfig { adapter?: ElysiaAdapter; + /** + * Browser capability for feed routes that declare `browser: true`. + * + * `undefined` behaves like `true` and creates a lazy local Puppeteer Core + * browser using `PUPPETEER_EXECUTABLE_PATH` or the installed stable Chrome. + * `false` disables browser routes. Pass a `Browser` instance for CDP + * services or Puppeteer-compatible serverless SDKs. + */ + browser?: boolean | Browser; book?: RSSBookBookConfig; cache?: Cache; openapi?: { @@ -261,7 +271,7 @@ export const createRSSBookApp = (init?: RSSBookAppConfig) => { .use(openAPIPlugin(config.openapi?.enableFetchOnlineServer)) // init RSSBook instance - .use(initPlugin({ book: config.book, cache: config.cache })) + .use(initPlugin({ book: config.book, browser: config.browser, cache: config.cache })) // book plugin .use(bookPlugin) // sign routes plugin diff --git a/pkgs/rssbook/src/books/index.test.ts b/pkgs/rssbook/src/books/index.test.ts index 60b98a4..d58f154 100644 --- a/pkgs/rssbook/src/books/index.test.ts +++ b/pkgs/rssbook/src/books/index.test.ts @@ -1,8 +1,6 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; -import { createStorage } from "unstorage"; -import lruCacheDriver from "unstorage/drivers/lru-cache"; import { getCachedBooksData } from "@/books"; -import Cache from "@/utils/cache"; +import { MemoryCache } from "@/cache"; let server: ReturnType | null = null; let baseUrl = ""; @@ -18,13 +16,7 @@ let feedB = ""; let invalidFeed = "not xml"; function createCache() { - return new Cache( - createStorage({ - driver: lruCacheDriver({ - ttl: 7 * 24 * 60 * 60 * 1000, - }), - }), - ); + return new MemoryCache({ defaultMaxAgeMs: 7 * 24 * 60 * 60 * 1000 }); } function resetFeeds() { diff --git a/pkgs/rssbook/src/books/index.ts b/pkgs/rssbook/src/books/index.ts index b094d10..5340afd 100644 --- a/pkgs/rssbook/src/books/index.ts +++ b/pkgs/rssbook/src/books/index.ts @@ -9,6 +9,7 @@ import { type ThemeProps, } from "@/types"; import { type Cache, filter, logger, ofetch, parse, render, sort, union, uuid } from "@/utils"; +import { DataValidationError, SourceFetchError } from "@/utils/error"; const DEFAULT_META: ThemeProps["meta"] = { atomFeed: "/books/atom", @@ -119,7 +120,7 @@ function encodeCachedBooksData(data: CachedBooksData): string { function decodeCachedBooksData(data: string): CachedBooksData { const parsed: unknown = JSON.parse(data, reviveBooksDate); if (!isRecord(parsed)) { - throw new Error("Invalid cached books data"); + throw new DataValidationError("Invalid cached books data"); } return { @@ -132,7 +133,7 @@ async function refreshBooksData(feeds: string[], cache: Cache, lastSuccessKey: s const rawData = await getAllFeedData(feeds); if (rawData === null) { - throw new Error("Unable to fetch or parse any configured books feeds"); + throw new SourceFetchError("Unable to fetch or parse any configured books feeds"); } const processedData = processBooksData(rawData); @@ -162,7 +163,7 @@ export async function getCachedBooksData( return decodeCachedBooksData(data); } catch (error) { const fallback = await cache.get(lastSuccess); - if (fallback !== null) { + if (fallback !== undefined) { logger.error("Failed to refresh books cache; using last successful data", error); return decodeCachedBooksData(fallback); } diff --git a/pkgs/rssbook/src/books/magazine/home/components/content/Featured.tsx b/pkgs/rssbook/src/books/magazine/home/components/content/Featured.tsx index 88d0feb..07f3ad0 100644 --- a/pkgs/rssbook/src/books/magazine/home/components/content/Featured.tsx +++ b/pkgs/rssbook/src/books/magazine/home/components/content/Featured.tsx @@ -1,5 +1,5 @@ import type { DataItem } from "@/types"; -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface FeaturedProps { diff --git a/pkgs/rssbook/src/books/magazine/home/components/content/Item.tsx b/pkgs/rssbook/src/books/magazine/home/components/content/Item.tsx index d020d8d..de305b5 100644 --- a/pkgs/rssbook/src/books/magazine/home/components/content/Item.tsx +++ b/pkgs/rssbook/src/books/magazine/home/components/content/Item.tsx @@ -1,5 +1,5 @@ import type { DataItem } from "@/types"; -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface ItemProps { diff --git a/pkgs/rssbook/src/books/magazine/home/components/layout/Footer.tsx b/pkgs/rssbook/src/books/magazine/home/components/layout/Footer.tsx index 2283880..3751f50 100644 --- a/pkgs/rssbook/src/books/magazine/home/components/layout/Footer.tsx +++ b/pkgs/rssbook/src/books/magazine/home/components/layout/Footer.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface FooterProps { diff --git a/pkgs/rssbook/src/books/magazine/home/components/layout/Nav.tsx b/pkgs/rssbook/src/books/magazine/home/components/layout/Nav.tsx index 511ee32..562899f 100644 --- a/pkgs/rssbook/src/books/magazine/home/components/layout/Nav.tsx +++ b/pkgs/rssbook/src/books/magazine/home/components/layout/Nav.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface NavProps { diff --git a/pkgs/rssbook/src/books/masonry/home/components/content/Item.tsx b/pkgs/rssbook/src/books/masonry/home/components/content/Item.tsx index 75b8734..7dc924b 100644 --- a/pkgs/rssbook/src/books/masonry/home/components/content/Item.tsx +++ b/pkgs/rssbook/src/books/masonry/home/components/content/Item.tsx @@ -1,5 +1,5 @@ import type { DataItem } from "@/types"; -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface ItemProps { diff --git a/pkgs/rssbook/src/books/masonry/home/components/layout/Footer.tsx b/pkgs/rssbook/src/books/masonry/home/components/layout/Footer.tsx index 7180587..17cfc21 100644 --- a/pkgs/rssbook/src/books/masonry/home/components/layout/Footer.tsx +++ b/pkgs/rssbook/src/books/masonry/home/components/layout/Footer.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface FooterProps { diff --git a/pkgs/rssbook/src/books/masonry/home/components/layout/Nav.tsx b/pkgs/rssbook/src/books/masonry/home/components/layout/Nav.tsx index 6fb601f..fad8647 100644 --- a/pkgs/rssbook/src/books/masonry/home/components/layout/Nav.tsx +++ b/pkgs/rssbook/src/books/masonry/home/components/layout/Nav.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface NavProps { diff --git a/pkgs/rssbook/src/books/minimal/home/components/content/Item.tsx b/pkgs/rssbook/src/books/minimal/home/components/content/Item.tsx index 0508a10..6cd532e 100644 --- a/pkgs/rssbook/src/books/minimal/home/components/content/Item.tsx +++ b/pkgs/rssbook/src/books/minimal/home/components/content/Item.tsx @@ -1,5 +1,5 @@ import type { DataItem } from "@/types"; -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface Item { diff --git a/pkgs/rssbook/src/books/minimal/home/components/layout/Footer.tsx b/pkgs/rssbook/src/books/minimal/home/components/layout/Footer.tsx index 0427ade..edbf392 100644 --- a/pkgs/rssbook/src/books/minimal/home/components/layout/Footer.tsx +++ b/pkgs/rssbook/src/books/minimal/home/components/layout/Footer.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface FooterProps { diff --git a/pkgs/rssbook/src/books/minimal/home/components/layout/Nav.tsx b/pkgs/rssbook/src/books/minimal/home/components/layout/Nav.tsx index 530e9ba..29ea92a 100644 --- a/pkgs/rssbook/src/books/minimal/home/components/layout/Nav.tsx +++ b/pkgs/rssbook/src/books/minimal/home/components/layout/Nav.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface NavProps { diff --git a/pkgs/rssbook/src/books/reader/home/components/content/Item.tsx b/pkgs/rssbook/src/books/reader/home/components/content/Item.tsx index 06ce1b2..96b402d 100644 --- a/pkgs/rssbook/src/books/reader/home/components/content/Item.tsx +++ b/pkgs/rssbook/src/books/reader/home/components/content/Item.tsx @@ -1,5 +1,5 @@ import type { DataItem } from "@/types"; -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface ItemProps { diff --git a/pkgs/rssbook/src/books/reader/home/components/layout/Footer.tsx b/pkgs/rssbook/src/books/reader/home/components/layout/Footer.tsx index d3945fc..10ee655 100644 --- a/pkgs/rssbook/src/books/reader/home/components/layout/Footer.tsx +++ b/pkgs/rssbook/src/books/reader/home/components/layout/Footer.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface FooterProps { diff --git a/pkgs/rssbook/src/books/redbook/home/components/content/Item.tsx b/pkgs/rssbook/src/books/redbook/home/components/content/Item.tsx index 9dfb09f..49b7959 100644 --- a/pkgs/rssbook/src/books/redbook/home/components/content/Item.tsx +++ b/pkgs/rssbook/src/books/redbook/home/components/content/Item.tsx @@ -1,5 +1,5 @@ import type { DataItem } from "@/types"; -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface Item { diff --git a/pkgs/rssbook/src/books/redbook/home/components/layout/Footer.tsx b/pkgs/rssbook/src/books/redbook/home/components/layout/Footer.tsx index 37776d1..998773c 100644 --- a/pkgs/rssbook/src/books/redbook/home/components/layout/Footer.tsx +++ b/pkgs/rssbook/src/books/redbook/home/components/layout/Footer.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface FooterProps { diff --git a/pkgs/rssbook/src/books/redbook/home/components/layout/Nav.tsx b/pkgs/rssbook/src/books/redbook/home/components/layout/Nav.tsx index c07e477..6e232f9 100644 --- a/pkgs/rssbook/src/books/redbook/home/components/layout/Nav.tsx +++ b/pkgs/rssbook/src/books/redbook/home/components/layout/Nav.tsx @@ -1,4 +1,4 @@ -import { formatHTML } from "@/utils"; +import { formatHTML } from "@/utils/formatHTML"; import type { Translations } from "../../i18n"; interface NavProps { diff --git a/pkgs/rssbook/src/browser/browser.test.ts b/pkgs/rssbook/src/browser/browser.test.ts new file mode 100644 index 0000000..2fc069b --- /dev/null +++ b/pkgs/rssbook/src/browser/browser.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, mock, test } from "bun:test"; +import type { Browser as PuppeteerBrowser } from "puppeteer-core"; +import { BrowserClosedError } from "@/utils/error"; +import { Browser } from "./browser"; +import { + createFakePage, + createFakePuppeteerBrowser, + createFakeTarget, + emitContextTarget, + tick, +} from "./test-helpers"; + +describe("Browser", () => { + test("enforces Browser and Context capacity and wakes FIFO waiters", async () => { + const browser = createTestBrowser(2, 1, 1); + const first = await browser.acquireContext(); + const second = await browser.acquireContext(); + expect(browser.created).toHaveLength(2); + + const order: number[] = []; + const thirdPromise = browser.acquireContext().then((lease) => { + order.push(3); + return lease; + }); + const fourthPromise = browser.acquireContext().then((lease) => { + order.push(4); + return lease; + }); + await tick(); + expect(order).toEqual([]); + + await first.close(); + const third = await thirdPromise; + expect(order[0]).toBe(3); + await second.close(); + const fourth = await fourthPromise; + expect(order).toEqual([3, 4]); + + await third.close(); + await fourth.close(); + await browser.deinit(); + }); + + test("enforces Page capacity within one Context", async () => { + const browser = createTestBrowser(1, 1, 1); + const context = await browser.acquireContext(); + const first = await context.acquirePage(); + let acquired = false; + const secondPromise = context.acquirePage().then((lease) => { + acquired = true; + return lease; + }); + await tick(); + expect(acquired).toBeFalse(); + + await first.close(); + const second = await secondPromise; + expect(acquired).toBeTrue(); + await second.close(); + await context.close(); + await browser.deinit(); + }); + + test("releases a Page reservation when newPage fails", async () => { + const browser = createTestBrowser(1, 1, 1); + const context = await browser.acquireContext(); + const createPage = context.context.newPage.bind(context.context); + let attempts = 0; + context.context.newPage = mock(async () => { + attempts += 1; + if (attempts === 1) throw new Error("target failed"); + return createPage(); + }); + + await expect(context.acquirePage()).rejects.toThrow("target failed"); + const page = await context.acquirePage(); + expect(attempts).toBe(2); + await page.close(); + await context.close(); + await browser.deinit(); + }); + + test("closes popups that exceed Page capacity", async () => { + const browser = createTestBrowser(1, 1, 1); + const context = await browser.acquireContext(); + const page = await context.acquirePage(); + const popup = createFakePage(); + emitContextTarget(context.context, "targetcreated", createFakeTarget(popup)); + await tick(); + expect(popup.close).toHaveBeenCalledTimes(1); + + await page.close(); + await context.close(); + await browser.deinit(); + }); + + test("supports aborting a queued acquisition", async () => { + const browser = createTestBrowser(1, 1, 1); + const context = await browser.acquireContext(); + const controller = new AbortController(); + const waiting = browser.acquireContext({ signal: controller.signal }); + controller.abort(new Error("cancelled")); + await expect(waiting).rejects.toThrow("cancelled"); + await context.close(); + await browser.deinit(); + }); + + test("acquirePage releases its private Context when Page closes externally", async () => { + const browser = createTestBrowser(1, 1, 1); + const first = await browser.acquirePage(); + await first.page.close(); + await tick(); + + const second = await browser.acquirePage(); + await second.close(); + await browser.deinit(); + }); + + test("does not initialize an unused pool during deinit", async () => { + const browser = createTestBrowser(1, 1, 1); + await browser.deinit(); + expect(browser.created).toHaveLength(0); + await expect(browser.acquireContext()).rejects.toBeInstanceOf(BrowserClosedError); + }); + + test("replaces a disconnected physical Browser", async () => { + const browser = createTestBrowser(1, 1, 1); + const first = await browser.acquireContext(); + browser.created[0]?.disconnect(); + await tick(); + const second = await browser.acquireContext(); + expect(browser.created).toHaveLength(2); + await first.close(); + await second.close(); + await browser.deinit(); + }); + + test("validates direct capacity props", () => { + expect(() => createTestBrowser(0, 1, 1)).toThrow("maxBrowsers"); + expect(() => createTestBrowser(1, 0, 1)).toThrow("maxContextsPerBrowser"); + expect(() => createTestBrowser(1, 1, 0)).toThrow("maxPagesPerContext"); + }); +}); + +class TestBrowser extends Browser { + public readonly created: ReturnType[] = []; + + protected createBrowser(): Promise { + const fake = createFakePuppeteerBrowser(); + this.created.push(fake); + return Promise.resolve(fake.browser); + } +} + +function createTestBrowser( + maxBrowsers: number, + maxContextsPerBrowser: number, + maxPagesPerContext: number, +): TestBrowser { + return new TestBrowser({ maxBrowsers, maxContextsPerBrowser, maxPagesPerContext }); +} diff --git a/pkgs/rssbook/src/browser/browser.ts b/pkgs/rssbook/src/browser/browser.ts new file mode 100644 index 0000000..fa491f2 --- /dev/null +++ b/pkgs/rssbook/src/browser/browser.ts @@ -0,0 +1,459 @@ +import type { BrowserContext, Browser as PuppeteerBrowser, Target } from "puppeteer-core"; +import type { Awaitable } from "@/types/utils"; +import { BrowserClosedError, BrowserInitializationError } from "@/utils/error"; +import { logger } from "@/utils/logger"; +import { BrowserContextLease, BrowserPageLease } from "./lease"; + +export interface BrowserConcurrencyOptions { + /** Maximum number of physical browser processes or remote sessions. */ + maxBrowsers?: number; + /** Maximum number of isolated contexts managed in each physical browser. */ + maxContextsPerBrowser?: number; + /** Maximum number of tracked pages, including popups, in each context. */ + maxPagesPerContext?: number; +} + +export interface BrowserAcquireOptions { + /** Cancels an acquisition while it is waiting for pool capacity. */ + signal?: AbortSignal; +} + +interface BrowserSlot { + browser?: PuppeteerBrowser; + contexts: Set; + contextReservations: number; + disconnected: boolean; + opening?: Promise; +} + +interface ContextSlot { + browserSlot: BrowserSlot; + closing: boolean; + context: BrowserContext; + expectedPageTargets: number; + lease?: BrowserContextLease; + managedTargets: Set; + pageLeases: Set; + pageReservations: number; + unmanagedTargets: Set; +} + +interface CapacityWaiter { + onAbort?: () => void; + reject: (reason?: unknown) => void; + resolve: () => void; + signal?: AbortSignal; +} + +/** + * App-scoped Puppeteer browser pool. + * + * Concrete providers only create and close physical browsers. This base class + * owns Browser, BrowserContext, and Page concurrency and lifecycle. A route + * must close every acquired lease; application shutdown only provides a final + * cleanup boundary. + * + * `acquirePage()` creates an isolated context for one page, so its effective + * concurrency is bounded by both context and page capacity. Use + * `acquireContext()` when several pages need to share cookies or other context + * state, then keep concurrent page leases within `maxPagesPerContext`. + */ +export abstract class Browser { + /** Maximum number of physical browser processes or remote sessions. */ + public readonly maxBrowsers: number; + /** Maximum number of isolated contexts in one physical browser. */ + public readonly maxContextsPerBrowser: number; + /** Maximum number of tracked pages, including popups, in one context. */ + public readonly maxPagesPerContext: number; + + private readonly browserSlots: BrowserSlot[] = []; + private closed = false; + private deinitializing?: Promise; + private readonly waiters: CapacityWaiter[] = []; + + /** Configure the fixed capacity limits enforced by this pool. */ + public constructor(options: BrowserConcurrencyOptions) { + this.maxBrowsers = validateCapacity("maxBrowsers", options.maxBrowsers ?? 1); + this.maxContextsPerBrowser = validateCapacity( + "maxContextsPerBrowser", + options.maxContextsPerBrowser ?? 1, + ); + this.maxPagesPerContext = validateCapacity( + "maxPagesPerContext", + options.maxPagesPerContext ?? 1, + ); + } + + /** + * Create one physical Puppeteer-compatible browser. + * + * Providers should create a new local process or remote session on every + * call. The pool invokes this method lazily as demand reaches new slots. + */ + protected abstract createBrowser(): Awaitable; + + /** + * Release one physical browser. + * + * Providers that do not own the remote session may override this method and + * disconnect instead of closing it. + */ + protected async closeBrowser(browser: PuppeteerBrowser): Promise { + await browser.close(); + } + + /** + * Warm one physical browser slot. + * + * Calling this method is optional because acquisitions initialize the pool + * lazily. It never fills every configured browser slot eagerly. + */ + public async init(): Promise { + this.assertOpen(); + const slot = this.browserSlots.find((candidate) => !candidate.disconnected); + await this.resolveBrowser(slot ?? this.createBrowserSlot()); + } + + /** + * Acquire an isolated BrowserContext lease from the pool. + * + * Pages acquired from the returned lease share cookies, local storage, and + * other context state. Close the lease in `finally`; closing it also closes + * its outstanding pages and returns context capacity to the pool. + */ + public async acquireContext(options: BrowserAcquireOptions = {}): Promise { + for (;;) { + this.assertOpen(); + options.signal?.throwIfAborted(); + this.pruneClosedContexts(); + + const browserSlot = this.reserveBrowserContext(); + if (!browserSlot) { + await this.waitForCapacity(options.signal); + continue; + } + + let context: BrowserContext | undefined; + try { + const browser = await this.resolveBrowser(browserSlot); + this.assertOpen(); + if (browserSlot.disconnected) continue; + + context = await browser.createBrowserContext(); + this.assertOpen(); + + const contextSlot: ContextSlot = { + browserSlot, + closing: false, + context, + expectedPageTargets: 0, + managedTargets: new Set(), + pageLeases: new Set(), + pageReservations: 0, + unmanagedTargets: new Set(), + }; + const lease = new BrowserContextLease( + context, + (acquireOptions) => this.acquirePageInContext(contextSlot, acquireOptions), + () => this.closeContext(contextSlot), + ); + contextSlot.lease = lease; + browserSlot.contexts.add(contextSlot); + this.observeContextTargets(contextSlot); + return lease; + } catch (error) { + if (context && !context.closed) await context.close().catch(() => {}); + throw error; + } finally { + browserSlot.contextReservations -= 1; + this.notifyCapacity(); + } + } + } + + /** + * Acquire one Page in its own isolated BrowserContext. + * + * Close the returned lease in `finally`. Releasing the page also closes its + * private context, which prevents cookies and storage leaking between route + * executions. + */ + public async acquirePage(options: BrowserAcquireOptions = {}): Promise { + const contextLease = await this.acquireContext(options); + try { + const pageLease = await contextLease.acquirePage(options); + return pageLease.closeContextOnRelease(() => contextLease.close()); + } catch (error) { + await contextLease.close().catch(() => {}); + throw error; + } + } + + /** + * Reject pending acquisitions and close all contexts and physical browsers. + * + * Deinitialization is idempotent and does not initialize an unused pool. + * RSSBook calls it automatically when the application stops. + */ + public async deinit(): Promise { + if (this.deinitializing) return this.deinitializing; + + this.closed = true; + this.rejectWaiters(new BrowserClosedError()); + this.deinitializing = (async () => { + const slots = [...this.browserSlots]; + const contextResults = await Promise.allSettled( + slots.flatMap((slot) => [...slot.contexts].map((context) => context.lease?.close())), + ); + const browsers = await Promise.allSettled(slots.map((slot) => this.resolveBrowser(slot))); + const closeResults = await Promise.allSettled( + browsers.flatMap((result) => + result.status === "fulfilled" ? [this.closePhysicalBrowser(result.value)] : [], + ), + ); + + this.browserSlots.length = 0; + const failed = [...contextResults, ...closeResults].find( + (result) => result.status === "rejected", + ); + if (failed?.status === "rejected") throw failed.reason; + })(); + + return this.deinitializing; + } + + /** Deinitialize the pool when used with `await using`. */ + public async [Symbol.asyncDispose](): Promise { + await this.deinit(); + } + + private async acquirePageInContext( + contextSlot: ContextSlot, + options: BrowserAcquireOptions, + ): Promise { + for (;;) { + this.assertOpen(); + options.signal?.throwIfAborted(); + if (contextSlot.closing || contextSlot.context.closed) { + throw new BrowserClosedError(); + } + + if (this.contextPageCount(contextSlot) >= this.maxPagesPerContext) { + await this.waitForCapacity(options.signal); + continue; + } + + contextSlot.pageReservations += 1; + contextSlot.expectedPageTargets += 1; + let acquired = false; + try { + const page = await contextSlot.context.newPage(); + acquired = true; + const target = page.target(); + contextSlot.managedTargets.add(target); + if (contextSlot.expectedPageTargets > 0) contextSlot.expectedPageTargets -= 1; + + let lease: BrowserPageLease; + lease = new BrowserPageLease(page, contextSlot.context, () => { + contextSlot.pageLeases.delete(lease); + contextSlot.managedTargets.delete(target); + this.notifyCapacity(); + }); + contextSlot.pageLeases.add(lease); + page.once("close", () => void lease.release()); + return lease; + } finally { + if (!acquired && contextSlot.expectedPageTargets > 0) { + contextSlot.expectedPageTargets -= 1; + } + contextSlot.pageReservations -= 1; + this.notifyCapacity(); + } + } + } + + private async closeContext(contextSlot: ContextSlot): Promise { + if (contextSlot.closing) return; + contextSlot.closing = true; + + try { + await Promise.allSettled([...contextSlot.pageLeases].map((lease) => lease.close())); + if (!contextSlot.context.closed) await contextSlot.context.close(); + } finally { + contextSlot.browserSlot.contexts.delete(contextSlot); + contextSlot.pageLeases.clear(); + contextSlot.managedTargets.clear(); + contextSlot.unmanagedTargets.clear(); + this.notifyCapacity(); + } + } + + private closePhysicalBrowser(browser: PuppeteerBrowser): Promise { + logger.info("[Browser] Deinitializing Puppeteer browser."); + return Promise.resolve(this.closeBrowser(browser)); + } + + private contextPageCount(contextSlot: ContextSlot): number { + return ( + contextSlot.pageLeases.size + contextSlot.pageReservations + contextSlot.unmanagedTargets.size + ); + } + + private createBrowserSlot(): BrowserSlot { + const slot: BrowserSlot = { + contextReservations: 0, + contexts: new Set(), + disconnected: false, + }; + this.browserSlots.push(slot); + return slot; + } + + private async openBrowser(slot: BrowserSlot): Promise { + logger.info("[Browser] Initializing Puppeteer browser."); + try { + const browser = await this.createBrowser(); + if (!isPuppeteerBrowser(browser)) { + throw new BrowserInitializationError( + "Browser provider must create a Puppeteer-compatible Browser.", + ); + } + + slot.browser = browser; + browser.once("disconnected", () => this.handleBrowserDisconnected(slot)); + logger.info("[Browser] Puppeteer browser is ready."); + return browser; + } catch (error) { + this.removeBrowserSlot(slot); + throw error; + } finally { + slot.opening = undefined; + this.notifyCapacity(); + } + } + + private handleBrowserDisconnected(slot: BrowserSlot): void { + slot.disconnected = true; + this.removeBrowserSlot(slot); + for (const context of slot.contexts) void context.lease?.close().catch(() => {}); + this.notifyCapacity(); + } + + private notifyCapacity(): void { + for (const waiter of this.waiters.splice(0)) { + if (waiter.onAbort && waiter.signal) { + waiter.signal.removeEventListener("abort", waiter.onAbort); + } + waiter.resolve(); + } + } + + private observeContextTargets(contextSlot: ContextSlot): void { + contextSlot.context.on("targetcreated", (target) => { + if (target.type() !== "page") return; + if (contextSlot.expectedPageTargets > 0) { + contextSlot.expectedPageTargets -= 1; + contextSlot.managedTargets.add(target); + return; + } + + contextSlot.unmanagedTargets.add(target); + if (this.contextPageCount(contextSlot) > this.maxPagesPerContext) { + void target + .page() + .then((page) => page?.close()) + .catch(() => {}); + } + }); + contextSlot.context.on("targetdestroyed", (target) => { + if (contextSlot.unmanagedTargets.delete(target)) this.notifyCapacity(); + }); + } + + private pruneClosedContexts(): void { + for (const slot of this.browserSlots) { + for (const context of slot.contexts) { + if (context.context.closed) void context.lease?.close().catch(() => {}); + } + } + } + + private rejectWaiters(reason: unknown): void { + for (const waiter of this.waiters.splice(0)) { + if (waiter.onAbort && waiter.signal) { + waiter.signal.removeEventListener("abort", waiter.onAbort); + } + waiter.reject(reason); + } + } + + private removeBrowserSlot(slot: BrowserSlot): void { + const index = this.browserSlots.indexOf(slot); + if (index >= 0) this.browserSlots.splice(index, 1); + } + + private reserveBrowserContext(): BrowserSlot | undefined { + let slot = this.browserSlots + .filter( + (candidate) => + !candidate.disconnected && + candidate.contexts.size + candidate.contextReservations < this.maxContextsPerBrowser, + ) + .sort( + (left, right) => + left.contexts.size + + left.contextReservations - + (right.contexts.size + right.contextReservations), + )[0]; + + if (!slot && this.browserSlots.length < this.maxBrowsers) { + slot = this.createBrowserSlot(); + } + if (slot) slot.contextReservations += 1; + return slot; + } + + private async resolveBrowser(slot: BrowserSlot): Promise { + if (slot.browser) return slot.browser; + if (!slot.opening) slot.opening = this.openBrowser(slot); + return slot.opening; + } + + private waitForCapacity(signal?: AbortSignal): Promise { + signal?.throwIfAborted(); + return new Promise((resolve, reject) => { + const waiter: CapacityWaiter = { reject, resolve, signal }; + if (signal) { + waiter.onAbort = () => { + const index = this.waiters.indexOf(waiter); + if (index >= 0) this.waiters.splice(index, 1); + reject(signal.reason); + }; + signal.addEventListener("abort", waiter.onAbort, { once: true }); + } + this.waiters.push(waiter); + }); + } + + private assertOpen(): void { + if (this.closed) throw new BrowserClosedError(); + } +} + +function isPuppeteerBrowser(value: unknown): value is PuppeteerBrowser { + if (typeof value !== "object" || value === null) return false; + + return ( + typeof Reflect.get(value, "close") === "function" && + typeof Reflect.get(value, "createBrowserContext") === "function" && + typeof Reflect.get(value, "newPage") === "function" && + typeof Reflect.get(value, "once") === "function" + ); +} + +function validateCapacity(name: string, value: number): number { + if (!Number.isInteger(value) || value < 1) { + throw new RangeError(`${name} must be a positive integer.`); + } + return value; +} diff --git a/pkgs/rssbook/src/browser/cdp.test.ts b/pkgs/rssbook/src/browser/cdp.test.ts new file mode 100644 index 0000000..9d52678 --- /dev/null +++ b/pkgs/rssbook/src/browser/cdp.test.ts @@ -0,0 +1,69 @@ +import { afterEach, describe, expect, mock, test } from "bun:test"; +import { CDPBrowser } from "./cdp"; +import { puppeteerCalls, remotePuppeteer } from "./test-helpers"; + +const originalFetch = globalThis.fetch; +afterEach(() => { + mock.clearAllMocks(); + puppeteerCalls.connect.length = 0; + globalThis.fetch = originalFetch; +}); + +describe("CDPBrowser", () => { + test("resolves Browser-as-a-Service sessions lazily", async () => { + const endpoint = mock(async () => "wss://browser.example/lazy-session"); + const browser = new CDPBrowser({ endpoint }); + + expect(endpoint).not.toHaveBeenCalled(); + await browser.init(); + expect(endpoint).toHaveBeenCalledTimes(1); + expect(puppeteerCalls.connect).toEqual(["wss://browser.example/lazy-session"]); + await browser.deinit(); + }); + + test("resolves one endpoint for each physical Browser slot", async () => { + let session = 0; + const endpoint = mock(async () => { + session += 1; + return `wss://browser.example/session-${session}`; + }); + const browser = new CDPBrowser({ + endpoint, + maxBrowsers: 2, + maxContextsPerBrowser: 1, + }); + + const first = await browser.acquireContext(); + const second = await browser.acquireContext(); + expect(endpoint).toHaveBeenCalledTimes(2); + expect(puppeteerCalls.connect).toEqual([ + "wss://browser.example/session-1", + "wss://browser.example/session-2", + ]); + await first.close(); + await second.close(); + await browser.deinit(); + }); + + test("discovers a WebSocket endpoint over HTTP", async () => { + globalThis.fetch = Object.assign( + mock(async () => Response.json({ webSocketDebuggerUrl: "wss://browser.example/session" })), + { preconnect: originalFetch.preconnect }, + ); + const browser = new CDPBrowser({ endpoint: "https://browser.example/cdp" }); + await browser.init(); + expect(puppeteerCalls.connect).toEqual(["wss://browser.example/session"]); + await browser.deinit(); + expect(remotePuppeteer.browser.disconnect).toHaveBeenCalledTimes(1); + }); + + test("can close an owned remote session", async () => { + const browser = new CDPBrowser({ + endpoint: "wss://browser.example/session", + shutdown: "close", + }); + await browser.init(); + await browser.deinit(); + expect(remotePuppeteer.browser.close).toHaveBeenCalled(); + }); +}); diff --git a/pkgs/rssbook/src/browser/cdp.ts b/pkgs/rssbook/src/browser/cdp.ts new file mode 100644 index 0000000..ed25de9 --- /dev/null +++ b/pkgs/rssbook/src/browser/cdp.ts @@ -0,0 +1,49 @@ +import type { ConnectOptions, Browser as PuppeteerBrowser } from "puppeteer-core"; +import type { Awaitable } from "@/types/utils"; +import { resolveBrowserWSEndpoint } from "@/utils/browser/cdp"; +import { Browser, type BrowserConcurrencyOptions } from "./browser"; + +export type CDPBrowserEndpoint = string | URL; +export type CDPBrowserEndpointResolver = () => Awaitable; + +export interface CDPBrowserOptions extends BrowserConcurrencyOptions { + connect?: Omit; + /** Static endpoint or lazy Browser-as-a-Service session resolver. */ + endpoint: CDPBrowserEndpoint | CDPBrowserEndpointResolver; + shutdown?: "close" | "disconnect"; +} + +/** Puppeteer Core provider connected to a remote CDP endpoint. */ +export class CDPBrowser extends Browser { + private readonly connectOptions?: Omit; + private readonly endpoint: CDPBrowserEndpoint | CDPBrowserEndpointResolver; + private readonly shutdown: "close" | "disconnect"; + + public constructor(options: CDPBrowserOptions) { + super({ + maxBrowsers: options.maxBrowsers ?? 1, + maxContextsPerBrowser: options.maxContextsPerBrowser ?? 4, + maxPagesPerContext: options.maxPagesPerContext ?? 4, + }); + this.connectOptions = options.connect; + this.endpoint = options.endpoint; + this.shutdown = options.shutdown ?? "disconnect"; + } + + protected async createBrowser(): Promise { + const puppeteer = await import("puppeteer-core"); + const endpoint = typeof this.endpoint === "function" ? await this.endpoint() : this.endpoint; + return puppeteer.connect({ + ...this.connectOptions, + browserWSEndpoint: await resolveBrowserWSEndpoint(endpoint), + }); + } + + protected override async closeBrowser(browser: PuppeteerBrowser): Promise { + if (this.shutdown === "close") { + await browser.close(); + return; + } + await browser.disconnect(); + } +} diff --git a/pkgs/rssbook/src/browser/errors.test.ts b/pkgs/rssbook/src/browser/errors.test.ts new file mode 100644 index 0000000..bcdbfa6 --- /dev/null +++ b/pkgs/rssbook/src/browser/errors.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, test } from "bun:test"; +import { BrowserUnavailableError } from "@/utils/error"; +import { createUnavailableBrowser } from "./errors"; + +describe("createUnavailableBrowser", () => { + test("fails lazily without initializing during deinit", async () => { + const unused = createUnavailableBrowser(() => new BrowserUnavailableError()); + await unused.deinit(); + + const browser = createUnavailableBrowser(() => new BrowserUnavailableError()); + await expect(browser.init()).rejects.toBeInstanceOf(BrowserUnavailableError); + }); +}); diff --git a/pkgs/rssbook/src/browser/errors.ts b/pkgs/rssbook/src/browser/errors.ts new file mode 100644 index 0000000..b1f8497 --- /dev/null +++ b/pkgs/rssbook/src/browser/errors.ts @@ -0,0 +1,19 @@ +import type { Browser as PuppeteerBrowser } from "puppeteer-core"; +import { Browser } from "./browser"; + +export { BrowserClosedError, BrowserUnavailableError } from "@/utils/error"; + +/** Create a Browser that fails lazily when browser support is used. */ +export function createUnavailableBrowser(createError: () => Error): Browser { + return new UnavailableBrowser(createError); +} + +class UnavailableBrowser extends Browser { + public constructor(private readonly createError: () => Error) { + super({ maxBrowsers: 1, maxContextsPerBrowser: 1, maxPagesPerContext: 1 }); + } + + protected createBrowser(): Promise { + return Promise.reject(this.createError()); + } +} diff --git a/pkgs/rssbook/src/browser/index.ts b/pkgs/rssbook/src/browser/index.ts new file mode 100644 index 0000000..acd2ab5 --- /dev/null +++ b/pkgs/rssbook/src/browser/index.ts @@ -0,0 +1,15 @@ +export type { Browser as PuppeteerBrowser } from "puppeteer-core"; +export { + Browser, + type BrowserAcquireOptions, + type BrowserConcurrencyOptions, +} from "./browser"; +export { + CDPBrowser, + type CDPBrowserEndpoint, + type CDPBrowserEndpointResolver, + type CDPBrowserOptions, +} from "./cdp"; +export { BrowserClosedError, BrowserUnavailableError } from "./errors"; +export { BrowserContextLease, BrowserPageLease } from "./lease"; +export { LocalPuppeteerBrowser, type LocalPuppeteerBrowserOptions } from "./local"; diff --git a/pkgs/rssbook/src/browser/lease.test.ts b/pkgs/rssbook/src/browser/lease.test.ts new file mode 100644 index 0000000..4ecc5a2 --- /dev/null +++ b/pkgs/rssbook/src/browser/lease.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, mock, test } from "bun:test"; +import { BrowserContextLease, BrowserPageLease } from "./lease"; +import { createFakeContext, createFakePage } from "./test-helpers"; + +describe("Browser leases", () => { + test("BrowserPageLease releases once when closed repeatedly", async () => { + const page = createFakePage(); + const context = createFakeContext(); + const release = mock(async () => {}); + const lease = new BrowserPageLease(page, context, release); + await Promise.all([lease.close(), lease.close()]); + expect(page.close).toHaveBeenCalledTimes(1); + expect(release).toHaveBeenCalledTimes(1); + }); + + test("private Page release closes its owning Context", async () => { + const page = createFakePage(); + const context = createFakeContext(); + const pageLease = new BrowserPageLease(page, context, () => {}); + const contextLease = new BrowserContextLease( + context, + async () => pageLease, + () => context.close(), + ); + const privatePage = (await contextLease.acquirePage()).closeContextOnRelease(() => + contextLease.close(), + ); + await privatePage.close(); + expect(context.close).toHaveBeenCalledTimes(1); + }); + + test("BrowserContextLease closes idempotently", async () => { + const context = createFakeContext(); + const release = mock(async () => {}); + const lease = new BrowserContextLease( + context, + async () => { + throw new Error("not used"); + }, + release, + ); + await Promise.all([lease.close(), lease.close()]); + expect(release).toHaveBeenCalledTimes(1); + }); +}); diff --git a/pkgs/rssbook/src/browser/lease.ts b/pkgs/rssbook/src/browser/lease.ts new file mode 100644 index 0000000..118bbe3 --- /dev/null +++ b/pkgs/rssbook/src/browser/lease.ts @@ -0,0 +1,85 @@ +import type { BrowserContext, Page } from "puppeteer-core"; +import type { BrowserAcquireOptions } from "./browser"; + +type AcquirePage = (options: BrowserAcquireOptions) => Promise; +type Release = () => void | Promise; + +/** A concurrency-tracked Puppeteer Page. */ +export class BrowserPageLease { + private closePromise?: Promise; + private releaseContext?: Release; + private releaseContextPromise?: Promise; + private releasePromise?: Promise; + private released = false; + + public constructor( + public readonly page: Page, + public readonly context: BrowserContext, + private readonly onRelease: Release, + ) {} + + /** Close the owning Context when this Page is released. */ + public closeContextOnRelease(release: Release): this { + this.releaseContext = release; + if (this.released) void this.releaseOwnedContext(); + return this; + } + + public close(): Promise { + if (this.closePromise) return this.closePromise; + this.closePromise = (async () => { + try { + if (!this.page.isClosed()) await this.page.close(); + } finally { + await this.release(); + } + })(); + return this.closePromise; + } + + /** Release capacity when Puppeteer closes the page externally. */ + public release(): Promise { + if (this.releasePromise) return this.releasePromise; + this.released = true; + this.releasePromise = (async () => { + await this.onRelease(); + await this.releaseOwnedContext(); + })(); + return this.releasePromise; + } + + public async [Symbol.asyncDispose](): Promise { + await this.close(); + } + + private releaseOwnedContext(): Promise { + if (!this.releaseContext) return Promise.resolve(); + this.releaseContextPromise ??= Promise.resolve(this.releaseContext()); + return this.releaseContextPromise; + } +} + +/** A concurrency-tracked isolated Puppeteer BrowserContext. */ +export class BrowserContextLease { + private closePromise?: Promise; + + public constructor( + public readonly context: BrowserContext, + private readonly acquire: AcquirePage, + private readonly release: Release, + ) {} + + public async acquirePage(options: BrowserAcquireOptions = {}): Promise { + if (this.closePromise) throw new Error("BrowserContextLease is closed."); + return this.acquire(options); + } + + public close(): Promise { + if (!this.closePromise) this.closePromise = Promise.resolve(this.release()); + return this.closePromise; + } + + public async [Symbol.asyncDispose](): Promise { + await this.close(); + } +} diff --git a/pkgs/rssbook/src/browser/local.test.ts b/pkgs/rssbook/src/browser/local.test.ts new file mode 100644 index 0000000..b6e2499 --- /dev/null +++ b/pkgs/rssbook/src/browser/local.test.ts @@ -0,0 +1,38 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { LocalPuppeteerBrowser } from "./local"; +import { puppeteerCalls } from "./test-helpers"; + +const previousExecutablePath = process.env.PUPPETEER_EXECUTABLE_PATH; + +afterEach(() => { + puppeteerCalls.launch.length = 0; + if (previousExecutablePath === undefined) delete process.env.PUPPETEER_EXECUTABLE_PATH; + else process.env.PUPPETEER_EXECUTABLE_PATH = previousExecutablePath; +}); + +describe("LocalPuppeteerBrowser", () => { + test("launches stable local Chrome lazily", async () => { + delete process.env.PUPPETEER_EXECUTABLE_PATH; + const browser = new LocalPuppeteerBrowser(); + await browser.init(); + await browser.init(); + expect(puppeteerCalls.launch).toEqual([{ channel: "chrome" }]); + await browser.deinit(); + }); + + test("uses the environment executable path", async () => { + process.env.PUPPETEER_EXECUTABLE_PATH = "/env/chrome"; + const browser = new LocalPuppeteerBrowser(); + await browser.init(); + expect(puppeteerCalls.launch).toEqual([{ executablePath: "/env/chrome" }]); + await browser.deinit(); + }); + + test("prefers explicit launch configuration", async () => { + process.env.PUPPETEER_EXECUTABLE_PATH = "/env/chrome"; + const browser = new LocalPuppeteerBrowser({ launch: { executablePath: "/opt/chromium" } }); + await browser.init(); + expect(puppeteerCalls.launch).toEqual([{ executablePath: "/opt/chromium" }]); + await browser.deinit(); + }); +}); diff --git a/pkgs/rssbook/src/browser/local.ts b/pkgs/rssbook/src/browser/local.ts new file mode 100644 index 0000000..a0c6b6b --- /dev/null +++ b/pkgs/rssbook/src/browser/local.ts @@ -0,0 +1,34 @@ +import type { LaunchOptions, Browser as PuppeteerBrowser } from "puppeteer-core"; +import { Browser, type BrowserConcurrencyOptions } from "./browser"; + +export interface LocalPuppeteerBrowserOptions extends BrowserConcurrencyOptions { + launch?: LaunchOptions; +} + +/** Puppeteer Core provider backed by an installed local Chromium browser. */ +export class LocalPuppeteerBrowser extends Browser { + private readonly launchOptions: LaunchOptions; + + public constructor(options: LocalPuppeteerBrowserOptions = {}) { + super({ + maxBrowsers: options.maxBrowsers ?? 1, + maxContextsPerBrowser: options.maxContextsPerBrowser ?? 4, + maxPagesPerContext: options.maxPagesPerContext ?? 4, + }); + this.launchOptions = options.launch ?? {}; + } + + protected async createBrowser(): Promise { + const puppeteer = await import("puppeteer-core"); + const executablePath = process.env.PUPPETEER_EXECUTABLE_PATH; + + return puppeteer.launch({ + ...this.launchOptions, + ...(!this.launchOptions.channel && !this.launchOptions.executablePath + ? executablePath + ? { executablePath } + : { channel: "chrome" as const } + : {}), + }); + } +} diff --git a/pkgs/rssbook/src/browser/test-helpers.ts b/pkgs/rssbook/src/browser/test-helpers.ts new file mode 100644 index 0000000..497dd51 --- /dev/null +++ b/pkgs/rssbook/src/browser/test-helpers.ts @@ -0,0 +1,118 @@ +import { mock } from "bun:test"; +import type { BrowserContext, Page, Browser as PuppeteerBrowser, Target } from "puppeteer-core"; + +export const puppeteerCalls = { + connect: [] as string[], + launch: [] as object[], +}; +export const localPuppeteer = createFakePuppeteerBrowser(); +export const remotePuppeteer = createFakePuppeteerBrowser(); +const contextHandlers = new WeakMap void>>>(); + +mock.module("puppeteer-core", () => ({ + connect: mock(async ({ browserWSEndpoint }: { browserWSEndpoint: string }) => { + puppeteerCalls.connect.push(browserWSEndpoint); + return remotePuppeteer.browser; + }), + launch: mock(async (options: object) => { + puppeteerCalls.launch.push(options); + return localPuppeteer.browser; + }), +})); + +export function createFakePuppeteerBrowser() { + let disconnected: (() => void) | undefined; + let browser: PuppeteerBrowser; + const contexts: BrowserContext[] = []; + browser = { + close: mock(async () => {}), + createBrowserContext: mock(async () => { + const context = createFakeContext(); + contexts.push(context); + return context; + }), + disconnect: mock(async () => {}), + newPage: mock(async () => createFakePage()), + once: mock((event, handler) => { + if (event === "disconnected") disconnected = handler; + return browser; + }), + } as unknown as PuppeteerBrowser; + return { browser, contexts, disconnect: () => disconnected?.() }; +} + +export function createFakeContext(overrides: Partial = {}): BrowserContext { + let closed = false; + const handlers = new Map void>>(); + let context: BrowserContext; + context = { + close: mock(async () => { + closed = true; + }), + get closed() { + return closed; + }, + cookies: mock(async () => []), + newPage: mock(async () => { + const page = createFakePage(); + for (const handler of handlers.get("targetcreated") ?? []) handler(page.target()); + return page; + }), + on: mock((event, handler) => { + const entries = handlers.get(String(event)) ?? []; + entries.push(handler); + handlers.set(String(event), entries); + return context; + }), + setCookie: mock(async () => {}), + ...overrides, + } as unknown as BrowserContext; + contextHandlers.set(context, handlers); + return context; +} + +export function createFakeTarget(page = createFakePage()): Target { + return { + page: async () => page, + type: () => "page", + } as Target; +} + +export function emitContextTarget( + context: BrowserContext, + event: "targetcreated" | "targetdestroyed", + target: Target, +): void { + for (const handler of contextHandlers.get(context)?.get(event) ?? []) handler(target); +} + +export function createFakePage(overrides: Partial = {}): Page { + let closed = false; + const closeHandlers: Array<() => void> = []; + let page: Page; + const target = { + page: async () => page, + type: () => "page", + } as Target; + page = { + close: mock(async () => { + if (closed) return; + closed = true; + for (const handler of closeHandlers) handler(); + }), + content: mock(async () => ""), + goto: mock(async () => null), + isClosed: mock(() => closed), + once: mock((event, handler) => { + if (event === "close") closeHandlers.push(handler); + return page; + }), + target: mock(() => target), + ...overrides, + } as unknown as Page; + return page; +} + +export async function tick(): Promise { + await new Promise((resolve) => setTimeout(resolve, 0)); +} diff --git a/pkgs/rssbook/src/cache/cache.test.ts b/pkgs/rssbook/src/cache/cache.test.ts new file mode 100644 index 0000000..b477ce6 --- /dev/null +++ b/pkgs/rssbook/src/cache/cache.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, test } from "bun:test"; +import { Cache, type CacheValue } from "./cache"; + +class TestCache extends Cache { + public readonly values = new Map(); + public readonly deleted: string[] = []; + public closeCount = 0; + + // biome-ignore lint/complexity/noUselessConstructor: exposes the protected base constructor for tests + public constructor(options?: import("./cache").CacheOptions) { + super(options); + } + + protected async getRaw(key: string): Promise { + return this.values.get(key); + } + + protected async setRaw(key: string, value: string, _maxAgeMs: number): Promise { + this.values.set(key, value); + } + + protected async deleteRaw(key: string): Promise { + this.deleted.push(key); + this.values.delete(key); + } + + protected async closeBackend(): Promise { + this.closeCount += 1; + } +} + +const delay = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)); + +describe("Cache", () => { + test("prefixes keys and restores recursive values including Date and null", async () => { + const cache = new TestCache({ prefix: "test:" }); + const date = new Date("2026-01-02T03:04:05.000Z"); + const value = { date, nested: [{ date }, null] } satisfies CacheValue; + + await cache.set("key", value); + + expect(cache.values.has("test:key")).toBe(true); + expect(await cache.get("key")).toEqual(value); + }); + + test("uses undefined exclusively for cache misses", async () => { + const cache = new TestCache(); + await cache.set("null", null); + + expect(await cache.get("missing")).toBeUndefined(); + expect(await cache.get("null")).toBeNull(); + }); + + test("enforces exact TTL and asynchronously deletes expired entries", async () => { + const cache = new TestCache(); + await cache.set("short", "value", 10); + expect(await cache.get("short")).toBe("value"); + + await delay(20); + expect(await cache.get("short")).toBeUndefined(); + await delay(0); + expect(cache.deleted).toContain("short"); + }); + + test("keeps zero-TTL entries and rejects invalid TTL values", async () => { + const cache = new TestCache({ defaultMaxAgeMs: 0 }); + await cache.set("forever", "value", 0); + await delay(5); + expect(await cache.get("forever")).toBe("value"); + + for (const invalid of [-1, Number.NaN, Number.POSITIVE_INFINITY]) { + await expect(cache.set("invalid", "value", invalid)).rejects.toBeInstanceOf(RangeError); + await expect(cache.tryGet("invalid", () => "value", invalid)).rejects.toBeInstanceOf( + RangeError, + ); + } + expect(() => new TestCache({ defaultMaxAgeMs: -1 })).toThrow(RangeError); + }); + + test("coalesces concurrent misses for the same key", async () => { + const cache = new TestCache(); + let calls = 0; + const fetcher = async () => { + calls += 1; + await delay(10); + return "fresh"; + }; + + expect(await Promise.all([cache.tryGet("key", fetcher), cache.tryGet("key", fetcher)])).toEqual( + ["fresh", "fresh"], + ); + expect(calls).toBe(1); + }); + + test("does not block fetchers for different keys", async () => { + const cache = new TestCache(); + const started: string[] = []; + let release: (() => void) | undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const fetcher = async (key: string) => { + started.push(key); + await gate; + return key; + }; + + const pending = Promise.all([cache.tryGet("a", fetcher), cache.tryGet("b", fetcher)]); + await delay(0); + expect(started).toEqual(["a", "b"]); + release?.(); + expect(await pending).toEqual(["a", "b"]); + }); + + test("shares fetch errors and allows a later retry", async () => { + const cache = new TestCache(); + const error = new Error("failed"); + let calls = 0; + const failing = async () => { + calls += 1; + await delay(5); + throw error; + }; + + const results = await Promise.allSettled([ + cache.tryGet("key", failing), + cache.tryGet("key", failing), + ]); + expect(results).toEqual([ + { reason: error, status: "rejected" }, + { reason: error, status: "rejected" }, + ]); + expect(calls).toBe(1); + expect(await cache.tryGet("key", () => "recovered")).toBe("recovered"); + }); + + test("deinitializes once and rejects operations after closing", async () => { + const cache = new TestCache(); + await Promise.all([cache.deinit(), cache.deinit(), cache[Symbol.asyncDispose]()]); + expect(cache.closeCount).toBe(1); + + await expect(cache.get("key")).rejects.toThrow("deinitialized"); + await expect(cache.set("key", "value")).rejects.toThrow("deinitialized"); + await expect(cache.del("key")).rejects.toThrow("deinitialized"); + await expect(cache.tryGet("key", () => "value")).rejects.toThrow("deinitialized"); + }); +}); diff --git a/pkgs/rssbook/src/cache/cache.ts b/pkgs/rssbook/src/cache/cache.ts new file mode 100644 index 0000000..1821cf8 --- /dev/null +++ b/pkgs/rssbook/src/cache/cache.ts @@ -0,0 +1,188 @@ +/** Values supported by RSSBook cache implementations. */ +export type CacheValue = + | null + | string + | number + | boolean + | Date + | CacheValue[] + | { + [key: string]: CacheValue; + }; + +/** Shared options for cache implementations. */ +export interface CacheOptions { + /** Default lifetime in milliseconds. Zero disables automatic expiration. */ + defaultMaxAgeMs?: number; + /** Prefix prepended to every backend key. */ + prefix?: string; +} + +type SerializedValue = + | null + | string + | number + | boolean + | SerializedValue[] + | { + [key: string]: SerializedValue; + }; + +interface SerializedEntry { + expiresAt: number | null; + value: SerializedValue; +} + +const DATE_MARKER = "__rssbook_cache_date__"; +const DEFAULT_MAX_AGE_MS = 10 * 60 * 1000; + +const encode = (value: CacheValue): SerializedValue => { + if (value instanceof Date) return { [DATE_MARKER]: value.toISOString() }; + if (Array.isArray(value)) return value.map(encode); + if (value !== null && typeof value === "object") { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encode(item)])); + } + return value; +}; + +const decode = (value: SerializedValue): CacheValue => { + if (Array.isArray(value)) return value.map(decode); + if (value !== null && typeof value === "object") { + const entries = Object.entries(value); + if (entries.length === 1 && typeof value[DATE_MARKER] === "string") { + return new Date(value[DATE_MARKER]); + } + return Object.fromEntries(entries.map(([key, item]) => [key, decode(item)])); + } + return value; +}; + +const validateMaxAge = (maxAgeMs: number): number => { + if (!Number.isFinite(maxAgeMs) || maxAgeMs < 0) { + throw new RangeError("Cache maxAgeMs must be a finite, non-negative number."); + } + return maxAgeMs; +}; + +/** + * Storage-independent RSSBook cache with serialization, exact TTL handling, + * request coalescing, and lifecycle management. + */ +export abstract class Cache { + /** Prefix prepended to every backend key. */ + public readonly prefix: string; + + /** Default lifetime in milliseconds. Zero disables automatic expiration. */ + public readonly defaultMaxAgeMs: number; + + private readonly inFlight = new Map>(); + private closed = false; + private deinitializing?: Promise; + + protected constructor(options: CacheOptions = {}) { + this.prefix = options.prefix ?? ""; + this.defaultMaxAgeMs = validateMaxAge(options.defaultMaxAgeMs ?? DEFAULT_MAX_AGE_MS); + } + + /** Read a serialized entry from the backend. */ + protected abstract getRaw(key: string): Promise; + + /** Store a serialized entry using the requested lifetime in milliseconds. */ + protected abstract setRaw(key: string, serializedEntry: string, maxAgeMs: number): Promise; + + /** Delete an entry from the backend. */ + protected abstract deleteRaw(key: string): Promise; + + /** Release resources owned by the backend. */ + protected abstract closeBackend(): Promise; + + private fullKey(key: string): string { + return `${this.prefix}${key}`; + } + + private assertOpen(): void { + if (this.closed) throw new Error("This RSSBook Cache has been deinitialized."); + } + + /** Get a cached value, or `undefined` when it is missing or expired. */ + public async get(key: string): Promise { + this.assertOpen(); + const fullKey = this.fullKey(key); + const raw = await this.getRaw(fullKey); + if (raw === undefined) return undefined; + + const entry: SerializedEntry = JSON.parse(raw); + if (entry.expiresAt !== null && Date.now() >= entry.expiresAt) { + void this.deleteRaw(fullKey).catch(() => undefined); + return undefined; + } + + return decode(entry.value) as T; + } + + /** Store a value with an optional lifetime in milliseconds. */ + public async set( + key: string, + value: CacheValue, + maxAgeMs: number = this.defaultMaxAgeMs, + ): Promise { + this.assertOpen(); + const lifetime = validateMaxAge(maxAgeMs); + const entry: SerializedEntry = { + expiresAt: lifetime === 0 ? null : Date.now() + lifetime, + value: encode(value), + }; + await this.setRaw(this.fullKey(key), JSON.stringify(entry), lifetime); + } + + /** Delete a cached value. */ + public async del(key: string): Promise { + this.assertOpen(); + await this.deleteRaw(this.fullKey(key)); + } + + /** + * Get a cached value or run one shared fetcher for concurrent misses of the + * same fully-prefixed key. + */ + public async tryGet( + key: string, + fetcher: (key: string) => T | Promise, + maxAgeMs: number = this.defaultMaxAgeMs, + ): Promise { + this.assertOpen(); + validateMaxAge(maxAgeMs); + const cached = await this.get(key); + if (cached !== undefined) return cached; + + const fullKey = this.fullKey(key); + const existing = this.inFlight.get(fullKey); + if (existing) return existing as Promise; + + const pending = (async (): Promise => { + const fresh = await fetcher(key); + await this.set(key, fresh, maxAgeMs); + return fresh; + })(); + this.inFlight.set(fullKey, pending); + + try { + return (await pending) as T; + } finally { + if (this.inFlight.get(fullKey) === pending) this.inFlight.delete(fullKey); + } + } + + /** Release backend resources. Calling this method more than once is safe. */ + public async deinit(): Promise { + if (this.deinitializing) return this.deinitializing; + this.closed = true; + this.deinitializing = this.closeBackend(); + return this.deinitializing; + } + + /** Release backend resources when used with `await using`. */ + public async [Symbol.asyncDispose](): Promise { + await this.deinit(); + } +} diff --git a/pkgs/rssbook/src/cache/index.ts b/pkgs/rssbook/src/cache/index.ts new file mode 100644 index 0000000..2d77b94 --- /dev/null +++ b/pkgs/rssbook/src/cache/index.ts @@ -0,0 +1,3 @@ +export * from "./cache"; +export * from "./memory"; +export * from "./null"; diff --git a/pkgs/rssbook/src/cache/memory.test.ts b/pkgs/rssbook/src/cache/memory.test.ts new file mode 100644 index 0000000..26aa9d3 --- /dev/null +++ b/pkgs/rssbook/src/cache/memory.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import { MemoryCache } from "./memory"; + +const delay = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)); + +describe("MemoryCache", () => { + test("evicts the least recently used entry at capacity", async () => { + const cache = new MemoryCache({ maxEntries: 2 }); + await cache.set("a", 1); + await cache.set("b", 2); + await cache.get("a"); + await cache.set("c", 3); + + expect(await cache.get("a")).toBe(1); + expect(await cache.get("b")).toBeUndefined(); + expect(await cache.get("c")).toBe(3); + }); + + test("expires and deletes entries", async () => { + const cache = new MemoryCache(); + await cache.set("expiring", "value", 10); + await delay(20); + expect(await cache.get("expiring")).toBeUndefined(); + + await cache.set("deleted", "value"); + await cache.del("deleted"); + expect(await cache.get("deleted")).toBeUndefined(); + }); +}); diff --git a/pkgs/rssbook/src/cache/memory.ts b/pkgs/rssbook/src/cache/memory.ts new file mode 100644 index 0000000..ea77ba1 --- /dev/null +++ b/pkgs/rssbook/src/cache/memory.ts @@ -0,0 +1,34 @@ +import { LRUCache } from "lru-cache"; +import { Cache, type CacheOptions } from "./cache"; + +/** Options for the in-process LRU cache. */ +export interface MemoryCacheOptions extends CacheOptions { + /** Maximum number of cached entries. */ + maxEntries?: number; +} + +/** In-process LRU cache used by RSSBook by default. */ +export class MemoryCache extends Cache { + private readonly storage: LRUCache; + + public constructor(options: MemoryCacheOptions = {}) { + super(options); + this.storage = new LRUCache({ max: options.maxEntries ?? 1000 }); + } + + protected async getRaw(key: string): Promise { + return this.storage.get(key); + } + + protected async setRaw(key: string, serializedEntry: string, maxAgeMs: number): Promise { + this.storage.set(key, serializedEntry, maxAgeMs === 0 ? undefined : { ttl: maxAgeMs }); + } + + protected async deleteRaw(key: string): Promise { + this.storage.delete(key); + } + + protected async closeBackend(): Promise { + this.storage.clear(); + } +} diff --git a/pkgs/rssbook/src/cache/null.test.ts b/pkgs/rssbook/src/cache/null.test.ts new file mode 100644 index 0000000..6b93f89 --- /dev/null +++ b/pkgs/rssbook/src/cache/null.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, test } from "bun:test"; +import { NullCache } from "./null"; + +describe("NullCache", () => { + test("never persists values", async () => { + const cache = new NullCache(); + await cache.set("key", "value"); + expect(await cache.get("key")).toBeUndefined(); + await cache.del("key"); + }); + + test("still coalesces concurrent fetches", async () => { + const cache = new NullCache(); + let calls = 0; + const fetcher = async () => { + calls += 1; + await new Promise((resolve) => setTimeout(resolve, 5)); + return "fresh"; + }; + + expect(await Promise.all([cache.tryGet("key", fetcher), cache.tryGet("key", fetcher)])).toEqual( + ["fresh", "fresh"], + ); + expect(calls).toBe(1); + expect(await cache.get("key")).toBeUndefined(); + }); +}); diff --git a/pkgs/rssbook/src/cache/null.ts b/pkgs/rssbook/src/cache/null.ts new file mode 100644 index 0000000..c9b989f --- /dev/null +++ b/pkgs/rssbook/src/cache/null.ts @@ -0,0 +1,22 @@ +import { Cache, type CacheOptions } from "./cache"; + +/** Cache backend that intentionally never persists values. */ +export class NullCache extends Cache { + public constructor(options: CacheOptions = {}) { + super(options); + } + + protected async getRaw(_key: string): Promise { + return undefined; + } + + protected async setRaw( + _key: string, + _serializedEntry: string, + _maxAgeMs: number, + ): Promise {} + + protected async deleteRaw(_key: string): Promise {} + + protected async closeBackend(): Promise {} +} diff --git a/pkgs/rssbook/src/index.ts b/pkgs/rssbook/src/index.ts index 702ed28..978764c 100644 --- a/pkgs/rssbook/src/index.ts +++ b/pkgs/rssbook/src/index.ts @@ -16,6 +16,25 @@ export default { fetch: (request: Request) => getApp().fetch(request), }; +export { + Browser, + type BrowserAcquireOptions, + BrowserClosedError, + type BrowserConcurrencyOptions, + BrowserContextLease, + BrowserPageLease, + BrowserUnavailableError, + CDPBrowser, + type CDPBrowserEndpoint, + type CDPBrowserEndpointResolver, + type CDPBrowserOptions, + LocalPuppeteerBrowser, + type LocalPuppeteerBrowserOptions, + type PuppeteerBrowser, +} from "@/browser"; +export type { CacheOptions, CacheValue, MemoryCacheOptions } from "@/cache"; +// Classes +export { Cache, MemoryCache, NullCache } from "@/cache"; export type { RSSBook, RSSBookBookConfig, RSSBookInitConfig } from "@/plugins/init"; export { createRSSBook } from "@/plugins/init"; // Types @@ -31,8 +50,20 @@ export type { Meta } from "@/types/meta"; export type { RouteConfig } from "@/types/route"; export type { Config, SourceConfigs } from "@/types/source"; export type { Theme, ThemeProps } from "@/types/theme"; -// Classes -export { Cache } from "@/utils/cache"; +export { + allowResources, + blockResources, + cookieHeaderToCookies, + cookiesToHeader, + getCookieHeader, + resolveBrowserWSEndpoint, + setColorDepth, + setCookieHeader, + setDeviceMemory, + setHardwareConcurrency, + setLanguages, + waitForResponse, +} from "@/utils/browser"; export { Category } from "@/utils/category"; export { detectLanguage } from "@/utils/detectLanguage"; // Feed utilities diff --git a/pkgs/rssbook/src/plugins/errorHandler.test.ts b/pkgs/rssbook/src/plugins/errorHandler.test.ts new file mode 100644 index 0000000..ab53bb3 --- /dev/null +++ b/pkgs/rssbook/src/plugins/errorHandler.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import { Elysia } from "elysia"; +import { InvalidUrlError } from "@/utils/error"; +import { errorHandlerPlugin } from "./errorHandler"; + +describe("errorHandlerPlugin", () => { + test("renders an HTML error response for thrown errors", async () => { + const app = new Elysia().use(errorHandlerPlugin).get("/broken", () => { + throw new Error("Feed route failed"); + }); + + const response = await app.handle(new Request("http://localhost/broken")); + const html = await response.text(); + + expect(response.status).toBe(500); + expect(response.headers.get("content-type")).toBe("text/html"); + expect(html.match(/]*>\s*(Feed route failed)\s*<\/p>/)?.[1]).toBe("Feed route failed"); + }); + + test("uses the status from RSSBookError instances", async () => { + const app = new Elysia().use(errorHandlerPlugin).get("/broken", () => { + throw new InvalidUrlError(); + }); + + const response = await app.handle(new Request("http://localhost/broken")); + + expect(response.status).toBe(400); + }); +}); diff --git a/pkgs/rssbook/src/plugins/errorHandler.ts b/pkgs/rssbook/src/plugins/errorHandler.ts index 385a88b..52a396f 100644 --- a/pkgs/rssbook/src/plugins/errorHandler.ts +++ b/pkgs/rssbook/src/plugins/errorHandler.ts @@ -5,6 +5,7 @@ const { version } = pkg; import { defaultErrorPage } from "@/books/error"; import type { ErrorPageProps } from "@/types"; +import { RSSBookError } from "@/utils/error"; /** * Error Handler Plugin @@ -16,6 +17,10 @@ export const errorHandlerPlugin = new Elysia({ name: "RSSBook/ErrorHandler" }).o as: "global", }, ({ code, error, set }) => { + if (error instanceof RSSBookError) { + set.status = error.status; + } + set.headers["content-type"] = "text/html"; const props: ErrorPageProps = { diff --git a/pkgs/rssbook/src/plugins/init.test.ts b/pkgs/rssbook/src/plugins/init.test.ts new file mode 100644 index 0000000..90c6e76 --- /dev/null +++ b/pkgs/rssbook/src/plugins/init.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, mock, test } from "bun:test"; +import { Elysia } from "elysia"; +import type { Browser as PuppeteerBrowser } from "puppeteer-core"; +import { Browser, BrowserClosedError } from "@/browser"; +import { BrowserUnavailableError } from "@/browser/errors"; +import { MemoryCache } from "@/cache"; +import { initPlugin } from "./init"; + +describe("initPlugin", () => { + test("deinitializes the app-owned Browser on stop without initializing it", async () => { + const browser = new NeverBrowser(); + const app = new Elysia().use(initPlugin({ browser })); + + for (const hook of app.event.stop ?? []) { + await hook.fn(app); + } + + expect(browser.create).not.toHaveBeenCalled(); + await expect(browser.init()).rejects.toBeInstanceOf(BrowserClosedError); + }); + + test("provides default RSSBook runtime state", async () => { + const app = new Elysia().use(initPlugin()).get("/state", async ({ rssbook }) => { + await rssbook.cache.set("plugin:init:default", "ok"); + + return { + cacheValue: await rssbook.cache.get("plugin:init:default"), + feedCount: rssbook.books.feeds.length, + maxAge: rssbook.books.cacheMaxAgeMs, + themeRenderable: typeof rssbook.books.theme.render === "function", + }; + }); + + const response = await app.handle(new Request("http://localhost/state")); + const body: { + cacheValue: string; + feedCount: number; + maxAge: number; + themeRenderable: boolean; + } = await response.json(); + + expect(response.status).toBe(200); + expect(body).toEqual({ + cacheValue: "ok", + feedCount: 0, + maxAge: 600000, + themeRenderable: true, + }); + }); + + test("uses caller-provided book config, cache, and disabled browser", async () => { + const cache = new MemoryCache(); + await cache.set("plugin:init:custom", "from-custom-cache"); + + const app = new Elysia() + .use( + initPlugin({ + book: { + cacheMaxAgeMs: 1234, + config: { + token: "secret", + }, + feeds: ["https://example.com/feed.xml"], + }, + browser: false, + cache, + }), + ) + .get("/state", async ({ rssbook }) => { + const renderResult = await rssbook.browser + .init() + .then(() => "available") + .catch((error: unknown) => + error instanceof BrowserUnavailableError ? "unavailable" : "unexpected", + ); + + return { + cacheValue: await rssbook.cache.get("plugin:init:custom"), + configToken: rssbook.config.token, + feeds: rssbook.books.feeds, + maxAge: rssbook.books.cacheMaxAgeMs, + renderResult, + }; + }); + + const response = await app.handle(new Request("http://localhost/state")); + const body: { + cacheValue: string; + configToken: string; + feeds: string[]; + maxAge: number; + renderResult: string; + } = await response.json(); + + expect(response.status).toBe(200); + expect(body).toEqual({ + cacheValue: "from-custom-cache", + configToken: "secret", + feeds: ["https://example.com/feed.xml"], + maxAge: 1234, + renderResult: "unavailable", + }); + }); +}); + +class NeverBrowser extends Browser { + public readonly create = mock(async () => { + throw new Error("should not initialize"); + }); + + public constructor() { + super({ maxBrowsers: 1, maxContextsPerBrowser: 1, maxPagesPerContext: 1 }); + } + + protected createBrowser(): Promise { + return this.create(); + } +} diff --git a/pkgs/rssbook/src/plugins/init.ts b/pkgs/rssbook/src/plugins/init.ts index 1fc88a0..0ab39a1 100644 --- a/pkgs/rssbook/src/plugins/init.ts +++ b/pkgs/rssbook/src/plugins/init.ts @@ -1,7 +1,10 @@ import { Elysia } from "elysia"; import { DEFAULT_THEME, getThemeByName, type ThemeName } from "@/books/themes"; +import type { Browser } from "@/browser/browser"; +import { BrowserUnavailableError, createUnavailableBrowser } from "@/browser/errors"; +import { LocalPuppeteerBrowser } from "@/browser/local"; +import { type Cache, MemoryCache } from "@/cache"; import type { Meta, Theme } from "@/types"; -import { Cache } from "@/utils"; export type { ThemeName }; @@ -23,6 +26,7 @@ export interface RSSBookBookConfig { } export interface RSSBook { + browser: Browser; books: { cacheMaxAgeMs: number; feeds: string[]; @@ -34,6 +38,16 @@ export interface RSSBook { } export interface RSSBookInitConfig { + /** + * Browser capability exposed to feed routes that declare + * `RouteConfig.browser: true`. + * + * `undefined` and `true` create RSSBook's lazy local Puppeteer Core + * `Browser`, using `PUPPETEER_EXECUTABLE_PATH` or the installed stable + * Chrome. `false` disables browser routes. Pass a `Browser` instance for + * CDP services or Puppeteer-compatible serverless SDKs. + */ + browser?: boolean | Browser; book?: RSSBookBookConfig; cache?: Cache; } @@ -44,6 +58,15 @@ function resolveTheme(theme?: ThemeName | Theme): Theme { return theme; } +function resolveBrowser(browser?: boolean | Browser): Browser { + if (browser === false) { + return createUnavailableBrowser(() => new BrowserUnavailableError()); + } + + if (browser === undefined || browser === true) return new LocalPuppeteerBrowser(); + return browser; +} + export function createRSSBook(init?: RSSBookInitConfig): RSSBook { return { books: { @@ -52,7 +75,8 @@ export function createRSSBook(init?: RSSBookInitConfig): RSSBook { meta: init?.book?.meta || {}, theme: resolveTheme(init?.book?.theme), }, - cache: init?.cache || new Cache(), + browser: resolveBrowser(init?.browser), + cache: init?.cache || new MemoryCache(), config: init?.book?.config || {}, }; } @@ -62,12 +86,20 @@ export function createRSSBook(init?: RSSBookInitConfig): RSSBook { * * Init the RSSBook instance and decorate it to Elysia app. */ -export const initPlugin = (config?: RSSBookInitConfig) => - new Elysia({ name: "RSSBook/Init" }).decorate( - { as: "append" }, // Inject ONLY if not exixts - "rssbook", - createRSSBook({ - book: config?.book, - cache: config?.cache, - }), - ); +export const initPlugin = (config?: RSSBookInitConfig) => { + const rssbook = createRSSBook({ + book: config?.book, + browser: config?.browser, + cache: config?.cache, + }); + + return new Elysia({ name: "RSSBook/Init" }) + .decorate( + { as: "append" }, // Inject ONLY if not exixts + "rssbook", + rssbook, + ) + .onStop(async () => { + await Promise.allSettled([rssbook.browser.deinit(), rssbook.cache.deinit()]); + }); +}; diff --git a/pkgs/rssbook/src/plugins/inject.test.ts b/pkgs/rssbook/src/plugins/inject.test.ts new file mode 100644 index 0000000..e08acd2 --- /dev/null +++ b/pkgs/rssbook/src/plugins/inject.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, test } from "bun:test"; +import { Elysia } from "elysia"; +import { initPlugin, injectPlugin } from "@/plugins"; + +describe("injectPlugin", () => { + test("injects utilities and resolves runtime config from initPlugin", async () => { + const app = new Elysia() + .use( + initPlugin({ + book: { + config: { + source: "unit-test", + }, + }, + browser: false, + }), + ) + .use(injectPlugin) + .get("/context", async ({ cache, config, formatHTML, toAbsoluteURL, uuid }) => { + await cache.set("plugin:inject", "cache-hit"); + + return { + absoluteURL: toAbsoluteURL("/article", "https://example.com/root/"), + cacheValue: await cache.get("plugin:inject"), + configSource: config.source, + sanitizedHTML: formatHTML( + 'Read', + "https://example.com/root/", + ), + stableId: uuid("rssbook", 1), + }; + }); + + const response = await app.handle(new Request("http://localhost/context")); + const body: { + absoluteURL: string; + cacheValue: string; + configSource: string; + sanitizedHTML: string; + stableId: string; + } = await response.json(); + + expect(response.status).toBe(200); + expect(body).toEqual({ + absoluteURL: "https://example.com/article", + cacheValue: "cache-hit", + configSource: "unit-test", + sanitizedHTML: 'Read', + stableId: "c0b131e3-45a1-54b5-9db9-1d863a6be509", + }); + }); +}); diff --git a/pkgs/rssbook/src/plugins/inject.ts b/pkgs/rssbook/src/plugins/inject.ts index 0a13865..ea45837 100644 --- a/pkgs/rssbook/src/plugins/inject.ts +++ b/pkgs/rssbook/src/plugins/inject.ts @@ -11,25 +11,19 @@ export const injectPlugin = new Elysia({ name: "RSSBook/Inject", }) .use(initPlugin()) // type inference - // transform `Context` type, and only keep add some props - .decorate(({ rssbook }) => { - const { cache, config } = rssbook; - - const utils = { - date, - formatHTML, - load, - logger, - ofetch, - toAbsoluteURL, - uuid, - }; - - return { - cache, - config, - - // from `@/utils` - ...utils, - }; - }); + // Static utilities from `@/utils`. + .decorate({ + date, + formatHTML, + load, + logger, + ofetch, + toAbsoluteURL, + uuid, + }) + // Runtime values must follow the actual app-level initPlugin config. + .resolve({ as: "scoped" }, ({ rssbook }) => ({ + browser: rssbook.browser, + cache: rssbook.cache, + config: rssbook.config, + })); diff --git a/pkgs/rssbook/src/plugins/openAPI.ts b/pkgs/rssbook/src/plugins/openAPI.ts index 53d6229..812ee07 100644 --- a/pkgs/rssbook/src/plugins/openAPI.ts +++ b/pkgs/rssbook/src/plugins/openAPI.ts @@ -1,6 +1,5 @@ import { openapi } from "@elysiajs/openapi"; import { Elysia } from "elysia"; -import { dataItemSchema, dataSchema, feedType } from "@/types"; import { logger, ofetch } from "@/utils"; import pkg from "../../package.json" with { type: "json" }; @@ -59,176 +58,151 @@ export const openAPIPlugin = (enableFetchOnlineServer: boolean = true) => { setInterval(updateHosts, 1000 * 60 * 60 * 24); } - return ( - new Elysia({ name: "RSSBook/OpenAPI" }) - .use( - openapi({ - documentation: { - info: { - contact: { - name: "RSSBook", - url: "https://github.com/HackHTU/RSSBook", - }, - description: ` -## Welcome to RSSBook 📕 -![RSSBook Logo](/favicon.ico) - -📕 Your Feed Generator, Toolkits and Blogger, with Type-safe, Lightweight, and Serverless support✨ - -\`\`\`shell -$ bun create github.com/HackHTU/RSSBook -$ cd RSSBook && bun dev -\`\`\` - ---- + return new Elysia({ name: "RSSBook/OpenAPI" }).use( + openapi({ + documentation: { + info: { + contact: { + name: "RSSBook", + url: "https://github.com/HackHTU/RSSBook", + }, + description: ` +# 📕 RSSBook -📄 This is OpenAPI Documentation, every feed includes the following information: +Try to browse routes, inspect parameters, and test feeds. -0. **The \`path\`, \`title\` and \`description\` of the feed** , you can use \`test request\` button to preview the feed. -1. **Maintainers** Displays details about the feed's maintainers. -2. **Configuration** Displays the feed's settings, which you must configure during RSSBook initialization. -3. **Information** Displays details about the feed, including: Fulltext support, Image inclusion, and Supported/Display languages. +Can't find your feed? **Try making one yourself** and PR it. ---- -> [!tip] -> For more information, please see [**RSSBook**](https://github.com/HackHTU/RSSBook). +Send this prompt to your agent. -![RSSBook](https://img.shields.io/badge/Powered%20by-RSSBook-red.svg) -![GitHub Repo stars](https://img.shields.io/github/stars/HackHTU/RSSBook) +\`\`\`plaintext +Clone HackHTU/RSSBook repo and bun install, read create-feeds skill, ask user for new source URL, run source:new script, implement feed and test logic, push to GitHub and create a PR. +\`\`\` `, - license: { - name: "MIT", - url: "https://github.com/HackHTU/RSSBook/blob/master/LICENSE", - }, - title: "RSSBook OpenAPI Documentation", - version: version, - }, - servers, - tags: [ - { - description: - "Content related to **Anime, Comics, and Games**, including news, reviews, and fan creations.", - name: "acg", - }, - { - description: - "Online **forums** for discussions, Q&A, and community interactions on various topics.", - name: "bbs", - }, - { - description: - "Topics covering **graphic design, UI/UX, industrial design**, and creative projects.", - name: "design", - }, - { - description: - "Information on **financial markets, investments, and personal finance**, including news and analysis.", - name: "finance", - }, - { - description: - "News, reviews, and discussions about **video games**, esports, and gaming culture.", - name: "gaming", - }, - { - description: - "Official information, **policies, services, and announcements** from government sources.", - name: "government", - }, - { - description: - "**Career opportunities, job listings, and professional advice** for job seekers.", - name: "jobs", - }, - { - description: - "**Live streaming** content including events, shows, and interactive broadcasts.", - name: "live", - }, - { - description: - "Various **media content**, including videos, audio, images, and interactive media.", - name: "multimedia", - }, - { - description: "**Latest news** and current events from around the world.", - name: "news", - }, - { - description: "Miscellaneous content that does not fit into other categories.", - name: "others", - }, - { - description: - "Resources, tutorials, and discussions about **coding, software development, and tech projects**.", - name: "programming", - }, - { - description: - "Books, articles, and **reading materials** for leisure, education, or research.", - name: "reading", - }, - { - description: - "**Academic, scientific, and technical research** materials and studies.", - name: "research", - }, - { - description: - "Educational resources, **school-related news**, and learning materials for students and teachers.", - name: "school", - }, - { - description: - "**E-commerce**, product reviews, and guides for online and offline shopping.", - name: "shopping", - }, - { - description: - "Content and discussions from **social networking platforms**, trends, and viral posts.", - name: "socialmedia", - }, - { - description: - "Information and guides for **travel destinations, experiences, and tips**.", - name: "travel", - }, - { - description: "**Announcements and updates** about products, services, or projects.", - name: "updates", - }, - { - description: - "Personal or professional **blogs** covering various topics, stories, and experiences.", - name: "blog", - }, - { - description: - "Feed utilities and tools for enhancing the existing RSS/Atom feeds.\n> [!TIP]\n> **You can visit Feed Tools Helper to generate your feed**.", - name: "utils", - }, - { - description: - "RSSBook related endpoints, including theme, documentation and metadata.", - name: "_", - }, - ], - }, - scalar: { - customCss: `main p,h1,h2,h3,h4,h5,h6,li,img,article,span{opacity:0;transform:translateY(2em);animation:starting-style .6s cubic-bezier(.22,.98,.35,1) forwards}@keyframes starting-style{from{opacity:0;transform:translateY(2em);filter:blur(5px);}to{opacity:1;transform:translateY(0);filter:blur(0);}}@media (prefers-reduced-motion:reduce){main p,h1,h2,h3,h4,h5,h6,li,img,article,span{animation:none;transition:none;opacity:1;transform:none;}}`, - favicon: "/favicon.ico", - operationsSorter: "alpha", - orderSchemaPropertiesBy: "alpha", - tagsSorter: "alpha", - theme: "elysiajs", - }, - }), - ) - // Use for OpenAPI - .model({ - dataItemSchema, - dataSchema, - feedType, - }) + license: { + name: "MIT", + url: "https://github.com/HackHTU/RSSBook/blob/master/LICENSE", + }, + title: "RSSBook OpenAPI Documentation", + version: version, + }, + servers, + tags: [ + { + description: + "Content related to **Anime, Comics, and Games**, including news, reviews, and fan creations.", + name: "acg", + }, + { + description: + "Online **forums** for discussions, Q&A, and community interactions on various topics.", + name: "bbs", + }, + { + description: + "Topics covering **graphic design, UI/UX, industrial design**, and creative projects.", + name: "design", + }, + { + description: + "Information on **financial markets, investments, and personal finance**, including news and analysis.", + name: "finance", + }, + { + description: + "News, reviews, and discussions about **video games**, esports, and gaming culture.", + name: "gaming", + }, + { + description: + "Official information, **policies, services, and announcements** from government sources.", + name: "government", + }, + { + description: + "**Career opportunities, job listings, and professional advice** for job seekers.", + name: "jobs", + }, + { + description: + "**Live streaming** content including events, shows, and interactive broadcasts.", + name: "live", + }, + { + description: + "Various **media content**, including videos, audio, images, and interactive media.", + name: "multimedia", + }, + { + description: "**Latest news** and current events from around the world.", + name: "news", + }, + { + description: "Miscellaneous content that does not fit into other categories.", + name: "others", + }, + { + description: + "Resources, tutorials, and discussions about **coding, software development, and tech projects**.", + name: "programming", + }, + { + description: + "Books, articles, and **reading materials** for leisure, education, or research.", + name: "reading", + }, + { + description: "**Academic, scientific, and technical research** materials and studies.", + name: "research", + }, + { + description: + "Educational resources, **school-related news**, and learning materials for students and teachers.", + name: "school", + }, + { + description: + "**E-commerce**, product reviews, and guides for online and offline shopping.", + name: "shopping", + }, + { + description: + "Content and discussions from **social networking platforms**, trends, and viral posts.", + name: "socialmedia", + }, + { + description: + "Information and guides for **travel destinations, experiences, and tips**.", + name: "travel", + }, + { + description: "**Announcements and updates** about products, services, or projects.", + name: "updates", + }, + { + description: + "Personal or professional **blogs** covering various topics, stories, and experiences.", + name: "blog", + }, + { + description: + "Feed utilities and tools for enhancing the existing RSS/Atom feeds.\n> [!TIP]\n> **You can visit Feed Tools Helper to generate your feed**.", + name: "utils", + }, + { + description: "RSSBook related endpoints, including theme, documentation and metadata.", + name: "_", + }, + ], + }, + scalar: { + customCss: `main p,h1,h2,h3,h4,h5,h6,li,img,article,span{opacity:0;transform:translateY(2em);animation:starting-style .6s cubic-bezier(.22,.98,.35,1) forwards}@keyframes starting-style{from{opacity:0;transform:translateY(2em);filter:blur(5px);}to{opacity:1;transform:translateY(0);filter:blur(0);}}@media (prefers-reduced-motion:reduce){main p,h1,h2,h3,h4,h5,h6,li,img,article,span{animation:none;transition:none;opacity:1;transform:none;}}`, + favicon: "/favicon.ico", + operationsSorter: "alpha", + orderSchemaPropertiesBy: "alpha", + tagsSorter: "alpha", + theme: "elysiajs", + }, + }), ); }; diff --git a/pkgs/rssbook/src/plugins/render.test.ts b/pkgs/rssbook/src/plugins/render.test.ts new file mode 100644 index 0000000..f3534be --- /dev/null +++ b/pkgs/rssbook/src/plugins/render.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, test } from "bun:test"; +import { openapi } from "@elysiajs/openapi"; +import { Elysia, t } from "elysia"; +import { renderPlugin } from "./render"; + +const demoFeed = { + description: "Demo feed", + item: [ + { + date: new Date("2024-01-01T00:00:00.000Z"), + description: "Demo entry", + link: "https://example.com/posts/1", + title: "First post", + }, + ], + link: "https://example.com", + title: "Demo", +}; + +describe("renderPlugin", () => { + test("honors styled=false query after boolean coercion", async () => { + const app = new Elysia().use(renderPlugin).get("/demo", () => demoFeed); + + const response = await app.handle(new Request("http://localhost/demo?styled=false&type=rss")); + const xml = await response.text(); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("application/xml"); + expect(xml.match(/^<\?xml-stylesheet/g)).toBeNull(); + expect(xml.match(//g)).toHaveLength(1); + }); + + test("renders JSON feed output as JSON Feed data", async () => { + const app = new Elysia().use(renderPlugin).get("/demo", () => demoFeed); + + const response = await app.handle(new Request("http://localhost/demo?type=json")); + const body: { + description: string; + items: { + content_html: string; + date_modified: string; + title: string; + url: string; + }[]; + title: string; + version: string; + } = await response.json(); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("application/json"); + expect(body).toMatchObject({ + description: "Demo feed", + title: "Demo", + version: "https://jsonfeed.org/version/1", + }); + expect(body.items).toEqual([ + { + content_html: "Demo entry", + date_modified: "2024-01-01T00:00:00.000Z", + title: "First post", + url: "https://example.com/posts/1", + }, + ]); + }); + + test("returns raw feed data without renderer normalization", async () => { + const app = new Elysia().use(renderPlugin).get("/demo", () => demoFeed); + + const response = await app.handle(new Request("http://localhost/demo?type=raw")); + const body: { + description: string; + item: { + date: string; + description: string; + link: string; + title: string; + }[]; + link: string; + title: string; + } = await response.json(); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("application/json"); + expect(body).toEqual({ + ...demoFeed, + item: [ + { + ...demoFeed.item[0], + date: "2024-01-01T00:00:00.000Z", + }, + ], + }); + }); + + test("keeps route query schema when adding render query parameters to OpenAPI", async () => { + const app = new Elysia() + .use(openapi()) + .use(renderPlugin) + .get( + "/demo", + () => ({ + description: "Demo feed", + item: [], + link: "https://example.com", + title: "Demo", + }), + { + query: t.Object({ + foo: t.String({ + description: "Route-specific query parameter.", + }), + }), + }, + ); + + const response = await app.handle(new Request("http://localhost/openapi/json")); + const document = (await response.json()) as { + paths: { + "/demo": { + get: { + parameters: { name: string }[]; + }; + }; + }; + }; + + expect(document.paths["/demo"].get.parameters.map(({ name }) => name)).toEqual([ + "foo", + "styled", + "type", + ]); + }); +}); diff --git a/pkgs/rssbook/src/plugins/render.ts b/pkgs/rssbook/src/plugins/render.ts index 172d01c..8bd25e5 100644 --- a/pkgs/rssbook/src/plugins/render.ts +++ b/pkgs/rssbook/src/plugins/render.ts @@ -1,5 +1,5 @@ import { Elysia, t } from "elysia"; -import { type Data, dataSchema, feedType } from "@/types"; +import { type Data, feedData, feedType } from "@/types"; import { render } from "@/utils"; export const renderQuery = { @@ -15,11 +15,15 @@ export const renderQuery = { export const renderPlugin = new Elysia({ name: "RSSBook/Render", }) + .model({ + feedData, + feedQuery: t.Object(renderQuery), + feedType, + }) .guard({ as: "scoped", query: t.Object(renderQuery), - // TODO: improve response type - response: t.Union([t.String(), dataSchema]), + response: "feedData", schema: "standalone", }) .onAfterHandle( @@ -27,7 +31,7 @@ export const renderPlugin = new Elysia({ as: "scoped", }, ({ responseValue, set, query: { type, styled } }) => { - const isStyled = styled !== "false"; + const isStyled = !!(styled ?? true); switch (type) { case "json": diff --git a/pkgs/rssbook/src/routers/feeds/_example/_browser/index.start.ts b/pkgs/rssbook/src/routers/feeds/_example/_browser/index.start.ts new file mode 100644 index 0000000..09f33bd --- /dev/null +++ b/pkgs/rssbook/src/routers/feeds/_example/_browser/index.start.ts @@ -0,0 +1,46 @@ +import type { Data, DataItem } from "@/types"; +import { Source, t } from "@/utils"; +export default new Source({ + description: ``, + domain: "", + slug: "slug", + title: "", +}).feed( + { + description: ``, + fulltext: true, + language: ["en-US"], + maintainer: { name: "RSSBook" }, + title: "", + withImage: "If-Present", + }, + (app) => + app.get( + "/user/:username", + async ({ meta: { domain }, browser, params: { username } }) => { + const link = `https://${domain}/user/${username}`; + const lease = await browser.acquirePage(); + let description: string; + + try { + const { page } = lease; + await page.goto(link, { waitUntil: "domcontentloaded" }); + description = await page.content(); + } finally { + await lease.close(); + } + + return { + description, + item: [] satisfies DataItem[], + link, + title: "Hello World", + } satisfies Data; + }, + { + params: t.Object({ + username: t.String({}), + }), + }, + ), +); diff --git a/pkgs/rssbook/src/routers/feeds/_example/_browser/index.test.ts b/pkgs/rssbook/src/routers/feeds/_example/_browser/index.test.ts new file mode 100644 index 0000000..360e3e0 --- /dev/null +++ b/pkgs/rssbook/src/routers/feeds/_example/_browser/index.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, test } from "bun:test"; +import { Elysia } from "elysia"; +import type { BrowserContext, Page, Browser as PuppeteerBrowser, Target } from "puppeteer-core"; +import { Browser } from "@/browser"; +import { initPlugin } from "@/plugins"; +import type { Data } from "@/types"; +import source from "."; + +const bilibiliDynamicHTML = /* html */ ` + + +
鹿目圆
+
+
鹿目圆
+
2025年03月03日
+
馒头卡mvp,吼姆拉躺赢狗
+ + 晓美焰:救不了小圆怎么不找找自己问题 + + +
+
+
鹿目圆
+
2025年11月08日
+
好像被片姐盯上了,被误清的只能说抱歉了
+ +
+ + +`; + +class StaticHTMLBrowser extends Browser { + public constructor(private readonly html: string) { + super({ maxBrowsers: 1, maxContextsPerBrowser: 1, maxPagesPerContext: 1 }); + } + + protected createBrowser(): Promise { + return Promise.resolve(createStaticHTMLPuppeteerBrowser(this.html)); + } +} + +function createStaticHTMLPuppeteerBrowser(html: string): PuppeteerBrowser { + let browser: PuppeteerBrowser; + let contextClosed = false; + let pageClosed = false; + const target = { + page: async () => page, + type: () => "page", + } as Target; + const page = { + close: async () => { + pageClosed = true; + }, + content: async () => html, + goto: async () => null, + isClosed: () => pageClosed, + once: () => page, + target: () => target, + waitForSelector: async () => null, + } as unknown as Page; + let context: BrowserContext; + context = { + close: async () => { + contextClosed = true; + }, + get closed() { + return contextClosed; + }, + newPage: async () => page, + on: () => context, + } as unknown as BrowserContext; + + browser = { + close: async () => {}, + createBrowserContext: async () => context, + newPage: async () => page, + once: () => browser, + } as unknown as PuppeteerBrowser; + + return browser; +} + +describe("Browser example", () => { + test("builds Bilibili space dynamic feed from rendered HTML", async () => { + const sourceConfig = source.getConfig(); + const app = new Elysia() + .use( + initPlugin({ + browser: new StaticHTMLBrowser(bilibiliDynamicHTML), + }), + ) + .use(source.getApp()); + + const response = await app.handle( + new Request(`http://rssbook.test/${sourceConfig.slug}/bilibili/space/50/dynamic?type=raw`), + ); + const data = (await response.json()) as Data; + + expect(response.status).toBe(200); + expect(data.title).toBe("鹿目圆 - Bilibili Dynamics"); + expect(data.item).toHaveLength(2); + expect(data.item?.[0]?.link).toBe("https://www.bilibili.com/video/BV1MaXZYQEZr/"); + expect(data.item?.[0]?.image).toContain("/bfs/archive/"); + expect(data.item?.[1]?.title).toContain("好像被片姐盯上了"); + expect(data.item?.[1]?.image).toContain("/bfs/new_dyn/"); + }); +}); diff --git a/pkgs/rssbook/src/routers/feeds/_example/_browser/index.ts b/pkgs/rssbook/src/routers/feeds/_example/_browser/index.ts new file mode 100644 index 0000000..20c6dcf --- /dev/null +++ b/pkgs/rssbook/src/routers/feeds/_example/_browser/index.ts @@ -0,0 +1,152 @@ +import type { Data, DataItem } from "@/types"; +import { Source, t } from "@/utils"; + +const DYNAMIC_CARD_SELECTOR = ".bili-dyn-list__item"; +const CONTENT_SELECTORS = [ + ".bili-rich-text", + ".opus-paragraph-children", + ".bili-dyn-content__orig__desc", + ".bili-dyn-card-video__desc", + ".dyn-card-opus__summary", +]; + +function normalizeURL(value: string | undefined, baseURL: string): string | undefined { + if (!value) return undefined; + if (value.startsWith("//")) return `https:${value}`; + + try { + return new URL(value, baseURL).toString(); + } catch { + return undefined; + } +} + +function normalizeText(value: string | undefined): string { + return (value ?? "").replace(/\s+/g, " ").trim(); +} + +function escapeHTML(value: string): string { + return value + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} + +function parseBilibiliDate(value: string, parseDate: (value: string) => Date): Date { + const match = value.match(/\d{4}年\d{1,2}月\d{1,2}日/); + if (!match) return parseDate(value); + + const [year, month, day] = match[0].match(/\d+/g) ?? []; + return parseDate(`${year}-${month?.padStart(2, "0")}-${day?.padStart(2, "0")}T00:00:00+08:00`); +} + +function isContentImage(url: string): boolean { + return url.includes("/bfs/new_dyn/") || url.includes("/bfs/archive/"); +} + +function buildDescription( + text: string, + images: string[], + formatHTML: (html: string) => string, +): string { + const imageHTML = images.map( + (image) => `

`, + ); + return formatHTML([text ? `

${escapeHTML(text)}

` : "", ...imageHTML].join("")); +} + +export default new Source({ + description: "Rendered browser examples for pages that require JavaScript.", + domain: "bilibili.com", + slug: "browser", + title: "Browser Rendered Feeds", +}).feed( + { + browser: true, + description: "Render a Bilibili user space dynamic page and build an RSS feed from cards.", + fulltext: true, + language: "zh-CN", + maintainer: { name: "RSSBook" }, + title: "Bilibili Space Dynamics", + withImage: "If-Present", + }, + (app) => + app.get( + "/bilibili/space/:mid/dynamic", + async ({ browser, cache, date, formatHTML, load, params: { mid } }) => { + const link = `https://space.bilibili.com/${mid}/dynamic`; + + const html = await cache.tryGet(link, async () => { + const lease = await browser.acquirePage(); + + try { + const { page } = lease; + await page.goto(link, { waitUntil: "networkidle2" }); + await page.waitForSelector(DYNAMIC_CARD_SELECTOR, { timeout: 15_000 }).catch(() => {}); + return page.content(); + } finally { + await lease.close(); + } + }); + const $ = load(html); + const profileName = normalizeText( + $(".h-name, .n-name, .nickname, .username").first().text(), + ); + + const item = $(DYNAMIC_CARD_SELECTOR) + .toArray() + .map((element, index) => { + const card = $(element); + const author = + normalizeText(card.find(".bili-dyn-title__text, .bili-dyn-name").first().text()) || + profileName || + `Bilibili ${mid}`; + const rawDate = normalizeText(card.find(".bili-dyn-time").first().text()); + const text = + CONTENT_SELECTORS.map((selector) => + normalizeText(card.find(selector).first().text()), + ).find(Boolean) || "Bilibili dynamic"; + const videoLink = normalizeURL( + card.find("a.bili-dyn-card-video[href]").first().attr("href"), + link, + ); + const images = card + .find("img") + .toArray() + .map((image) => normalizeURL($(image).attr("src") || $(image).attr("data-src"), link)) + .filter((url): url is string => typeof url === "string" && isContentImage(url)); + const itemLink = videoLink ?? `${link}#dynamic-${index + 1}`; + const title = text.length > 80 ? `${text.slice(0, 80)}...` : text; + + return { + author: [{ name: author }], + date: parseBilibiliDate(rawDate, date), + description: buildDescription(text, images, formatHTML), + id: `${mid}:${rawDate || index}:${videoLink ?? images[0] ?? title}`, + image: images[0], + link: itemLink, + title, + video: videoLink, + } satisfies DataItem; + }) + .filter((item) => item.title && item.link); + + return { + description: `Bilibili space dynamic feed for ${profileName || mid}.`, + item, + language: "zh-CN", + link, + title: `${profileName || mid} - Bilibili Dynamics`, + } satisfies Data; + }, + { + params: t.Object({ + mid: t.String({ + description: "Bilibili user space id, for example 50.", + examples: ["50"], + }), + }), + }, + ), +); diff --git a/pkgs/rssbook/src/routers/feeds/_example/_html/index.ts b/pkgs/rssbook/src/routers/feeds/_example/_html/index.ts index ee38f1e..09533e8 100644 --- a/pkgs/rssbook/src/routers/feeds/_example/_html/index.ts +++ b/pkgs/rssbook/src/routers/feeds/_example/_html/index.ts @@ -391,9 +391,12 @@ export default new Source({ // ), }), /// - /// But do not define body, query or other parts - /// Defining these parts violates design principles and may cause errors - /// 但是不要定义 body query 等其他部分,定义这些部分违反了设计原则,还可能出现错误 + /// You may define route-specific query parameters here when the feed needs them. + /// The render plugin adds its own `type` and `styled` query parameters as a + /// standalone schema, so they can coexist with this route schema. + /// 当 Feed 需要时,可以在这里定义路由自己的 query 参数。 + /// render plugin 会以独立 schema 追加 `type` 和 `styled`, + /// 因此不会覆盖这里定义的路由 schema。 /// }, ), diff --git a/pkgs/rssbook/src/routers/feeds/_example/index.ts b/pkgs/rssbook/src/routers/feeds/_example/index.ts index f1b7946..548af2a 100644 --- a/pkgs/rssbook/src/routers/feeds/_example/index.ts +++ b/pkgs/rssbook/src/routers/feeds/_example/index.ts @@ -12,6 +12,7 @@ import { Category } from "@/utils"; import _api from "./_api"; +import _browser from "./_browser"; import _html from "./_html"; /** @@ -38,5 +39,6 @@ import _html from "./_html"; */ export default new Category("_example", "This is an example feed category.").use({ _api, // Source that fetches data from an API / 从 API 获取数据的源 + _browser, // Source that renders JavaScript pages with the browser / 使用浏览器渲染 JavaScript 页面的源 _html, // Source that scrapes data from HTML pages / 从 HTML 页面抓取数据的源 }); diff --git a/pkgs/rssbook/src/routers/feeds/multimedia/ithome/errors.ts b/pkgs/rssbook/src/routers/feeds/multimedia/ithome/errors.ts new file mode 100644 index 0000000..2bb3b59 --- /dev/null +++ b/pkgs/rssbook/src/routers/feeds/multimedia/ithome/errors.ts @@ -0,0 +1,11 @@ +import { RSSBookError } from "@/utils/error"; + +export class InvalidRankingTypeError extends RSSBookError { + public constructor(type: string) { + super({ + code: "INVALID_RANKING_TYPE", + message: `Invalid ranking type: ${type}`, + status: 400, + }); + } +} diff --git a/pkgs/rssbook/src/routers/feeds/multimedia/ithome/index.ts b/pkgs/rssbook/src/routers/feeds/multimedia/ithome/index.ts index 7e3e12e..a558a98 100644 --- a/pkgs/rssbook/src/routers/feeds/multimedia/ithome/index.ts +++ b/pkgs/rssbook/src/routers/feeds/multimedia/ithome/index.ts @@ -1,5 +1,6 @@ import type { Data, DataItem } from "@/types"; import { Source, t } from "@/utils"; +import { InvalidRankingTypeError } from "./errors"; const CATEGORIES: Record = { android: "Android", @@ -153,7 +154,7 @@ export default new Source({ ? "d-3" : undefined; if (!id) { - throw new Error(`Invalid ranking type: ${type}`); + throw new InvalidRankingTypeError(type); } const rankingUrl = "https://www.ithome.com/block/rank.html"; diff --git a/pkgs/rssbook/src/routers/feeds/multimedia/pingwest/index.ts b/pkgs/rssbook/src/routers/feeds/multimedia/pingwest/index.ts index 24884f0..64d7e31 100644 --- a/pkgs/rssbook/src/routers/feeds/multimedia/pingwest/index.ts +++ b/pkgs/rssbook/src/routers/feeds/multimedia/pingwest/index.ts @@ -1,6 +1,7 @@ import type { Data, DataItem } from "@/types"; import type { Cache } from "@/utils"; import { Source, t } from "@/utils"; +import { FeedNotFoundError } from "@/utils/error"; const ROOT_URL = "https://www.pingwest.com"; @@ -220,7 +221,7 @@ export default new Source({ }); if (!tagInfo.tagId) { - throw new Error(`Pingwest tag not found: ${tag}`); + throw new FeedNotFoundError(`Pingwest tag not found: ${tag}`); } const apiUrl = `${ROOT_URL}/api/tag_article_list?id=${tagInfo.tagId}&type=${Number(type) - 1}`; @@ -289,7 +290,7 @@ export default new Source({ }); if (!userInfo.realUid) { - throw new Error(`Pingwest user not found: ${uid}`); + throw new FeedNotFoundError(`Pingwest user not found: ${uid}`); } const apiUrl = `${ROOT_URL}/api/user_data?page=1&user_id=${userInfo.realUid}&tab=${type}`; diff --git a/pkgs/rssbook/src/routers/feeds/multimedia/sspai/index.ts b/pkgs/rssbook/src/routers/feeds/multimedia/sspai/index.ts index 57657f5..339c87b 100644 --- a/pkgs/rssbook/src/routers/feeds/multimedia/sspai/index.ts +++ b/pkgs/rssbook/src/routers/feeds/multimedia/sspai/index.ts @@ -1,5 +1,6 @@ import type { Data, DataItem } from "@/types"; import { Source, t } from "@/utils"; +import { FeedNotFoundError } from "@/utils/error"; type SSPAIAuthor = { nickname?: string; @@ -210,7 +211,7 @@ export default new Source({ }); if (userResponse.error !== 0 || !userResponse.data?.id) { - throw new Error(`SSPAI author not found: ${id}`); + throw new FeedNotFoundError(`SSPAI author not found: ${id}`); } authorId = String(userResponse.data.id); diff --git a/pkgs/rssbook/src/routers/utils/fetch.ts b/pkgs/rssbook/src/routers/utils/fetch.ts index 3b7c6ad..0a325a4 100644 --- a/pkgs/rssbook/src/routers/utils/fetch.ts +++ b/pkgs/rssbook/src/routers/utils/fetch.ts @@ -2,6 +2,16 @@ import type { CheerioAPI } from "cheerio"; import { Elysia, t } from "elysia"; import { injectPlugin, renderQuery } from "@/plugins"; import type { Data, DataItem } from "@/types"; +import { + FetchHtmlError, + InvalidDomainNameError, + InvalidDomainSuffixError, + InvalidProtocolError, + InvalidUrlError, + LocalAddressError, + LocalIpAddressError, + PrivateNetworkError, +} from "@/utils/error"; export default new Elysia({ detail: { @@ -51,12 +61,12 @@ Check out the [📕 RSSBook](https://github.com/HackHTU/RSSBook) for more detail try { parsedUrl = new URL(urlString); } catch { - throw new Error("Invalid URL format"); + throw new InvalidUrlError(); } // Only allow http and https protocols if (!["http:", "https:"].includes(parsedUrl.protocol)) { - throw new Error("Only http and https protocols are allowed"); + throw new InvalidProtocolError(); } // Skip further validation in test environment @@ -69,12 +79,12 @@ Check out the [📕 RSSBook](https://github.com/HackHTU/RSSBook) for more detail // Disallow localhost and local hostnames const localHostnames = ["localhost", "127.0.0.1", "::1", "0.0.0.0"]; if (localHostnames.includes(hostname)) { - throw new Error("Local addresses are not allowed"); + throw new LocalAddressError(); } // Disallow .local and .localhost TLDs if (hostname.endsWith(".local") || hostname.endsWith(".localhost")) { - throw new Error("Local domain suffixes are not allowed"); + throw new InvalidDomainSuffixError(); } // Disallow IP addresses (IPv4 and IPv6) @@ -84,11 +94,11 @@ Check out the [📕 RSSBook](https://github.com/HackHTU/RSSBook) for more detail const ipv6Pattern = /^(\[)?[0-9a-f:]+(\])?$/i; if (ipv4Pattern.test(hostname)) { - throw new Error("IP addresses are not allowed"); + throw new LocalIpAddressError(); } if (ipv6Pattern.test(hostname) || hostname.includes(":")) { - throw new Error("IP addresses are not allowed"); + throw new LocalIpAddressError(); } // Disallow private network ranges (additional check for edge cases) @@ -103,13 +113,13 @@ Check out the [📕 RSSBook](https://github.com/HackHTU/RSSBook) for more detail for (const pattern of privateIpPatterns) { if (pattern.test(hostname)) { - throw new Error("Private network addresses are not allowed"); + throw new PrivateNetworkError(); } } // Ensure hostname has at least one dot (is a proper domain) if (!hostname.includes(".")) { - throw new Error("Invalid domain name"); + throw new InvalidDomainNameError(); } }; @@ -282,7 +292,7 @@ Check out the [📕 RSSBook](https://github.com/HackHTU/RSSBook) for more detail return data; } catch (error) { - throw new Error(`Failed to fetch or parse HTML from ${url}: ${error}`); + throw new FetchHtmlError(url, error); } }, { diff --git a/pkgs/rssbook/src/routers/utils/filter.ts b/pkgs/rssbook/src/routers/utils/filter.ts index 6074691..5640584 100644 --- a/pkgs/rssbook/src/routers/utils/filter.ts +++ b/pkgs/rssbook/src/routers/utils/filter.ts @@ -3,6 +3,7 @@ import { ofetch } from "ofetch"; import { injectPlugin, renderQuery } from "@/plugins"; import type { Data } from "@/types"; import { filter, parse } from "@/utils"; +import { FilterFeedError, InvalidOverrideJsonError } from "@/utils/error"; import type { FilterOptions } from "@/utils/feeds/filter"; export default new Elysia({ @@ -91,7 +92,10 @@ Filter feed items by keywords, date, author, categories, or limit count. try { overrideData = JSON.parse(override); } catch (error) { - throw new Error(`Invalid override JSON: ${error}`); + throw new InvalidOverrideJsonError( + `Invalid override JSON: ${error instanceof Error ? error.message : String(error)}`, + error, + ); } } @@ -100,7 +104,10 @@ Filter feed items by keywords, date, author, categories, or limit count. return filtered; } catch (error) { - throw new Error(`Failed to fetch or filter feed: ${error}`); + throw new FilterFeedError( + `Failed to fetch or filter feed: ${error instanceof Error ? error.message : String(error)}`, + error, + ); } }, { diff --git a/pkgs/rssbook/src/routers/utils/intersection.ts b/pkgs/rssbook/src/routers/utils/intersection.ts index b6bdcfa..989f7bf 100644 --- a/pkgs/rssbook/src/routers/utils/intersection.ts +++ b/pkgs/rssbook/src/routers/utils/intersection.ts @@ -2,7 +2,7 @@ import { Elysia, t } from "elysia"; import { ofetch } from "ofetch"; import { injectPlugin, renderQuery } from "@/plugins"; import type { Data } from "@/types"; -import { intersection, parse } from "@/utils"; +import { IntersectionFeedError, InvalidOverrideJsonError, intersection, parse } from "@/utils"; export default new Elysia({ detail: { @@ -21,7 +21,7 @@ Returns only items that appear in **all** provided feeds, based on item ID, titl "/", async ({ query: { feeds, override }, logger }) => { if (feeds.length < 2) { - throw new Error("At least 2 feeds are required for intersection"); + throw new IntersectionFeedError("At least 2 feeds are required for intersection"); } try { @@ -46,7 +46,7 @@ Returns only items that appear in **all** provided feeds, based on item ID, titl .filter((result): result is Data => result !== null); if (datas.length < 2) { - throw new Error("At least 2 valid feeds are required for intersection"); + throw new IntersectionFeedError("At least 2 valid feeds are required for intersection"); } // Parse override if provided @@ -55,7 +55,10 @@ Returns only items that appear in **all** provided feeds, based on item ID, titl try { overrideData = JSON.parse(override); } catch (error) { - throw new Error(`Invalid override JSON: ${error}`); + throw new InvalidOverrideJsonError( + `Invalid override JSON: ${error instanceof Error ? error.message : String(error)}`, + error, + ); } } @@ -65,7 +68,10 @@ Returns only items that appear in **all** provided feeds, based on item ID, titl return result; } catch (error) { - throw new Error(`Failed to compute intersection: ${error}`); + throw new IntersectionFeedError( + `Failed to compute intersection: ${error instanceof Error ? error.message : String(error)}`, + error, + ); } }, { diff --git a/pkgs/rssbook/src/routers/utils/sort.ts b/pkgs/rssbook/src/routers/utils/sort.ts index 645d9ce..3f1e75b 100644 --- a/pkgs/rssbook/src/routers/utils/sort.ts +++ b/pkgs/rssbook/src/routers/utils/sort.ts @@ -3,6 +3,7 @@ import { ofetch } from "ofetch"; import { injectPlugin, renderQuery } from "@/plugins"; import type { Data } from "@/types"; import { parse, sort } from "@/utils"; +import { InvalidOverrideJsonError, SortFeedError } from "@/utils/error"; export default new Elysia({ detail: { @@ -29,7 +30,10 @@ By default, sorts items in **descending order** (newest first).`, try { overrideData = JSON.parse(override); } catch (error) { - throw new Error(`Invalid override JSON: ${error}`); + throw new InvalidOverrideJsonError( + `Invalid override JSON: ${error instanceof Error ? error.message : String(error)}`, + error, + ); } } @@ -41,7 +45,10 @@ By default, sorts items in **descending order** (newest first).`, ...overrideData, }; } catch (error) { - throw new Error(`Failed to fetch or sort feed: ${error}`); + throw new SortFeedError( + `Failed to fetch or sort feed: ${error instanceof Error ? error.message : String(error)}`, + error, + ); } }, { diff --git a/pkgs/rssbook/src/routers/utils/transform.ts b/pkgs/rssbook/src/routers/utils/transform.ts index 1d46173..b4f8dfa 100644 --- a/pkgs/rssbook/src/routers/utils/transform.ts +++ b/pkgs/rssbook/src/routers/utils/transform.ts @@ -2,6 +2,7 @@ import { Elysia, t } from "elysia"; import { injectPlugin, renderQuery } from "@/plugins"; import { allFeedTypes, type Data, type FeedType } from "@/types"; import { parse } from "@/utils"; +import { TransformFeedError } from "@/utils/error"; export default new Elysia({ detail: { @@ -32,7 +33,10 @@ Transform feed items to a different format. return data; } catch (error) { - throw new Error(`Failed to fetch or parse feed from ${feed}: ${error}`); + throw new TransformFeedError( + `Failed to fetch or parse feed from ${feed}: ${error instanceof Error ? error.message : String(error)}`, + error, + ); } }, { diff --git a/pkgs/rssbook/src/routers/utils/union.ts b/pkgs/rssbook/src/routers/utils/union.ts index b2d8ce6..d8b6787 100644 --- a/pkgs/rssbook/src/routers/utils/union.ts +++ b/pkgs/rssbook/src/routers/utils/union.ts @@ -2,7 +2,7 @@ import { Elysia, t } from "elysia"; import { ofetch } from "ofetch"; import { injectPlugin, renderQuery } from "@/plugins"; import type { Data } from "@/types"; -import { parse, union } from "@/utils"; +import { InvalidOverrideJsonError, parse, UnionFeedError, union } from "@/utils"; export default new Elysia({ detail: { @@ -20,7 +20,7 @@ Returns all unique items from the provided feeds, removing duplicates based on i "/", async ({ query: { feeds, override }, logger }) => { if (feeds.length < 2) { - throw new Error("At least 2 feeds are required for union"); + throw new UnionFeedError("At least 2 feeds are required for union"); } const promises = feeds.map(async (feedUrl) => { @@ -50,7 +50,10 @@ Returns all unique items from the provided feeds, removing duplicates based on i try { overrideData = JSON.parse(override); } catch (error) { - throw new Error(`Invalid override JSON: ${error}`); + throw new InvalidOverrideJsonError( + `Invalid override JSON: ${error instanceof Error ? error.message : String(error)}`, + error, + ); } } diff --git a/pkgs/rssbook/src/types/data.ts b/pkgs/rssbook/src/types/data.ts index 5d7fabf..6aced7a 100644 --- a/pkgs/rssbook/src/types/data.ts +++ b/pkgs/rssbook/src/types/data.ts @@ -280,6 +280,11 @@ export const dataSchema = t.Object( title: "Feed Data Schema", }, ); + +export const feedData = t.Union([dataSchema, t.String()], { + description: "The feed data to be rendered.", + title: "Feed Data", +}); export type Data = Static; export const dataValidator = getSchemaValidator(dataSchema); @@ -291,7 +296,7 @@ export function parseData(obj: unknown): Data { const result = dataValidator.safeParse(obj); if (!result.success) { - throw new Error(`Data Validation Error: ${result.error}`); + throw new DataValidationError(`Data Validation Error: ${result.error}`); } return { ...EMPTY_DATA, @@ -315,3 +320,5 @@ export type FeedType = Static; export function isFeedType(type: string): type is FeedType { return (allFeedTypes as readonly string[]).includes(type); } + +import { DataValidationError } from "@/utils/error"; diff --git a/pkgs/rssbook/src/types/route.ts b/pkgs/rssbook/src/types/route.ts index 6a69cbd..932ee08 100644 --- a/pkgs/rssbook/src/types/route.ts +++ b/pkgs/rssbook/src/types/route.ts @@ -46,4 +46,14 @@ export interface RouteConfig { fulltext?: boolean; withImage?: "Always" | "If-Present" | "None"; language: MaybeArray; + /** + * Mark this feed route as using Puppeteer browser rendering. + * + * Feed handlers receive a non-optional `ctx.browser` from the app context. + * This flag is route metadata for OpenAPI documentation and source readers; + * it does not sandbox access at runtime. If the app was created with + * `browser: false`, using `ctx.browser` still throws a browser unavailable + * error. + */ + browser?: boolean; } diff --git a/pkgs/rssbook/src/types/source.ts b/pkgs/rssbook/src/types/source.ts index fd4ce4c..894dd7f 100644 --- a/pkgs/rssbook/src/types/source.ts +++ b/pkgs/rssbook/src/types/source.ts @@ -44,15 +44,26 @@ export interface SourceConfigs< description: string; /** - * The root domain of the source + * The website domain for this source. * - * You can use `meta` in route handlers to get the root URL. + * This is metadata for building upstream request URLs and feed links. It is + * not the RSSBook route URL; feed routes are mounted with the source `slug` + * as their prefix, for example `/example/latest`. + * + * You can read it from `meta.domain` in route handlers. * * @example * ```ts - * app => app.get("/", ({ meta: { domain } }) => { - * const link = ``https://${domain}/some/path`; - * } + * (app) => + * app.get("/latest", ({ meta: { domain } }) => { + * const link = `https://${domain}/some/path`; + * + * return { + * title: "Latest", + * link, + * item: [], + * }; + * }); * ``` */ domain: string; diff --git a/pkgs/rssbook/src/types/utils.ts b/pkgs/rssbook/src/types/utils.ts index 718c03c..0697a6e 100644 --- a/pkgs/rssbook/src/types/utils.ts +++ b/pkgs/rssbook/src/types/utils.ts @@ -3,8 +3,12 @@ export type DeepPartial = T extends object [P in keyof T]?: DeepPartial; } : T; - export type MaybeArray = T | T[]; +export type NonEmptyArray = [T, ...T[]]; +export type Awaitable = T | Promise; +export type Prettify = { + [K in keyof T]: T[K]; +} & {}; // Validate slug format: only lowercase letters, numbers, and hyphens are allowed. type Lower = @@ -54,9 +58,3 @@ type _IsValid = S extends "" ? false : _IsValidInternal; * Only allows lowercase letters, numbers, and hyphens. */ export type Slug = _IsValid extends true ? S : never; - -export type NonEmptyArray = [T, ...T[]]; - -export type Prettify = { - [K in keyof T]: T[K]; -} & {}; diff --git a/pkgs/rssbook/src/utils/browser/cdp.test.ts b/pkgs/rssbook/src/utils/browser/cdp.test.ts new file mode 100644 index 0000000..68b0615 --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/cdp.test.ts @@ -0,0 +1,44 @@ +import { afterEach, describe, expect, mock, test } from "bun:test"; +import { BrowserEndpointError, UnsupportedProtocolError } from "@/utils/error"; +import { resolveBrowserWSEndpoint } from "./cdp"; + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +describe("resolveBrowserWSEndpoint", () => { + test("passes through WebSocket endpoints", async () => { + await expect(resolveBrowserWSEndpoint("wss://example.com/session")).resolves.toBe( + "wss://example.com/session", + ); + }); + + test("discovers HTTP endpoints through /json/version", async () => { + globalThis.fetch = Object.assign( + mock(async (url: string | URL | Request) => { + expect(String(url)).toBe("https://example.com/cdp/json/version"); + return Response.json({ webSocketDebuggerUrl: "wss://example.com/session" }); + }), + { preconnect: originalFetch.preconnect }, + ); + await expect(resolveBrowserWSEndpoint("https://example.com/cdp")).resolves.toBe( + "wss://example.com/session", + ); + }); + + test("rejects unsupported and invalid endpoints", async () => { + await expect(resolveBrowserWSEndpoint("ftp://example.com")).rejects.toBeInstanceOf( + UnsupportedProtocolError, + ); + globalThis.fetch = Object.assign( + mock(async () => Response.json({})), + { + preconnect: originalFetch.preconnect, + }, + ); + await expect(resolveBrowserWSEndpoint("https://example.com")).rejects.toBeInstanceOf( + BrowserEndpointError, + ); + }); +}); diff --git a/pkgs/rssbook/src/utils/browser/cdp.ts b/pkgs/rssbook/src/utils/browser/cdp.ts new file mode 100644 index 0000000..f45f390 --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/cdp.ts @@ -0,0 +1,36 @@ +import { BrowserEndpointError, UnsupportedProtocolError } from "@/utils/error"; + +/** Resolve an HTTP Chrome debugging endpoint or normalize a WebSocket endpoint. */ +export async function resolveBrowserWSEndpoint(endpoint: string | URL): Promise { + const url = new URL(endpoint); + + if (url.protocol === "ws:" || url.protocol === "wss:") { + return url.toString(); + } + + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new UnsupportedProtocolError(url.protocol); + } + + const pathname = url.pathname.replace(/\/$/, ""); + url.pathname = pathname.endsWith("/json/version") ? pathname : `${pathname}/json/version`; + + const response = await fetch(url); + if (!response.ok) { + throw new BrowserEndpointError( + `Failed to resolve Puppeteer browser endpoint from ${url}: ${response.status} ${response.statusText}`, + ); + } + + const data: unknown = await response.json(); + if ( + typeof data !== "object" || + data === null || + !("webSocketDebuggerUrl" in data) || + typeof data.webSocketDebuggerUrl !== "string" + ) { + throw new BrowserEndpointError(`Invalid Puppeteer browser version response from ${url}`); + } + + return data.webSocketDebuggerUrl; +} diff --git a/pkgs/rssbook/src/utils/browser/cookies.test.ts b/pkgs/rssbook/src/utils/browser/cookies.test.ts new file mode 100644 index 0000000..f25608a --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/cookies.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, mock, test } from "bun:test"; +import type { Cookie } from "puppeteer-core"; +import { createFakeContext } from "@/browser/test-helpers"; +import { + cookieHeaderToCookies, + cookiesToHeader, + getCookieHeader, + setCookieHeader, +} from "./cookies"; + +describe("browser cookie utilities", () => { + test("preserves Cookie values without URI rewriting", () => { + expect(cookiesToHeader([{ name: "token", value: "a=b==" }])).toBe("token=a=b=="); + expect(cookieHeaderToCookies("token=a=b==", "https://example.com/path")).toEqual([ + { domain: "example.com", name: "token", path: "/", secure: true, value: "a=b==" }, + ]); + }); + + test("reads and applies Cookie headers through BrowserContext", async () => { + const cookies = [{ name: "token", value: "value" }] as Cookie[]; + const context = createFakeContext({ cookies: mock(async () => cookies) }); + await expect(getCookieHeader(context)).resolves.toBe("token=value"); + await setCookieHeader(context, "token=value", "https://example.com"); + expect(context.setCookie).toHaveBeenCalledWith({ + domain: "example.com", + name: "token", + path: "/", + secure: true, + value: "value", + }); + }); +}); diff --git a/pkgs/rssbook/src/utils/browser/cookies.ts b/pkgs/rssbook/src/utils/browser/cookies.ts new file mode 100644 index 0000000..af8e292 --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/cookies.ts @@ -0,0 +1,50 @@ +import type { BrowserContext, Cookie, CookieData, Page } from "puppeteer-core"; + +export type CookieTarget = BrowserContext | Page; + +/** Convert Puppeteer cookies to a Cookie request header without rewriting values. */ +export function cookiesToHeader(cookies: readonly Pick[]): string { + return cookies.map(({ name, value }) => (name ? `${name}=${value}` : value)).join("; "); +} + +/** Parse a Cookie request header into Puppeteer browser-context cookie data. */ +export function cookieHeaderToCookies(cookieHeader: string, target: string | URL): CookieData[] { + const url = typeof target === "string" ? new URL(target) : target; + + return cookieHeader + .split(";") + .map((part) => part.trim()) + .filter(Boolean) + .map((part) => { + const separatorIndex = part.indexOf("="); + const name = separatorIndex < 0 ? "" : part.slice(0, separatorIndex).trim(); + const value = separatorIndex < 0 ? part : part.slice(separatorIndex + 1).trim(); + + return { + domain: url.hostname, + name, + path: "/", + secure: url.protocol === "https:", + value, + }; + }); +} + +/** Read cookies and format them as a Cookie request header. */ +export async function getCookieHeader(target: CookieTarget): Promise { + return cookiesToHeader(await getBrowserContext(target).cookies()); +} + +/** Parse and apply a Cookie request header to a page or browser context. */ +export async function setCookieHeader( + target: CookieTarget, + cookieHeader: string, + url: string | URL, +): Promise { + const cookies = cookieHeaderToCookies(cookieHeader, url); + if (cookies.length > 0) await getBrowserContext(target).setCookie(...cookies); +} + +function getBrowserContext(target: CookieTarget): BrowserContext { + return "browserContext" in target ? target.browserContext() : target; +} diff --git a/pkgs/rssbook/src/utils/browser/fingerprint.test.ts b/pkgs/rssbook/src/utils/browser/fingerprint.test.ts new file mode 100644 index 0000000..6d96ae2 --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/fingerprint.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, mock, test } from "bun:test"; +import type { CDPSession } from "puppeteer-core"; +import { createFakePage } from "@/browser/test-helpers"; +import { + setColorDepth, + setDeviceMemory, + setHardwareConcurrency, + setLanguages, +} from "./fingerprint"; + +describe("browser fingerprint utilities", () => { + test("sets languages in both headers and new documents", async () => { + const page = createFakePage({ + evaluateOnNewDocument: mock(async () => ({ identifier: "language" })), + setExtraHTTPHeaders: mock(async () => {}), + }); + await setLanguages(page, ["en-US", "en"]); + expect(page.setExtraHTTPHeaders).toHaveBeenCalledWith({ + "Accept-Language": "en-US,en", + }); + expect(page.evaluateOnNewDocument).toHaveBeenCalledTimes(1); + }); + + test("sets hardware concurrency through CDP", async () => { + const send = mock(async () => ({})); + const detach = mock(async () => {}); + const page = createFakePage({ + createCDPSession: mock(async () => ({ detach, send }) as unknown as CDPSession), + }); + await setHardwareConcurrency(page, 8); + expect(send).toHaveBeenCalledWith("Emulation.setHardwareConcurrencyOverride", { + hardwareConcurrency: 8, + }); + expect(detach).toHaveBeenCalledTimes(1); + }); + + test("installs device memory and color depth scripts", async () => { + const page = createFakePage({ + evaluateOnNewDocument: mock(async () => ({ identifier: "fingerprint" })), + }); + await setDeviceMemory(page, 8); + await setColorDepth(page, 24); + expect(page.evaluateOnNewDocument).toHaveBeenCalledTimes(2); + }); + + test("rejects invalid values", async () => { + const page = createFakePage(); + await expect(setLanguages(page, [])).rejects.toBeInstanceOf(RangeError); + await expect(setHardwareConcurrency(page, 0)).rejects.toBeInstanceOf(RangeError); + await expect(setDeviceMemory(page, 0)).rejects.toBeInstanceOf(RangeError); + await expect(setColorDepth(page, 0)).rejects.toBeInstanceOf(RangeError); + }); +}); diff --git a/pkgs/rssbook/src/utils/browser/fingerprint.ts b/pkgs/rssbook/src/utils/browser/fingerprint.ts new file mode 100644 index 0000000..1cccd68 --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/fingerprint.ts @@ -0,0 +1,57 @@ +import type { Page } from "puppeteer-core"; + +/** Keep the Accept-Language header and navigator.languages in sync. */ +export async function setLanguages(page: Page, languages: readonly string[]): Promise { + if (languages.length === 0) throw new RangeError("languages must not be empty."); + const values = [...languages]; + await page.setExtraHTTPHeaders({ "Accept-Language": values.join(",") }); + await page.evaluateOnNewDocument((nextLanguages) => { + Object.defineProperty(Navigator.prototype, "languages", { + configurable: true, + get: () => Object.freeze([...nextLanguages]), + }); + }, values); +} + +/** Override navigator.hardwareConcurrency through Chrome DevTools Protocol. */ +export async function setHardwareConcurrency(page: Page, value: number): Promise { + if (!Number.isInteger(value) || value < 1) { + throw new RangeError("hardwareConcurrency must be a positive integer."); + } + const session = await page.createCDPSession(); + try { + await session.send("Emulation.setHardwareConcurrencyOverride", { + hardwareConcurrency: value, + }); + } finally { + await session.detach(); + } +} + +/** Override navigator.deviceMemory before site scripts execute. */ +export async function setDeviceMemory(page: Page, value: number): Promise { + if (!Number.isFinite(value) || value <= 0) { + throw new RangeError("deviceMemory must be greater than zero."); + } + await page.evaluateOnNewDocument((nextValue) => { + Object.defineProperty(Navigator.prototype, "deviceMemory", { + configurable: true, + get: () => nextValue, + }); + }, value); +} + +/** Override screen.colorDepth and screen.pixelDepth before navigation. */ +export async function setColorDepth(page: Page, value: number): Promise { + if (!Number.isInteger(value) || value < 1) { + throw new RangeError("colorDepth must be a positive integer."); + } + await page.evaluateOnNewDocument((nextValue) => { + for (const property of ["colorDepth", "pixelDepth"]) { + Object.defineProperty(Screen.prototype, property, { + configurable: true, + get: () => nextValue, + }); + } + }, value); +} diff --git a/pkgs/rssbook/src/utils/browser/index.ts b/pkgs/rssbook/src/utils/browser/index.ts new file mode 100644 index 0000000..b7499e4 --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/index.ts @@ -0,0 +1,5 @@ +export * from "./cdp"; +export * from "./cookies"; +export * from "./fingerprint"; +export * from "./resources"; +export * from "./response"; diff --git a/pkgs/rssbook/src/utils/browser/resources.test.ts b/pkgs/rssbook/src/utils/browser/resources.test.ts new file mode 100644 index 0000000..748ee9f --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/resources.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, mock, test } from "bun:test"; +import type { HTTPRequest } from "puppeteer-core"; +import { createFakePage } from "@/browser/test-helpers"; +import { allowResources, blockResources } from "./resources"; + +describe("browser resource utilities", () => { + test("blocks and allows selected resources cooperatively", async () => { + const handlers: Array<(request: HTTPRequest) => void> = []; + const page = createFakePage({ + on: mock((event, handler) => { + if (event === "request") handlers.push(handler); + return page; + }), + setRequestInterception: mock(async () => {}), + }); + const image = createRequest("image"); + const script = createRequest("script"); + await blockResources(page, { resourceTypes: ["image"] }); + handlers[0]?.(image.request); + handlers[0]?.(script.request); + await allowResources(page, { resourceTypes: ["script"] }); + handlers[1]?.(image.request); + handlers[1]?.(script.request); + expect(image.abort).toHaveBeenCalledTimes(2); + expect(script.continueRequest).toHaveBeenCalledTimes(2); + }); +}); + +function createRequest(resourceType: "image" | "script") { + const abort = mock(async () => {}); + const continueRequest = mock(async () => {}); + const request = { + abort, + continue: continueRequest, + continueRequestOverrides: () => ({}), + isInterceptResolutionHandled: () => false, + resourceType: () => resourceType, + } as unknown as HTTPRequest; + return { abort, continueRequest, request }; +} diff --git a/pkgs/rssbook/src/utils/browser/resources.ts b/pkgs/rssbook/src/utils/browser/resources.ts new file mode 100644 index 0000000..e0c094e --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/resources.ts @@ -0,0 +1,44 @@ +import type { HTTPRequest, Page, ResourceType } from "puppeteer-core"; + +const DEFAULT_BLOCKED_RESOURCES = ["image", "media", "font"] satisfies ResourceType[]; +const DEFAULT_INTERCEPT_PRIORITY = 0; + +export interface ResourceFilterOptions { + priority?: number; + resourceTypes?: readonly ResourceType[]; +} + +/** Block selected resource types while allowing every other request. */ +export async function blockResources( + page: Page, + options: ResourceFilterOptions = {}, +): Promise { + const resourceTypes = new Set(options.resourceTypes ?? DEFAULT_BLOCKED_RESOURCES); + await filterResources(page, (request) => !resourceTypes.has(request.resourceType()), options); +} + +/** Allow selected resource types while blocking every other request. */ +export async function allowResources(page: Page, options: ResourceFilterOptions): Promise { + const resourceTypes = new Set(options.resourceTypes ?? []); + await filterResources(page, (request) => resourceTypes.has(request.resourceType()), options); +} + +async function filterResources( + page: Page, + allow: (request: HTTPRequest) => boolean, + options: ResourceFilterOptions, +): Promise { + const priority = options.priority ?? DEFAULT_INTERCEPT_PRIORITY; + + await page.setRequestInterception(true); + page.on("request", (request) => { + if (request.isInterceptResolutionHandled()) return; + + if (allow(request)) { + void request.continue(request.continueRequestOverrides(), priority); + return; + } + + void request.abort(undefined, priority); + }); +} diff --git a/pkgs/rssbook/src/utils/browser/response.test.ts b/pkgs/rssbook/src/utils/browser/response.test.ts new file mode 100644 index 0000000..4a579e5 --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/response.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, mock, test } from "bun:test"; +import type { HTTPResponse } from "puppeteer-core"; +import { createFakePage } from "@/browser/test-helpers"; +import { waitForResponse } from "./response"; + +describe("waitForResponse", () => { + test("registers the waiter before its trigger", async () => { + const order: string[] = []; + const response = { json: mock(async () => ({ ok: true })) } as unknown as HTTPResponse; + const page = createFakePage({ + waitForResponse: mock(async () => { + order.push("wait"); + return response; + }), + }); + expect( + await waitForResponse( + page, + () => true, + async () => void order.push("trigger"), + ), + ).toBe(response); + expect(order).toEqual(["wait", "trigger"]); + }); +}); diff --git a/pkgs/rssbook/src/utils/browser/response.ts b/pkgs/rssbook/src/utils/browser/response.ts new file mode 100644 index 0000000..2c82a6f --- /dev/null +++ b/pkgs/rssbook/src/utils/browser/response.ts @@ -0,0 +1,14 @@ +import type { HTTPResponse, Page, WaitTimeoutOptions } from "puppeteer-core"; +import type { Awaitable } from "@/types/utils"; + +/** Register a response waiter before optionally triggering navigation or interaction. */ +export async function waitForResponse( + page: Page, + predicate: string | ((response: HTTPResponse) => Awaitable), + trigger?: () => Awaitable, + options?: WaitTimeoutOptions, +): Promise { + const responsePromise = page.waitForResponse(predicate, options); + await trigger?.(); + return responsePromise; +} diff --git a/pkgs/rssbook/src/utils/cache.test.ts b/pkgs/rssbook/src/utils/cache.test.ts deleted file mode 100644 index b85e238..0000000 --- a/pkgs/rssbook/src/utils/cache.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { createStorage } from "unstorage"; -import lruCacheDriver from "unstorage/drivers/lru-cache"; -import nullDriver from "unstorage/drivers/null"; -import Cache from "@/utils/cache"; - -describe("cache", () => { - describe("Cache - LRU Cache", () => { - const cache = new Cache( - createStorage({ - driver: lruCacheDriver({ - ttl: 300, - }), - }), - ); - - test("should set and get string values", async () => { - await cache.set("key", "value"); - expect(await cache.get("key")).toBe("value"); - }); - - test("should return null for non-existent keys", async () => { - expect(await cache.get("nonexistent")).toBeNull(); - }); - - test("should set and get values with custom TTL", async () => { - await cache.set("key2", "value2", 100); - expect(await cache.get("key2")).toBe("value2"); - }); - - test("should store and retrieve complex objects", async () => { - const complexObj = { - age: 25, - name: "test", - nested: { - array: [1, 2, 3], - key: "value", - }, - }; - await cache.set("complex", complexObj); - expect(await cache.get("complex")).toEqual(complexObj); - }); - - test("should store and retrieve arrays", async () => { - const arr = [1, 2, 3, "test", { key: "value" }]; - await cache.set("array", arr); - expect(await cache.get("array")).toEqual(arr); - }); - - test("should store primitive values", async () => { - await cache.set("number", 42); - expect(await cache.get("number")).toBe(42); - - await cache.set("boolean", true); - expect(await cache.get("boolean")).toBe(true); - - await cache.set("null", null); - expect(await cache.get("null")).toBeNull(); - }); - - test("should delete cached items", async () => { - await cache.set("to-delete", "value"); - expect(await cache.get("to-delete")).toBe("value"); - - await cache.del("to-delete"); - expect(await cache.get("to-delete")).toBeNull(); - }); - - test("should handle tryGet with cache hit", async () => { - await cache.set("cached-url", "cached-value"); - - const result = await cache.tryGet("cached-url", async () => { - throw new Error("Fetcher should not be called"); - }); - - expect(result).toBe("cached-value"); - }); - - test("should handle tryGet with cache miss", async () => { - const fetcher = async (key: string) => { - return `fetched-${key}`; - }; - - const result = await cache.tryGet("new-url", fetcher); - expect(result).toBe("fetched-new-url"); - - // Verify it was cached - expect(await cache.get("new-url")).toBe("fetched-new-url"); - }); - - test("should expire items after TTL", async () => { - await cache.set("expiring", "value", 50); // 50ms TTL - expect(await cache.get("expiring")).toBe("value"); - - // Wait for expiration - await new Promise((resolve) => setTimeout(resolve, 100)); - - expect(await cache.get("expiring")).toBeNull(); - }); - }); - - describe("Cache - with prefix", () => { - const cache = new Cache( - createStorage({ - driver: lruCacheDriver({ - ttl: 1000, - }), - }), - { - defaultMaxAgeMs: 1000, - prefix: "test:", - }, - ); - - test("should apply prefix to keys", async () => { - await cache.set("key", "value"); - expect(await cache.get("key")).toBe("value"); - }); - - test("should use default TTL from options", async () => { - await cache.set("key-with-default-ttl", "value"); - expect(await cache.get("key-with-default-ttl")).toBe("value"); - }); - }); - - describe("Cache - Null Cache", () => { - const cache = new Cache( - createStorage({ - driver: nullDriver(), - }), - ); - - test("should not persist any data", async () => { - await cache.set("key", "value"); - // Null driver doesn't persist data - expect(await cache.get("key")).toBeNull(); - }); - - test("should always trigger fetcher in tryGet", async () => { - let fetcherCalled = false; - - const result = await cache.tryGet("url", async () => { - fetcherCalled = true; - return "fetched"; - }); - - expect(fetcherCalled).toBe(true); - expect(result).toBe("fetched"); - }); - }); -}); diff --git a/pkgs/rssbook/src/utils/cache.ts b/pkgs/rssbook/src/utils/cache.ts deleted file mode 100644 index b10f452..0000000 --- a/pkgs/rssbook/src/utils/cache.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { createStorage, type Storage } from "unstorage"; -import lruCacheDriver from "unstorage/drivers/lru-cache"; - -/** - * Primitive types that can be stored directly - */ -type StoragePrimitive = null | string | number | boolean | Date; - -/** - * Values that can be safely stored and serialized - */ -type StorageValue = StoragePrimitive | { [key: string]: StorageValue } | StorageValue[]; - -/** - * Configuration options for Cache instance - */ -type CacheOptions = { - /** Key prefix for all cache operations */ - prefix: string; - /** Default TTL in milliseconds for cached items */ - defaultMaxAgeMs: number; -}; - -/** - * Cache metadata with TTL information - */ -interface CacheEntry { - /** The cached value */ - value: T; - /** Timestamp when the item was cached (Unix timestamp) */ - timestamp: number; - /** TTL in milliseconds */ - ttl?: number; -} - -/** - * Special marker for serialized Date objects - */ -const DATE_MARKER = "__date__"; - -/** - * Serializes a value, converting Date objects to a special format - */ -function serialize(value: T): T { - if (value instanceof Date) { - return { [DATE_MARKER]: value.toISOString() } as T; - } - if (Array.isArray(value)) { - return value.map(serialize) as T; - } - if (value !== null && typeof value === "object") { - const result: Record = {}; - for (const [key, val] of Object.entries(value)) { - result[key] = serialize(val); - } - return result as T; - } - return value; -} - -/** - * Deserializes a value, restoring Date objects from the special format - */ -function deserialize(value: T): T { - if (value !== null && typeof value === "object") { - // Check if it's a serialized Date - if ( - DATE_MARKER in value && - typeof (value as Record)[DATE_MARKER] === "string" - ) { - return new Date((value as Record)[DATE_MARKER]) as T; - } - // Handle arrays - if (Array.isArray(value)) { - return value.map(deserialize) as T; - } - // Handle objects - const result: Record = {}; - for (const [key, val] of Object.entries(value)) { - result[key] = deserialize(val); - } - return result as T; - } - return value; -} - -/** - * A high-performance cache wrapper around unstorage with TTL support. - * Optimizes storage operations by minimizing get/set calls. - */ -export class Cache { - private storage: Storage; - private option: CacheOptions; - - constructor( - storage: Storage = createStorage({ - driver: lruCacheDriver({ - ttl: 10 * 60 * 1000, - }), - }), - options: CacheOptions = { - defaultMaxAgeMs: 10 * 60 * 1000, - prefix: "", - }, - ) { - this.storage = storage; - this.option = options; - } - - private key(key: string): string { - return `${this.option.prefix}${key}`; - } - - private isExpired(entry: CacheEntry): boolean { - if (!entry.ttl) return false; - - return Date.now() - entry.timestamp > entry.ttl; - } - - async get(key: string): Promise { - const k = this.key(key); - const entry = await this.storage.getItem>(k); - - if (!entry) return null; - - if (this.isExpired(entry)) { - this.storage.removeItem(k).catch(() => {}); - return null; - } - - // Deserialize the value to restore Date objects - return deserialize(entry.value); - } - - async set( - key: string, - value: StorageValue, - maxAgeMs: number = this.option.defaultMaxAgeMs, - ): Promise { - const k = this.key(key); - - // Serialize the value to handle Date objects - const entry: CacheEntry = { - timestamp: Date.now(), - ttl: maxAgeMs, - value: serialize(value), - }; - - await this.storage.setItem(k, entry, { - // set for automatic expiration in the underlying storage - ttl: maxAgeMs, - }); - } - - async del(key: string): Promise { - const k = this.key(key); - await this.storage.removeItem(k); - } - - /** - * Gets a value from cache or fetches it using the provided function. - * Optimized to minimize storage operations by combining value and metadata in a single entry. - * @param key - The cache key - * @param fetcher - Function to fetch the value if not cached or expired - * @param maxAgeMs - TTL in milliseconds (overrides default) - * @returns The cached or freshly fetched value - * @throws Error if cache miss occurs and no fetcher is provided - */ - async tryGet( - key: string, - fetcher: (key: string) => T | Promise, - maxAgeMs: number = this.option.defaultMaxAgeMs, - ): Promise { - const data = await this.get(key); - if (data !== null) { - return data; - } - - if (!fetcher) { - throw new Error(`Cache miss for key "${key}" and no fetcher provided`); - } - - const fresh = await fetcher(key); - await this.set(key, fresh, maxAgeMs); - return fresh; - } -} -export default Cache; diff --git a/pkgs/rssbook/src/utils/category.ts b/pkgs/rssbook/src/utils/category.ts index 79b3ad9..faab339 100644 --- a/pkgs/rssbook/src/utils/category.ts +++ b/pkgs/rssbook/src/utils/category.ts @@ -1,4 +1,5 @@ import { type AnyElysia, Elysia } from "elysia"; +import { DuplicateSourceError } from "@/utils/error"; import type { Source } from "./source"; // biome-ignore lint/suspicious/noExplicitAny: Source can be any type @@ -22,9 +23,7 @@ export class Category { if (!this.sources.includes(source)) { this.sources.push(source); } else { - throw new Error( - `Source ${source.getConfig().title} is already added to category ${this.name}`, - ); + throw new DuplicateSourceError(source.getConfig().title, this.name); } } diff --git a/pkgs/rssbook/src/utils/dispatchRoute.ts b/pkgs/rssbook/src/utils/dispatchRoute.ts index 1a3bc8e..822d35d 100644 --- a/pkgs/rssbook/src/utils/dispatchRoute.ts +++ b/pkgs/rssbook/src/utils/dispatchRoute.ts @@ -1,4 +1,5 @@ import { routePlugin } from "@/routers"; +import { InvalidRoutePathError } from "@/utils/error"; type LocalRoutePath = `/${string}`; @@ -21,7 +22,7 @@ type LocalRoutePath = `/${string}`; */ export function dispatchRoute(path: LocalRoutePath): Promise { if (!path.startsWith("/")) { - throw new Error("Path must start with a leading slash (/)."); + throw new InvalidRoutePathError(); } const req = new Request(`http://rssbook.test${path}`, { diff --git a/pkgs/rssbook/src/utils/error.ts b/pkgs/rssbook/src/utils/error.ts new file mode 100644 index 0000000..9c6f4a9 --- /dev/null +++ b/pkgs/rssbook/src/utils/error.ts @@ -0,0 +1,458 @@ +/** + * Stable machine-readable RSSBook error codes used by route handlers, utilities, + * and the global error handler to classify failures without relying on message text. + */ +export type RSSBookErrorCode = + | "BROWSER_CLOSED" + | "BROWSER_ENDPOINT" + | "BROWSER_INITIALIZATION" + | "BROWSER_UNAVAILABLE" + | "CACHE_MISS" + | "DATA_VALIDATION" + | "DUPLICATE_ROUTE_TITLE" + | "DUPLICATE_SOURCE" + | "FETCH_HTML" + | "FEED_FORMAT" + | "FEED_RENDER" + | "FEED_NOT_FOUND" + | "FILTER_FEED" + | "INVALID_DOMAIN_NAME" + | "INVALID_DOMAIN_SUFFIX" + | "INVALID_DOMAIN_URL" + | "INVALID_FEED_FORMAT" + | "INVALID_JSON" + | "INVALID_OVERRIDE_JSON" + | "INVALID_PRIVATE_NETWORK" + | "INVALID_PROTOCOL" + | "INVALID_RAW_CONTENT" + | "INVALID_ROUTE_PATH" + | "INVALID_SOURCE_SLUG" + | "INVALID_RANKING_TYPE" + | "INVALID_URL" + | "LOCAL_ADDRESS" + | "LOCAL_IP_ADDRESS" + | "PARSE_ERROR" + | "PRIVATE_NETWORK" + | "SOURCE_FETCH" + | "SORT_FEED" + | "UNION_FEED" + | "INTERSECTION_FEED" + | "UNSUPPORTED_FEED_FORMAT" + | "UNSUPPORTED_BROWSER" + | "UNSUPPORTED_PROTOCOL" + | "TRANSFORM_FEED" + | "VALIDATION"; + +export interface RSSBookErrorOptions { + code: RSSBookErrorCode; + message: string; + status: number; + retryable?: boolean; + cause?: unknown; +} + +export class RSSBookError extends Error { + public readonly code: RSSBookErrorCode; + public readonly retryable: boolean; + public readonly status: number; + public readonly cause?: unknown; + + public constructor({ cause, code, message, retryable = false, status }: RSSBookErrorOptions) { + super(message); + this.name = new.target.name; + this.code = code; + this.retryable = retryable; + this.status = status; + this.cause = cause; + } +} + +export class BrowserClosedError extends RSSBookError { + public constructor() { + super({ + code: "BROWSER_CLOSED", + message: "This RSSBook Browser has been deinitialized and cannot be initialized again.", + status: 500, + }); + } +} + +export class BrowserUnavailableError extends RSSBookError { + public constructor() { + super({ + code: "BROWSER_UNAVAILABLE", + message: + "This feed route requires browser support, but RSSBook was created with browser: false.", + status: 503, + }); + } +} + +export class BrowserInitializationError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "BROWSER_INITIALIZATION", + message, + status: 500, + }); + } +} + +export class BrowserEndpointError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "BROWSER_ENDPOINT", + message, + retryable: true, + status: 502, + }); + } +} + +export class CacheMissError extends RSSBookError { + public constructor(key: string) { + super({ + code: "CACHE_MISS", + message: `Cache miss for key "${key}" and no fetcher provided`, + status: 500, + }); + } +} + +export class DataValidationError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "DATA_VALIDATION", + message, + status: 500, + }); + } +} + +export class DuplicateRouteTitleError extends RSSBookError { + public constructor(title: string) { + super({ + code: "DUPLICATE_ROUTE_TITLE", + message: `Duplicate Route Title: ${title}.`, + status: 500, + }); + } +} + +export class DuplicateSourceError extends RSSBookError { + public constructor(sourceTitle: string, categoryName: string) { + super({ + code: "DUPLICATE_SOURCE", + message: `Source ${sourceTitle} is already added to category ${categoryName}`, + status: 500, + }); + } +} + +export class FetchHtmlError extends RSSBookError { + public constructor(url: string, cause?: unknown) { + super({ + cause, + code: "FETCH_HTML", + message: `Failed to fetch or parse HTML from ${url}: ${cause instanceof Error ? cause.message : String(cause)}`, + retryable: true, + status: 502, + }); + } +} + +export class FilterFeedError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "FILTER_FEED", + message, + status: 500, + }); + } +} + +export class FeedFormatError extends RSSBookError { + public constructor(format: string) { + super({ + code: "FEED_FORMAT", + message: `Invalid feed format: ${format}.`, + status: 400, + }); + } +} + +export class FeedRenderError extends RSSBookError { + public constructor(format: string, cause?: unknown) { + super({ + cause, + code: "FEED_RENDER", + message: `Failed to generate ${format} feed: ${cause instanceof Error ? cause.message : String(cause)}`, + status: 500, + }); + } +} + +export class FeedNotFoundError extends RSSBookError { + public constructor(resource: string) { + super({ + code: "FEED_NOT_FOUND", + message: resource, + status: 404, + }); + } +} + +export class InvalidDomainNameError extends RSSBookError { + public constructor() { + super({ + code: "INVALID_DOMAIN_NAME", + message: "Invalid domain name", + status: 400, + }); + } +} + +export class InvalidDomainSuffixError extends RSSBookError { + public constructor() { + super({ + code: "INVALID_DOMAIN_SUFFIX", + message: "Local domain suffixes are not allowed", + status: 400, + }); + } +} + +export class InvalidFeedFormatError extends RSSBookError { + public constructor(format: string) { + super({ + code: "INVALID_FEED_FORMAT", + message: `Invalid feed format: ${format}.`, + status: 400, + }); + } +} + +export class InvalidJsonError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "INVALID_JSON", + message, + status: 400, + }); + } +} + +export class InvalidOverrideJsonError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "INVALID_OVERRIDE_JSON", + message, + status: 400, + }); + } +} + +export class InvalidPrivateNetworkError extends RSSBookError { + public constructor() { + super({ + code: "INVALID_PRIVATE_NETWORK", + message: "Private network addresses are not allowed", + status: 400, + }); + } +} + +export class InvalidProtocolError extends RSSBookError { + public constructor() { + super({ + code: "INVALID_PROTOCOL", + message: "Only http and https protocols are allowed", + status: 400, + }); + } +} + +export class InvalidRawContentError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "INVALID_RAW_CONTENT", + message, + status: 400, + }); + } +} + +export class InvalidRoutePathError extends RSSBookError { + public constructor() { + super({ + code: "INVALID_ROUTE_PATH", + message: "Path must start with a leading slash (/).", + status: 400, + }); + } +} + +export class InvalidSourceSlugError extends RSSBookError { + public constructor(slug: string) { + super({ + code: "INVALID_SOURCE_SLUG", + message: `Error Source Slug: ${slug}.`, + status: 500, + }); + } +} + +export class InvalidUrlError extends RSSBookError { + public constructor() { + super({ + code: "INVALID_URL", + message: "Invalid URL format", + status: 400, + }); + } +} + +export class LocalAddressError extends RSSBookError { + public constructor() { + super({ + code: "LOCAL_ADDRESS", + message: "Local addresses are not allowed", + status: 400, + }); + } +} + +export class LocalIpAddressError extends RSSBookError { + public constructor() { + super({ + code: "LOCAL_IP_ADDRESS", + message: "IP addresses are not allowed", + status: 400, + }); + } +} + +export class ParseError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "PARSE_ERROR", + message, + status: 400, + }); + } +} + +export class PrivateNetworkError extends RSSBookError { + public constructor() { + super({ + code: "PRIVATE_NETWORK", + message: "Private network addresses are not allowed", + status: 400, + }); + } +} + +export class SourceFetchError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "SOURCE_FETCH", + message, + retryable: true, + status: 502, + }); + } +} + +export class SortFeedError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "SORT_FEED", + message, + status: 500, + }); + } +} + +export class UnionFeedError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "UNION_FEED", + message, + status: 500, + }); + } +} + +export class IntersectionFeedError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "INTERSECTION_FEED", + message, + status: 500, + }); + } +} + +export class UnsupportedFeedFormatError extends RSSBookError { + public constructor(format: string) { + super({ + code: "UNSUPPORTED_FEED_FORMAT", + message: `Unsupported feed format: ${format}.`, + status: 400, + }); + } +} + +export class UnsupportedBrowserError extends RSSBookError { + public constructor(message: string) { + super({ + code: "UNSUPPORTED_BROWSER", + message, + status: 500, + }); + } +} + +export class UnsupportedProtocolError extends RSSBookError { + public constructor(protocol: string) { + super({ + code: "UNSUPPORTED_PROTOCOL", + message: `Unsupported Puppeteer browser endpoint protocol: ${protocol}`, + status: 400, + }); + } +} + +export class TransformFeedError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "TRANSFORM_FEED", + message, + status: 500, + }); + } +} + +export class ValidationError extends RSSBookError { + public constructor(message: string, cause?: unknown) { + super({ + cause, + code: "VALIDATION", + message, + status: 500, + }); + } +} diff --git a/pkgs/rssbook/src/utils/feeds/parse.ts b/pkgs/rssbook/src/utils/feeds/parse.ts index 445533c..ec7a110 100644 --- a/pkgs/rssbook/src/utils/feeds/parse.ts +++ b/pkgs/rssbook/src/utils/feeds/parse.ts @@ -2,6 +2,7 @@ import { parseFeed } from "@rowanmanning/feed-parser"; import type { Data, DataItem, FeedType } from "@/types"; import { EMPTY_DATA, parseData } from "@/types"; import { detectLanguage } from "@/utils"; +import { ParseError } from "@/utils/error"; export function parse(data: T | string, type: "raw"): Data; @@ -26,23 +27,24 @@ export function parse(XMLString: string, type?: "rss" | "atom"): Data; export function parse(content: string | T, type: FeedType = "rss"): Data { if (type === "raw") { if (typeof content !== "string" && typeof content !== "object") { - throw new Error("Parse Error: Content must be a string or object for raw type"); + throw new ParseError("Parse Error: Content must be a string or object for raw type"); } if (content === null) { - throw new Error("Parse Error: Content cannot be null"); + throw new ParseError("Parse Error: Content cannot be null"); } let formattedContent: T; try { formattedContent = typeof content === "string" ? JSON.parse(content) : (content as T); } catch (error) { - throw new Error( + throw new ParseError( `Parse Error: Invalid JSON string - ${error instanceof Error ? error.message : String(error)}`, + error, ); } if (typeof formattedContent !== "object" || formattedContent === null) { - throw new Error("Parse Error: Parsed content must be an object"); + throw new ParseError("Parse Error: Parsed content must be an object"); } return parseData({ @@ -51,7 +53,7 @@ export function parse(content: string | T, type: FeedType = "r }); } else { if (typeof content !== "string") { - throw new Error("Parse Error: Content must be a string for feed types"); + throw new ParseError("Parse Error: Content must be a string for feed types"); } const parsedFeed = parseFeed(content); diff --git a/pkgs/rssbook/src/utils/feeds/render.test.ts b/pkgs/rssbook/src/utils/feeds/render.test.ts index a0196ab..6b28a2c 100644 --- a/pkgs/rssbook/src/utils/feeds/render.test.ts +++ b/pkgs/rssbook/src/utils/feeds/render.test.ts @@ -1,67 +1,28 @@ import { describe, expect, test } from "bun:test"; import type { Data } from "@/types"; -import { addStylesheet, render } from "@/utils"; +import { render } from "@/utils"; describe("render", () => { - describe("addStylesheet", () => { - test("adds stylesheet to RSS feed with XML declaration", () => { - const xml = '\n'; - const result = addStylesheet(xml, "rss"); - - expect(result).toContain( - '', - ); - expect(result).toMatch(/^<\?xml[^?]*\?>\n<\?xml-stylesheet/); - }); - - test("adds stylesheet to Atom feed with XML declaration", () => { - const xml = '\n'; - const result = addStylesheet(xml, "atom"); - - expect(result).toContain( - '', - ); - expect(result).toMatch(/^<\?xml[^?]*\?>\n<\?xml-stylesheet/); - }); - - test("adds stylesheet to RSS feed without XML declaration", () => { - const xml = ''; - const result = addStylesheet(xml, "rss"); - - expect(result).toContain( - '', - ); - expect(result).toMatch(/^<\?xml-stylesheet/); - }); - - test("does not add duplicate stylesheet", () => { - const xml = - '\n\n'; - const result = addStylesheet(xml, "rss"); + describe("render", () => { + test("adds RSS stylesheet through feed options when styled", () => { + const rss = render(exampleData1(), "rss"); - expect(result).toBe(xml); - const count = (result.match(/xml-stylesheet/g) || []).length; - expect(count).toBe(1); + expect(rss).toContain(''); + expect(rss).toMatch(/^<\?xml[^?]*\?><\?xml-stylesheet/); }); - test("returns unchanged XML for invalid type", () => { - const xml = '\n'; - // @ts-expect-error Testing invalid type - const result = addStylesheet(xml, "json"); + test("adds Atom stylesheet through feed options when styled", () => { + const atom = render(exampleData1(), "atom"); - expect(result).toBe(xml); + expect(atom).toContain(''); + expect(atom).toMatch(/^<\?xml[^?]*\?><\?xml-stylesheet/); }); - test("trims whitespace after XML declaration", () => { - const xml = ' \n\n '; - const result = addStylesheet(xml, "rss"); - - expect(result).not.toContain("?> \n\n"); - expect(result).toMatch(/\?>\n<\?xml-stylesheet.*\?>\n { + expect(render(exampleData1(), "rss", false)).not.toContain("xml-stylesheet"); + expect(render(exampleData1(), "atom", false)).not.toContain("xml-stylesheet"); }); - }); - describe("render", () => { describe("exampleData1 (simple fields)", () => { describe("RSS", () => { const rss = render(exampleData1(), "rss", false); diff --git a/pkgs/rssbook/src/utils/feeds/render.ts b/pkgs/rssbook/src/utils/feeds/render.ts index d264d96..cd25f76 100644 --- a/pkgs/rssbook/src/utils/feeds/render.ts +++ b/pkgs/rssbook/src/utils/feeds/render.ts @@ -1,39 +1,6 @@ import { Feed } from "feed"; import { type Data, type FeedType, isFeedType, parseData } from "@/types/data"; -import { uuid } from "../uuid"; - -/** - * Add `xslt` stylesheet link to the feed XML. - * - * @todo: [May Be Deprecated](https://github.com/whatwg/html/issues/11523) - * - * @param xml the raw XML string - * @param type the feed type: "rss" or "atom" - * @returns styled XML string - */ -export function addStylesheet(xml: string, type: "rss" | "atom"): string { - if (type !== "rss" && type !== "atom") { - return xml; - } - if (xml.includes("xml-stylesheet")) { - return xml; - } - - const pi = ``; - - // Look for an XML declaration near the start and insert after it if present. - const head = xml.slice(0, 200); - const declMatch = head.match(/^<\?xml[^?]*\?>/i); - - if (declMatch) { - const declEnd = declMatch[0].length; - // insert PI after declaration, trim any immediate whitespace after decl - return `${xml.slice(0, declEnd)}\n${pi}\n${xml.slice(declEnd).replace(/^\s+/, "")}`; - } - - // no declaration — prepend PI - return `${pi}\n${xml}`; -} +import { FeedFormatError, FeedRenderError, InvalidFeedFormatError } from "@/utils/error"; /** * Render feed data into specified format. @@ -44,7 +11,7 @@ export function addStylesheet(xml: string, type: "rss" | "atom"): string { */ export function render(data: Data, format: FeedType = "rss", styled: boolean = true): string { if (!isFeedType(format)) { - throw new Error(`Invalid feed format: ${format}.`); + throw new InvalidFeedFormatError(format); } if (format === "raw") { @@ -56,7 +23,7 @@ export function render(data: Data, format: FeedType = "rss", styled: boolean = t const feed = new Feed({ copyright: "RSSBook", generator: "RSSBook", - id: uuid(), + stylesheet: styled ? `/xsl/${format}.xsl` : undefined, ...validDate, }); @@ -69,26 +36,17 @@ export function render(data: Data, format: FeedType = "rss", styled: boolean = t try { switch (format) { - case "rss": { - const rss = feed.rss2(); - return styled ? addStylesheet(rss, "rss") : rss; - } - - case "atom": { - const atom = feed.atom1(); - return styled ? addStylesheet(atom, "atom") : atom; - } + case "rss": + return feed.rss2(); + case "atom": + return feed.atom1(); case "json": return feed.json1(); default: - throw new Error(`Unsupported feed format: ${format}.`); + throw new FeedFormatError(format); } } catch (error) { - throw new Error( - `Failed to generate ${format} feed: ${ - error instanceof Error ? error.message : String(error) - }`, - ); + throw new FeedRenderError(format, error); } } diff --git a/pkgs/rssbook/src/utils/index.ts b/pkgs/rssbook/src/utils/index.ts index 61c4438..cbac7c3 100644 --- a/pkgs/rssbook/src/utils/index.ts +++ b/pkgs/rssbook/src/utils/index.ts @@ -1,7 +1,9 @@ -export * from "./cache"; +export * from "../cache"; +export * from "./browser"; export * from "./category"; export * from "./date"; export * from "./detectLanguage"; +export * from "./error"; export * from "./feeds"; export * from "./formatHTML"; export * from "./load"; diff --git a/pkgs/rssbook/src/utils/source.ts b/pkgs/rssbook/src/utils/source.ts index 7db5e38..fdb71f5 100644 --- a/pkgs/rssbook/src/utils/source.ts +++ b/pkgs/rssbook/src/utils/source.ts @@ -2,20 +2,26 @@ import { type AnyElysia, Elysia } from "elysia"; import { injectPlugin, renderPlugin } from "@/plugins"; import type { Config, GeneratedConfig, RouteConfig, Slug, SourceConfigs } from "@/types"; import { detectLanguage } from "@/utils"; +import { DuplicateRouteTitleError, InvalidSourceSlugError } from "@/utils/error"; import { logger } from "./logger"; /** * Source class to manage routes and configurations. * + * The source `slug` is mounted as the route prefix. Feed paths registered with + * {@link Source.feed} are appended to that prefix, so a source with + * `slug: "example"` and `app.get("/latest/:category", ...)` is exposed at + * `/example/latest/:category`. + * * @example * ```ts * export default new Source({ * slug: "example", // only allows lowercase letters, numbers, and hyphens * title: "Example Source", * description: `An example source`, // markdown supported - * rootURL: "https://example.com", // root URL of the source + * domain: "example.com", // source website domain * config: { - * category: { + * EXAMPLE_CATEGORY: { * description: "Category of the feed", * required: true, * default: "general", @@ -45,9 +51,9 @@ export class Source< * slug: "example", // only allows lowercase letters, numbers, and hyphens * title: "Example Source", * description: `An example source`, // markdown supported - * rootURL: "https://example.com", // root URL of the source + * domain: "example.com", // source website domain * config: { - * category: { + * EXAMPLE_CATEGORY: { * description: "Category of the feed", * required: true, * default: "general", @@ -93,7 +99,7 @@ export class Source< }), ) { if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(sourceConfig.slug)) { - throw new Error(`Error Source Slug: ${sourceConfig.slug}.`); + throw new InvalidSourceSlugError(sourceConfig.slug); } } @@ -101,6 +107,9 @@ export class Source< * Add a new feed item (route) to this source. * * Each item represents a route definition, along with its metadata and handler. + * The path passed to `app.get()` is mounted below the source prefix. For + * example, source slug `example` plus feed path `/latest/:category` creates + * the final route URL `/example/latest/:category`. * * @example * ```ts @@ -113,7 +122,8 @@ export class Source< * language: "en", // language of the feed * maintainer: { name: "RSSBook" }, // maintainer information * }, - * (app) => app.get("/example", () => "Hello World"), // route handler + * // Final route URL: /example/latest/:category + * (app) => app.get("/latest/:category", () => "Hello World"), * ); * ``` * @@ -123,7 +133,7 @@ export class Source< */ public feed(routeConfig: RouteConfig, handler: (_app: typeof this._app) => AnyElysia): this { if (this.routes.some((route) => route.title === routeConfig.title)) { - throw new Error(`Duplicate Route Title: ${routeConfig.title}.`); + throw new DuplicateRouteTitleError(routeConfig.title); } const newApp = new Elysia({ @@ -190,6 +200,7 @@ export class Source< `- **Fulltext**: ${routeConfig.fulltext !== undefined ? (routeConfig.fulltext ? "Enabled" : "Disabled") : "Not specified"}`, `- **With Image**: ${routeConfig.withImage ? `${routeConfig.withImage}` : "Not specified"}`, `- **Language**: ${languages.join(", ")}`, + ...(routeConfig.browser === true ? ["- **Browser**: Enabled"] : []), `- **Generate From**: ${this.sourceConfig.domain}`, "", ].join("\n\n"); diff --git a/pkgs/utils-feed-helper/.gitignore b/pkgs/utils-feed-helper/.gitignore index cbaaea6..f9f304b 100644 --- a/pkgs/utils-feed-helper/.gitignore +++ b/pkgs/utils-feed-helper/.gitignore @@ -1,52 +1,5 @@ -# Dependencies node_modules -/.pnp -.pnp.js - -# Testing -/coverage - -# Production -/build -/dist - -# Environment files -.env -.env.* -!.env.example - -# OS files +dist +build .DS_Store -*.pem - -# Logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Vercel -.vercel -**/.vercel - -# Wrangler -.wrangler -**/.wrangler - -# Netlify -.netlify -**/.netlify - -# Build artifacts -**/*.trace -**/*.zip -**/*.tar.gz -**/*.tgz -package-lock.json -**/*.bun - -# IDE -.idea -.vscode -*.swp -*.swo \ No newline at end of file +*.log \ No newline at end of file diff --git a/pkgs/utils-feed-helper/bun.lock b/pkgs/utils-feed-helper/bun.lock deleted file mode 100644 index baa04be..0000000 --- a/pkgs/utils-feed-helper/bun.lock +++ /dev/null @@ -1,56 +0,0 @@ -{ - "lockfileVersion": 1, - "configVersion": 1, - "workspaces": { - "": { - "name": "utils-feed-helper", - "dependencies": { - "elysia": "latest", - }, - "devDependencies": { - "bun-types": "latest", - }, - }, - }, - "packages": { - "@borewit/text-codec": ["@borewit/text-codec@0.2.2", "", {}, "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ=="], - - "@sinclair/typebox": ["@sinclair/typebox@0.34.49", "", {}, "sha512-brySQQs7Jtn0joV8Xh9ZV/hZb9Ozb0pmazDIASBkYKCjXrXU3mpcFahmK/z4YDhGkQvP9mWJbVyahdtU5wQA+A=="], - - "@tokenizer/inflate": ["@tokenizer/inflate@0.4.1", "", { "dependencies": { "debug": "^4.4.3", "token-types": "^6.1.1" } }, "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA=="], - - "@tokenizer/token": ["@tokenizer/token@0.3.0", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="], - - "@types/node": ["@types/node@25.6.0", "", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="], - - "bun-types": ["bun-types@1.3.12", "", { "dependencies": { "@types/node": "*" } }, "sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA=="], - - "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], - - "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], - - "elysia": ["elysia@1.4.28", "", { "dependencies": { "cookie": "^1.1.1", "exact-mirror": "^0.2.7", "fast-decode-uri-component": "^1.0.1", "memoirist": "^0.4.0" }, "peerDependencies": { "@sinclair/typebox": ">= 0.34.0 < 1", "@types/bun": ">= 1.2.0", "file-type": ">= 20.0.0", "openapi-types": ">= 12.0.0", "typescript": ">= 5.0.0" }, "optionalPeers": ["@types/bun", "typescript"] }, "sha512-Vrx8sBnvq8squS/3yNBzR1jBXI+SgmnmvwawPjNuEHndUe5l1jV2Gp6JJ4ulDkEB8On6bWmmuyPpA+bq4t+WYg=="], - - "exact-mirror": ["exact-mirror@0.2.7", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-+MeEmDcLA4o/vjK2zujgk+1VTxPR4hdp23qLqkWfStbECtAq9gmsvQa3LW6z/0GXZyHJobrCnmy1cdeE7BjsYg=="], - - "fast-decode-uri-component": ["fast-decode-uri-component@1.0.1", "", {}, "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg=="], - - "file-type": ["file-type@22.0.1", "", { "dependencies": { "@tokenizer/inflate": "^0.4.1", "strtok3": "^10.3.5", "token-types": "^6.1.2", "uint8array-extras": "^1.5.0" } }, "sha512-ww5Mhre0EE+jmBvOXTmXAbEMuZE7uX4a3+oRCQFNj8w++g3ev913N6tXQz0XTXbueQ5TWQfm6BdaViEHHn8bhA=="], - - "ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], - - "memoirist": ["memoirist@0.4.0", "", {}, "sha512-zxTgA0mSYELa66DimuNQDvyLq36AwDlTuVRbnQtB+VuTcKWm5Qc4z3WkSpgsFWHNhexqkIooqpv4hdcqrX5Nmg=="], - - "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - - "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], - - "strtok3": ["strtok3@10.3.5", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA=="], - - "token-types": ["token-types@6.1.2", "", { "dependencies": { "@borewit/text-codec": "^0.2.1", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww=="], - - "uint8array-extras": ["uint8array-extras@1.5.0", "", {}, "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A=="], - - "undici-types": ["undici-types@7.19.2", "", {}, "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg=="], - } -} diff --git a/pkgs/utils-feed-helper/package.json b/pkgs/utils-feed-helper/package.json index 4e4fae2..e5fd6c3 100644 --- a/pkgs/utils-feed-helper/package.json +++ b/pkgs/utils-feed-helper/package.json @@ -3,26 +3,29 @@ "url": "https://github.com/HackHTU/RSSBook/issues" }, "dependencies": { - "@elysiajs/html": "catalog:", - "@kitajs/html": "catalog:", - "@kitajs/ts-html-plugin": "catalog:", - "elysia": "catalog:" + "@elysiajs/static": "catalog:", + "elysia": "catalog:", + "react": "^19", + "react-dom": "^19" }, "devDependencies": { - "bun-types": "catalog:" + "@types/bun": "catalog:", + "@types/react": "^19", + "@types/react-dom": "^19" }, "homepage": "https://github.com/HackHTU/RSSBook", "license": "MIT", - "module": "src/index.js", + "module": "src/index.ts", "name": "utils-feed-helper", "packageManager": "bun@1.3.2", + "private": true, "repository": { "type": "git", "url": "git://github.com/HackHTU/RSSBook.git" }, "scripts": { - "dev": "bun run --watch src/index.tsx", - "test": "echo \"Error: no test specified\" && exit 1" + "build": "bun build --compile --target bun --outfile dist/utils-feed-helper src/index.ts", + "dev": "bun --hot src/index.ts" }, "type": "module", "version": "1.0.50" diff --git a/pkgs/utils-feed-helper/public/index.html b/pkgs/utils-feed-helper/public/index.html new file mode 100644 index 0000000..0df4586 --- /dev/null +++ b/pkgs/utils-feed-helper/public/index.html @@ -0,0 +1,14 @@ + + + + + + + + RSSBook Utils Feed Helper + + +
+ + + diff --git a/pkgs/utils-feed-helper/src/index.ts b/pkgs/utils-feed-helper/src/index.ts new file mode 100644 index 0000000..41cfc83 --- /dev/null +++ b/pkgs/utils-feed-helper/src/index.ts @@ -0,0 +1,17 @@ +import { staticPlugin } from "@elysiajs/static"; +import { Elysia } from "elysia"; + +const assetsPath = new URL("../public", import.meta.url).pathname; +const port = Number(Bun.env.PORT ?? 3000); + +const app = new Elysia() + .use( + await staticPlugin({ + assets: assetsPath, + bunFullstack: true, + prefix: "/", + }), + ) + .listen(port); + +export type App = typeof app; diff --git a/pkgs/utils-feed-helper/src/index.tsx b/pkgs/utils-feed-helper/src/index.tsx index 4a77930..e14cf9a 100644 --- a/pkgs/utils-feed-helper/src/index.tsx +++ b/pkgs/utils-feed-helper/src/index.tsx @@ -1,43 +1,7 @@ -import { Elysia } from "elysia"; +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; -export const app = new Elysia() - .get("/", () => ( - - - Utils Feed Helper - - - - - - - - {/* UnoCSS Runtime */} - - - {/* Datastar */} - - - {/* TailwindCSS Reset */} - - - - -
-
-

Utils Feed Helper

-

Utility functions for feed processing

-
- UnoCSS and Datastar enabled -
-
-
- - - )) - .listen(3000); - -// console.log(`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`); +const root = document.getElementById("root"); +if (root) { + createRoot(root).render(); +} diff --git a/pkgs/utils-feed-helper/tsconfig.json b/pkgs/utils-feed-helper/tsconfig.json index 5639a98..158090b 100644 --- a/pkgs/utils-feed-helper/tsconfig.json +++ b/pkgs/utils-feed-helper/tsconfig.json @@ -1,22 +1,20 @@ { "compilerOptions": { - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, + "ignoreDeprecations": "6.0", "jsx": "react-jsx", - "jsxImportSource": "@kitajs/html", - "moduleResolution": "bundler", + "jsxImportSource": "react", + "lib": ["ESNext", "DOM"], + "module": "Preserve", + "moduleDetection": "force", + "noEmit": true, "paths": { "@/*": ["./src/*"] }, - "plugins": [ - { - "name": "@kitajs/ts-html-plugin" - } - ], - "rootDir": "./", - "skipLibCheck": true, - "strict": true, - "target": "ES2021", - "types": ["bun-types"] - } + "rootDir": ".", + "types": ["bun", "react"], + "verbatimModuleSyntax": true + }, + "exclude": ["dist", "node_modules"], + "extends": "../../tsconfig.base.json", + "include": ["public/**/*.tsx", "src/**/*.ts", "src/**/*.tsx"] } diff --git a/platform/cloudflare/browser.test.ts b/platform/cloudflare/browser.test.ts new file mode 100644 index 0000000..9160738 --- /dev/null +++ b/platform/cloudflare/browser.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, mock, test } from "bun:test"; +import type { BrowserWorker } from "@cloudflare/puppeteer"; +import type { PuppeteerBrowser } from "rssbook"; +import { CloudflareBrowser } from "./browser"; + +const launchedBindings: BrowserWorker[] = []; +mock.module("@cloudflare/puppeteer", () => ({ + default: { + launch: mock(async (binding: BrowserWorker) => { + launchedBindings.push(binding); + return createFakeBrowser(); + }), + }, +})); + +describe("CloudflareBrowser", () => { + test("uses conservative Browser Rendering capacity defaults", () => { + const browser = new CloudflareBrowser(createBinding()); + expect(browser.maxBrowsers).toBe(1); + expect(browser.maxContextsPerBrowser).toBe(1); + expect(browser.maxPagesPerContext).toBe(2); + }); + + test("launches Cloudflare Puppeteer with the configured binding", async () => { + const binding = createBinding(); + const browser = new CloudflareBrowser(binding); + await browser.init(); + expect(launchedBindings.at(-1)).toBe(binding); + await browser.deinit(); + }); + + test("allows direct capacity overrides", () => { + const browser = new CloudflareBrowser(createBinding(), { + maxBrowsers: 2, + maxContextsPerBrowser: 3, + maxPagesPerContext: 4, + }); + expect(browser.maxBrowsers).toBe(2); + expect(browser.maxContextsPerBrowser).toBe(3); + expect(browser.maxPagesPerContext).toBe(4); + }); +}); + +function createBinding(): BrowserWorker { + return { fetch }; +} + +function createFakeBrowser(): PuppeteerBrowser { + let browser: PuppeteerBrowser; + browser = { + close: mock(async () => {}), + createBrowserContext: mock(async () => { + throw new Error("not used"); + }), + newPage: mock(async () => { + throw new Error("not used"); + }), + once: mock(() => browser), + } as unknown as PuppeteerBrowser; + return browser; +} diff --git a/platform/cloudflare/browser.ts b/platform/cloudflare/browser.ts new file mode 100644 index 0000000..1176f6a --- /dev/null +++ b/platform/cloudflare/browser.ts @@ -0,0 +1,26 @@ +import puppeteer, { + type BrowserWorker, + type Browser as CloudflarePuppeteerBrowser, +} from "@cloudflare/puppeteer"; +import { Browser, type BrowserConcurrencyOptions, type PuppeteerBrowser } from "rssbook"; + +export class CloudflareBrowser extends Browser { + public constructor( + private readonly binding: BrowserWorker, + options: BrowserConcurrencyOptions = {}, + ) { + super({ + maxBrowsers: options.maxBrowsers ?? 1, + maxContextsPerBrowser: options.maxContextsPerBrowser ?? 1, + maxPagesPerContext: options.maxPagesPerContext ?? 2, + }); + } + + protected async createBrowser(): Promise { + const browser: CloudflarePuppeteerBrowser = await puppeteer.launch(this.binding); + + // Cloudflare and upstream Puppeteer expose the same API from different + // package versions, so their nominal types do not unify. + return browser as unknown as PuppeteerBrowser; + } +} diff --git a/platform/cloudflare/cache.test.ts b/platform/cloudflare/cache.test.ts new file mode 100644 index 0000000..4eb196d --- /dev/null +++ b/platform/cloudflare/cache.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from "bun:test"; +import { CloudflareKVCache, type CloudflareKVNamespace } from "./cache"; + +class FakeNamespace implements CloudflareKVNamespace { + public readonly values = new Map(); + public readonly puts: { key: string; options?: { expirationTtl: number }; value: string }[] = []; + + public async get(key: string): Promise { + return this.values.get(key) ?? null; + } + + public async put(key: string, value: string, options?: { expirationTtl: number }): Promise { + this.puts.push({ key, options, value }); + this.values.set(key, value); + } + + public async delete(key: string): Promise { + this.values.delete(key); + } +} + +describe("CloudflareKVCache", () => { + test("stores JSON-compatible data and deletes entries", async () => { + const namespace = new FakeNamespace(); + const cache = new CloudflareKVCache(namespace, { prefix: "prefix:" }); + const value = { nested: [1, null, "value"] }; + + await cache.set("key", value); + expect(await cache.get("key")).toEqual(value); + expect(namespace.puts[0]?.key).toBe("prefix:key"); + await cache.del("key"); + expect(await cache.get("key")).toBeUndefined(); + }); + + test("rounds milliseconds up to seconds and enforces the 60-second minimum", async () => { + const namespace = new FakeNamespace(); + const cache = new CloudflareKVCache(namespace); + + await cache.set("short", "value", 1); + await cache.set("long", "value", 60_001); + expect(namespace.puts[0]?.options).toEqual({ expirationTtl: 60 }); + expect(namespace.puts[1]?.options).toEqual({ expirationTtl: 61 }); + }); + + test("omits backend expiration for zero TTL", async () => { + const namespace = new FakeNamespace(); + const cache = new CloudflareKVCache(namespace); + await cache.set("key", "value", 0); + expect(namespace.puts[0]?.options).toBeUndefined(); + }); +}); diff --git a/platform/cloudflare/cache.ts b/platform/cloudflare/cache.ts new file mode 100644 index 0000000..39ea272 --- /dev/null +++ b/platform/cloudflare/cache.ts @@ -0,0 +1,39 @@ +import { Cache, type CacheOptions } from "rssbook"; + +/** Minimal Workers KV surface required by the RSSBook cache adapter. */ +export interface CloudflareKVNamespace { + delete(key: string): Promise; + get(key: string): Promise; + put(key: string, value: string, options?: { expirationTtl: number }): Promise; +} + +/** RSSBook cache backed directly by a Cloudflare Workers KV binding. */ +export class CloudflareKVCache extends Cache { + public constructor( + private readonly namespace: CloudflareKVNamespace, + options: CacheOptions = {}, + ) { + super(options); + } + + protected async getRaw(key: string): Promise { + return (await this.namespace.get(key)) ?? undefined; + } + + protected async setRaw(key: string, serializedEntry: string, maxAgeMs: number): Promise { + if (maxAgeMs === 0) { + await this.namespace.put(key, serializedEntry); + return; + } + + await this.namespace.put(key, serializedEntry, { + expirationTtl: Math.max(60, Math.ceil(maxAgeMs / 1000)), + }); + } + + protected async deleteRaw(key: string): Promise { + await this.namespace.delete(key); + } + + protected async closeBackend(): Promise {} +} diff --git a/platform/cloudflare/index.ts b/platform/cloudflare/index.ts index 4beceb7..9f3824e 100644 --- a/platform/cloudflare/index.ts +++ b/platform/cloudflare/index.ts @@ -4,20 +4,18 @@ */ import { env } from "cloudflare:workers"; +import type { BrowserWorker } from "@cloudflare/puppeteer"; import { CloudflareAdapter } from "elysia/adapter/cloudflare-worker"; -import { Cache, createRSSBookApp } from "rssbook"; -import { createStorage } from "unstorage"; -import cloudflareKVBindingDriver from "unstorage/drivers/cloudflare-kv-binding"; +import { createRSSBookApp } from "rssbook"; +import { CloudflareBrowser } from "./browser"; +import { CloudflareKVCache } from "./cache"; + +export { CloudflareKVCache } from "./cache"; export const app = createRSSBookApp({ adapter: CloudflareAdapter, - cache: new Cache( - createStorage({ - driver: cloudflareKVBindingDriver({ - binding: env.RSSBookKV, - }), - }), - ), + browser: new CloudflareBrowser(env.BROWSER as unknown as BrowserWorker), + cache: new CloudflareKVCache(env.RSSBookKV), openapi: { enableFetchOnlineServer: false, }, diff --git a/platform/cloudflare/package.json b/platform/cloudflare/package.json index fbaafa2..7838534 100644 --- a/platform/cloudflare/package.json +++ b/platform/cloudflare/package.json @@ -1,8 +1,8 @@ { "dependencies": { + "@cloudflare/puppeteer": "^1.1.0", "elysia": "^1.4.29", - "rssbook": "workspace:*", - "unstorage": "^1.17.5" + "rssbook": "workspace:*" }, "devDependencies": {}, "name": "@rssbook/platform-cloudflare", diff --git a/platform/cloudflare/worker-configuration.d.ts b/platform/cloudflare/worker-configuration.d.ts index 3bdb415..8a7c87d 100644 --- a/platform/cloudflare/worker-configuration.d.ts +++ b/platform/cloudflare/worker-configuration.d.ts @@ -1,12 +1,17 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: ed4368aabd363188ef8ab7297b9726e3) -// Runtime types generated with workerd@1.20250730.0 2025-07-30 nodejs_compat,nodejs_compat_populate_process_env +// Generated by Wrangler by running `wrangler types` (hash: 3bac43bef73e7049ecc6db045bdcef3a) +// Runtime types generated with workerd@1.20260708.1 2026-06-16 nodejs_compat,nodejs_compat_populate_process_env +interface __BaseEnv_Env { + RSSBookKV: KVNamespace; + BROWSER: BrowserRun; +} declare namespace Cloudflare { - interface Env { - RSSBookKV: KVNamespace; + interface GlobalProps { + mainModule: typeof import("./index"); } + interface Env extends __BaseEnv_Env {} } -interface Env extends Cloudflare.Env {} +interface Env extends __BaseEnv_Env {} // Begin runtime types /*! ***************************************************************************** @@ -27,17 +32,26 @@ and limitations under the License. // noinspection JSUnusedGlobalSymbols declare var onmessage: never; /** - * An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. + * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) */ declare class DOMException extends Error { constructor(message?: string, name?: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + /** + * The **`message`** read-only property of the a message or description associated with the given error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) + */ readonly message: string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + /** + * The **`name`** read-only property of the one of the strings associated with an error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) + */ readonly name: string; /** + * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) @@ -81,45 +95,121 @@ type WorkerGlobalScopeEventMap = { declare abstract class WorkerGlobalScope extends EventTarget { EventTarget: typeof EventTarget; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * + * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) + */ interface Console { assert(condition?: boolean, ...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + /** + * The **`console.clear()`** static method clears the console if possible. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) + */ clear(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + /** + * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) + */ count(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + /** + * The **`console.countReset()`** static method resets counter used with console/count_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) + */ countReset(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + /** + * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) + */ debug(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + /** + * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) + */ dir(item?: any, options?: any): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + /** + * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) + */ dirxml(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + /** + * The **`console.error()`** static method outputs a message to the console at the 'error' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) + */ error(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + /** + * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) + */ group(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + /** + * The **`console.groupCollapsed()`** static method creates a new inline group in the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) + */ groupCollapsed(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + /** + * The **`console.groupEnd()`** static method exits the current inline group in the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) + */ groupEnd(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + /** + * The **`console.info()`** static method outputs a message to the console at the 'info' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) + */ info(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + /** + * The **`console.log()`** static method outputs a message to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) + */ log(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + /** + * The **`console.table()`** static method displays tabular data as a table. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) + */ table(tabularData?: any, properties?: string[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + /** + * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) + */ time(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + /** + * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) + */ timeEnd(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + /** + * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) + */ timeLog(label?: string, ...data: any[]): void; timeStamp(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + /** + * The **`console.trace()`** static method outputs a stack trace to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) + */ trace(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + /** + * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) + */ warn(...data: any[]): void; } declare const console: Console; @@ -204,7 +294,7 @@ declare namespace WebAssembly { function validate(bytes: BufferSource): boolean; } /** - * This ServiceWorker API interface represents the global execution context of a service worker. + * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) @@ -258,6 +348,8 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; CountQueuingStrategy: typeof CountQueuingStrategy; ErrorEvent: typeof ErrorEvent; + MessageChannel: typeof MessageChannel; + MessagePort: typeof MessagePort; EventSource: typeof EventSource; ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; ReadableStreamDefaultController: typeof ReadableStreamDefaultController; @@ -307,7 +399,7 @@ declare function removeEventListener { waitUntil(promise: Promise): void; passThroughOnException(): void; - props: any; + readonly exports: Cloudflare.Exports; + readonly props: Props; + cache?: CacheContext; + readonly access?: CloudflareAccessContext; + tracing: Tracing; } -type ExportedHandlerFetchHandler = ( +type ExportedHandlerFetchHandler = ( request: Request>, env: Env, - ctx: ExecutionContext, + ctx: ExecutionContext, ) => Response | Promise; -type ExportedHandlerTailHandler = ( +type ExportedHandlerConnectHandler = ( + socket: Socket, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTailHandler = ( events: TraceItem[], env: Env, - ctx: ExecutionContext, + ctx: ExecutionContext, ) => void | Promise; -type ExportedHandlerTraceHandler = ( +type ExportedHandlerTraceHandler = ( traces: TraceItem[], env: Env, - ctx: ExecutionContext, + ctx: ExecutionContext, ) => void | Promise; -type ExportedHandlerTailStreamHandler = ( +type ExportedHandlerTailStreamHandler = ( event: TailStream.TailEvent, env: Env, - ctx: ExecutionContext, + ctx: ExecutionContext, ) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = ( +type ExportedHandlerScheduledHandler = ( controller: ScheduledController, env: Env, - ctx: ExecutionContext, + ctx: ExecutionContext, ) => void | Promise; -type ExportedHandlerQueueHandler = ( +type ExportedHandlerQueueHandler = ( batch: MessageBatch, env: Env, - ctx: ExecutionContext, + ctx: ExecutionContext, ) => void | Promise; -type ExportedHandlerTestHandler = ( +type ExportedHandlerTestHandler = ( controller: TestController, env: Env, - ctx: ExecutionContext, + ctx: ExecutionContext, ) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; +interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, + Props = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + connect?: ExportedHandlerConnectHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { transfer?: any[]; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */ -declare abstract class PromiseRejectionEvent extends Event { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ - readonly promise: Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ - readonly reason: any; -} declare abstract class Navigator { - sendBeacon( - url: string, - body?: - | ReadableStream - | string - | (ArrayBuffer | ArrayBufferView) - | Blob - | FormData - | URLSearchParams - | URLSearchParams, - ): boolean; + sendBeacon(url: string, body?: BodyInit): boolean; readonly userAgent: string; readonly hardwareConcurrency: number; + readonly platform: string; readonly language: string; readonly languages: string[]; } -/** - * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, - * as well as timing of subrequests and other operations. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) - */ -interface Performance { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ - readonly timeOrigin: number; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ - now(): number; -} interface AlarmInvocationInfo { readonly isRetry: boolean; readonly retryCount: number; + readonly scheduledTime: number; } interface Cloudflare { readonly compatibilityFlags: Record; } +interface CachePurgeError { + code: number; + message: string; +} +interface CachePurgeResult { + success: boolean; + errors: CachePurgeError[]; +} +interface CachePurgeOptions { + tags?: string[]; + pathPrefixes?: string[]; + purgeEverything?: boolean; +} +interface CacheContext { + purge(options: CachePurgeOptions): Promise; +} +interface CloudflareAccessContext { + readonly aud: string; + getIdentity(): Promise; +} +declare abstract class ColoLocalActorNamespace { + get(actorId: string): Fetcher; +} interface DurableObject { fetch(request: Request): Response | Promise; + connect?(socket: Socket): void | Promise; alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; webSocketClose?( @@ -487,7 +591,7 @@ interface DurableObject { } type DurableObjectStub = Fetcher< T, - "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" + "alarm" | "connect" | "webSocketMessage" | "webSocketClose" | "webSocketError" > & { readonly id: DurableObjectId; readonly name?: string; @@ -496,8 +600,11 @@ interface DurableObjectId { toString(): string; equals(other: DurableObjectId): boolean; readonly name?: string; + readonly jurisdiction?: string; } -interface DurableObjectNamespace { +declare abstract class DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; idFromName(name: string): DurableObjectId; idFromString(id: string): DurableObjectId; @@ -505,9 +612,13 @@ interface DurableObjectNamespace; + getByName( + name: string, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; } -type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; +type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us"; interface DurableObjectNamespaceNewUniqueIdOptions { jurisdiction?: DurableObjectJurisdiction; } @@ -518,17 +629,25 @@ type DurableObjectLocationHint = | "weur" | "eeur" | "apac" + | "apac-ne" + | "apac-se" | "oc" | "afr" | "me"; +type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; } -interface DurableObjectState { +type DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> = {}; +interface DurableObjectState { waitUntil(promise: Promise): void; + readonly exports: Cloudflare.Exports; + readonly props: Props; readonly id: DurableObjectId; readonly storage: DurableObjectStorage; container?: Container; + facets: DurableObjectFacets; blockConcurrencyWhile(callback: () => Promise): Promise; acceptWebSocket(ws: WebSocket, tags?: string[]): void; getWebSockets(tag?: string): WebSocket[]; @@ -568,6 +687,7 @@ interface DurableObjectStorage { deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; sync(): Promise; sql: SqlStorage; + kv: SyncKvStorage; transactionSync(closure: () => T): T; getCurrentBookmark(): Promise; getBookmarkForTime(timestamp: number | Date): Promise; @@ -604,6 +724,19 @@ declare class WebSocketRequestResponsePair { get request(): string; get response(): string; } +interface DurableObjectFacets { + get( + name: string, + getStartupOptions: () => FacetStartupOptions | Promise>, + ): Fetcher; + abort(name: string, reason: any): void; + delete(name: string): void; + clone(src: string, dst: string): void; +} +interface FacetStartupOptions { + id?: DurableObjectId | string; + class: DurableObjectClass; +} interface AnalyticsEngineDataset { writeDataPoint(event?: AnalyticsEngineDataPoint): void; } @@ -613,116 +746,120 @@ interface AnalyticsEngineDataPoint { blobs?: ((ArrayBuffer | string) | null)[]; } /** - * An event which takes place in the DOM. + * The **`Event`** interface represents an event which takes place on an `EventTarget`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ declare class Event { constructor(type: string, init?: EventInit); /** - * Returns the type of event, e.g. "click", "hashchange", or "submit". + * The **`type`** read-only property of the Event interface returns a string containing the event's type. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) */ get type(): string; /** - * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * The **`eventPhase`** read-only property of the being evaluated. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) */ get 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. + * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) */ get 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. + * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) */ get 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. + * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) */ get cancelable(): boolean; /** - * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) */ get defaultPrevented(): boolean; /** + * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) */ get returnValue(): boolean; /** - * Returns the object whose event listener's callback is currently being invoked. + * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) */ get currentTarget(): EventTarget | undefined; /** - * Returns the object to which event is dispatched (its target). + * The read-only **`target`** property of the dispatched. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) */ get target(): EventTarget | undefined; /** + * The deprecated **`Event.srcElement`** is an alias for the Event.target property. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) */ get srcElement(): EventTarget | undefined; /** - * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) */ get timeStamp(): number; /** - * Returns true if event was dispatched by the user agent, and false otherwise. + * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) */ get isTrusted(): boolean; /** + * The **`cancelBubble`** property of the Event interface is deprecated. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) */ get cancelBubble(): boolean; /** + * The **`cancelBubble`** property of the Event interface is deprecated. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) */ set cancelBubble(value: boolean); /** - * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) */ stopImmediatePropagation(): void; /** - * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) */ preventDefault(): void; /** - * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) */ stopPropagation(): void; /** - * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) */ @@ -745,26 +882,14 @@ type EventListenerOrEventListenerObject = | EventListener | EventListenerObject; /** - * EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. + * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) */ declare class EventTarget = Record> { constructor(); /** - * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. - * - * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. - * - * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. - * - * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. - * - * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. - * - * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. - * - * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) */ @@ -774,7 +899,7 @@ declare class EventTarget = Record = Record any | undefined; } /** - * A controller object that allows you to abort one or more DOM requests as and when desired. + * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) */ declare class AbortController { constructor(); /** - * Returns the AbortSignal object associated with this object. + * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) */ get signal(): AbortSignal; /** - * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) */ abort(reason?: any): void; } /** - * A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. + * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) */ declare abstract class AbortSignal extends EventTarget { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + /** + * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) + */ static abort(reason?: any): AbortSignal; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + /** + * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) + */ static timeout(delay: number): AbortSignal; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */ + /** + * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) + */ static any(signals: AbortSignal[]): AbortSignal; /** - * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) */ get aborted(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + /** + * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) + */ get reason(): any; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ get onabort(): any | null; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ set onabort(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + /** + * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) + */ throwIfAborted(): void; } interface Scheduler { @@ -856,19 +1001,27 @@ interface SchedulerWaitOptions { signal?: AbortSignal; } /** - * Extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. + * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ declare abstract class ExtendableEvent extends Event { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + /** + * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) + */ waitUntil(promise: Promise): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ +/** + * The **`CustomEvent`** interface represents events initialized by an application for any purpose. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) + */ declare class CustomEvent extends Event { constructor(type: string, init?: CustomEventCustomEventInit); /** - * Returns any custom data event was created with. Typically used for synthetic events. + * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) */ @@ -881,32 +1034,60 @@ interface CustomEventCustomEventInit { detail?: any; } /** - * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. + * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ declare class Blob { - constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); + /** + * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) + */ get size(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + /** + * The **`type`** read-only property of the Blob interface returns the MIME type of the file. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) + */ get type(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + /** + * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) + */ slice(start?: number, end?: number, type?: string): Blob; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + /** + * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) + */ arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) */ + /** + * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) + */ bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + /** + * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) + */ text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + /** + * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) + */ stream(): ReadableStream; } interface BlobOptions { type?: string; } /** - * Provides information about files and allows JavaScript in a web page to access their content. + * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ @@ -916,9 +1097,17 @@ declare class File extends Blob { name: string, options?: FileOptions, ); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + /** + * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) + */ get name(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + /** + * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) + */ get lastModified(): number; } interface FileOptions { @@ -931,7 +1120,11 @@ interface FileOptions { * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) */ declare abstract class CacheStorage { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + /** + * The **`open()`** method of the the Cache object matching the `cacheName`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) + */ open(cacheName: string): Promise; readonly default: Cache; } @@ -961,12 +1154,17 @@ interface CacheQueryOptions { */ declare abstract class Crypto { /** + * The **`Crypto.subtle`** read-only property returns a cryptographic operations. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) */ get subtle(): SubtleCrypto; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + /** + * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) + */ getRandomValues< T extends | Int8Array @@ -979,6 +1177,7 @@ declare abstract class Crypto { | BigUint64Array, >(buffer: T): T; /** + * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) @@ -987,49 +1186,77 @@ declare abstract class Crypto { DigestStream: typeof DigestStream; } /** - * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). + * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) */ declare abstract class SubtleCrypto { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) */ + /** + * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) + */ encrypt( algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView, ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */ + /** + * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) + */ decrypt( algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView, ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) */ + /** + * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) + */ sign( algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView, ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) */ + /** + * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) + */ verify( algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView, ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */ + /** + * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) + */ digest( algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView, ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + /** + * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) + */ generateKey( algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[], ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + /** + * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) + */ deriveKey( algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, @@ -1037,13 +1264,21 @@ declare abstract class SubtleCrypto { extractable: boolean, keyUsages: string[], ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */ + /** + * The **`deriveBits()`** method of the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) + */ deriveBits( algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null, ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + /** + * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) + */ importKey( format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, @@ -1051,16 +1286,28 @@ declare abstract class SubtleCrypto { extractable: boolean, keyUsages: string[], ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */ + /** + * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) + */ exportKey(format: string, key: CryptoKey): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) */ + /** + * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) + */ wrapKey( format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, ): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + /** + * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) + */ unwrapKey( format: string, wrappedKey: ArrayBuffer | ArrayBufferView, @@ -1073,17 +1320,29 @@ declare abstract class SubtleCrypto { timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; } /** - * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. + * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) */ declare abstract class CryptoKey { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + /** + * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) + */ readonly type: string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + /** + * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) + */ readonly extractable: boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + /** + * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) + */ readonly algorithm: | CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm @@ -1091,7 +1350,11 @@ declare abstract class CryptoKey { | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + /** + * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) + */ readonly usages: string[]; } interface CryptoKeyPair { @@ -1198,24 +1461,14 @@ declare class DigestStream extends WritableStream get bytesWritten(): number | bigint; } /** - * A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. + * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) */ declare class TextDecoder { constructor(label?: string, options?: TextDecoderConstructorOptions); /** - * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. - * - * ``` - * var string = "", decoder = new TextDecoder(encoding), buffer; - * while(buffer = next_chunk()) { - * string += decoder.decode(buffer, {stream:true}); - * } - * string += decoder.decode(); // end-of-queue - * ``` - * - * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) */ @@ -1225,24 +1478,24 @@ declare class TextDecoder { get ignoreBOM(): boolean; } /** - * TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. + * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) */ declare class TextEncoder { constructor(); /** - * Returns the result of running UTF-8's encoder. + * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) */ encode(input?: string): Uint8Array; /** - * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) */ - encodeInto(input: string, buffer: ArrayBuffer | ArrayBufferView): TextEncoderEncodeIntoResult; + encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; get encoding(): string; } interface TextDecoderConstructorOptions { @@ -1257,21 +1510,41 @@ interface TextEncoderEncodeIntoResult { written: number; } /** - * Events providing information related to errors in scripts or in files. + * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) */ declare class ErrorEvent extends Event { constructor(type: string, init?: ErrorEventErrorEventInit); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + /** + * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) + */ get filename(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + /** + * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) + */ get message(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + /** + * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) + */ get lineno(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + /** + * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) + */ get colno(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + /** + * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) + */ get error(): any; } interface ErrorEventErrorEventInit { @@ -1282,38 +1555,38 @@ interface ErrorEventErrorEventInit { error?: any; } /** - * A message received by a target object. + * The **`MessageEvent`** interface represents a message received by a target object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) */ declare class MessageEvent extends Event { constructor(type: string, initializer: MessageEventInit); /** - * Returns the data of the message. + * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) */ readonly data: any; /** - * Returns the origin of the message, for server-sent events and cross-document messaging. + * The **`origin`** read-only property of the origin of the message emitter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) */ readonly origin: string | null; /** - * Returns the last event ID string, for server-sent events. + * The **`lastEventId`** read-only property of the unique ID for the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) */ readonly lastEventId: string; /** - * Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects. + * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) */ readonly source: MessagePort | null; /** - * Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. + * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) */ @@ -1323,27 +1596,90 @@ interface MessageEventInit { data: ArrayBuffer | string; } /** - * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". + * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) + */ +declare abstract class PromiseRejectionEvent extends Event { + /** + * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) + */ + readonly promise: Promise; + /** + * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) + */ + readonly reason: any; +} +/** + * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ declare class FormData { constructor(); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ append(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ append(name: string, value: Blob, filename?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */ + /** + * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) + */ delete(name: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */ + /** + * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) + */ get(name: string): (File | string) | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */ - getAll(name: string): (File | string)[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ - has(name: string): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ + /** + * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) + */ + getAll(name: string): (File | string)[]; + /** + * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ set(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ set(name: string, value: Blob, filename?: string): void; /* Returns an array of key, value pairs for every entry in the list. */ entries(): IterableIterator<[key: string, value: File | string]>; @@ -1428,37 +1764,69 @@ interface DocumentEnd { append(content: string, options?: ContentOptions): DocumentEnd; } /** - * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch. + * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) */ declare abstract class FetchEvent extends ExtendableEvent { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ readonly request: Request; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + /** + * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) + */ respondWith(promise: Response | Promise): void; passThroughOnException(): void; } type HeadersInit = Headers | Iterable> | Record; /** - * This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. + * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) */ declare class Headers { constructor(init?: HeadersInit); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */ + /** + * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) + */ get(name: string): string | null; getAll(name: string): string[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */ + /** + * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) + */ getSetCookie(): string[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */ + /** + * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) + */ has(name: string): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */ + /** + * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) + */ set(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */ + /** + * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) + */ append(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */ + /** + * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) + */ delete(name: string): void; forEach( callback: (this: This, value: string, key: string, parent: Headers) => void, @@ -1479,7 +1847,9 @@ type BodyInit = | ArrayBufferView | Blob | URLSearchParams - | FormData; + | FormData + | Iterable + | AsyncIterable; declare abstract class Body { /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ get body(): ReadableStream | null; @@ -1499,7 +1869,7 @@ declare abstract class Body { blob(): Promise; } /** - * This Fetch API interface represents the response to a request. + * The **`Response`** interface of the Fetch API represents the response to a request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ @@ -1511,28 +1881,60 @@ declare var Response: { json(any: any, maybeInit?: ResponseInit | Response): Response; }; /** - * This Fetch API interface represents the response to a request. + * The **`Response`** interface of the Fetch API represents the response to a request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ interface Response extends Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + /** + * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) + */ clone(): Response; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + /** + * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) + */ status: number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + /** + * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) + */ statusText: string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ headers: Headers; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + /** + * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) + */ ok: boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + /** + * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) + */ redirected: boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + /** + * The **`url`** read-only property of the Response interface contains the URL of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) + */ url: string; webSocket: WebSocket | null; cf: any | undefined; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) */ + /** + * The **`type`** read-only property of the Response interface contains the type of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) + */ type: "default" | "error"; } interface ResponseInit { @@ -1547,7 +1949,7 @@ type RequestInfo> = | Request | string; /** - * This Fetch API interface represents a resource request. + * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ @@ -1559,63 +1961,67 @@ declare var Request: { ): Request; }; /** - * This Fetch API interface represents a resource request. + * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ interface Request> extends Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + /** + * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) + */ clone(): Request; /** - * Returns request's HTTP method, which is "GET" by default. + * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) */ method: string; /** - * Returns the URL of request as a string. + * The **`url`** read-only property of the Request interface contains the URL of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) */ 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. + * The **`headers`** read-only property of the with the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) */ 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. + * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) */ redirect: string; 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. + * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) */ signal: AbortSignal; - cf: Cf | undefined; + 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] + * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) */ integrity: string; /** - * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) */ keepalive: boolean; /** - * Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. + * The **`cache`** read-only property of the Request interface contains the cache mode of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) */ - cache?: "no-store"; + cache?: "no-store" | "no-cache"; } interface RequestInit { /* A string to set request's method. */ @@ -1629,7 +2035,7 @@ interface RequestInit { fetcher?: Fetcher | null; cf?: Cf; /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: "no-store"; + cache?: "no-store" | "no-cache"; /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ integrity?: string; /* An AbortSignal to set request's signal. */ @@ -1796,11 +2202,34 @@ interface KVNamespaceGetWithMetadataResult { } type QueueContentType = "text" | "bytes" | "json" | "v8"; interface Queue { - send(message: Body, options?: QueueSendOptions): Promise; + metrics(): Promise; + send(message: Body, options?: QueueSendOptions): Promise; sendBatch( messages: Iterable>, options?: QueueSendBatchOptions, - ): Promise; + ): Promise; +} +interface QueueSendMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface QueueSendMetadata { + metrics: QueueSendMetrics; +} +interface QueueSendResponse { + metadata: QueueSendMetadata; +} +interface QueueSendBatchMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface QueueSendBatchMetadata { + metrics: QueueSendBatchMetrics; +} +interface QueueSendBatchResponse { + metadata: QueueSendBatchMetadata; } interface QueueSendOptions { contentType?: QueueContentType; @@ -1814,6 +2243,19 @@ interface MessageSendRequest { contentType?: QueueContentType; delaySeconds?: number; } +interface QueueMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface MessageBatchMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface MessageBatchMetadata { + metrics: MessageBatchMetrics; +} interface QueueRetryOptions { delaySeconds?: number; } @@ -1828,12 +2270,14 @@ interface Message { interface QueueEvent extends ExtendableEvent { readonly messages: readonly Message[]; readonly queue: string; + readonly metadata: MessageBatchMetadata; retryAll(options?: QueueRetryOptions): void; ackAll(): void; } interface MessageBatch { readonly messages: readonly Message[]; readonly queue: string; + readonly metadata: MessageBatchMetadata; retryAll(options?: QueueRetryOptions): void; ackAll(): void; } @@ -1852,7 +2296,7 @@ interface R2ListOptions { startAfter?: string; include?: ("httpMetadata" | "customMetadata")[]; } -declare abstract class R2Bucket { +interface R2Bucket { head(key: string): Promise; get( key: string, @@ -2042,6 +2486,8 @@ interface Transformer { expectedLength?: number; } interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; /** * 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. * @@ -2060,8 +2506,6 @@ interface StreamPipeOptions { * 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; } type ReadableStreamReadResult = @@ -2074,33 +2518,61 @@ type ReadableStreamReadResult = 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. + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ interface ReadableStream { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + /** + * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) + */ get locked(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + /** + * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) + */ cancel(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ getReader(): ReadableStreamDefaultReader; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + /** + * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) + */ pipeThrough( transform: ReadableWritablePair, options?: StreamPipeOptions, ): ReadableStream; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + /** + * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) + */ pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + /** + * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) + */ tee(): [ReadableStream, ReadableStream]; values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; } /** - * 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. + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ @@ -2115,24 +2587,48 @@ declare const ReadableStream: { strategy?: QueuingStrategy, ): ReadableStream; }; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ +/** + * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) + */ declare class ReadableStreamDefaultReader { constructor(stream: ReadableStream); get closed(): Promise; cancel(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + /** + * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) + */ read(): Promise>; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + /** + * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) + */ releaseLock(): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ +/** + * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) + */ declare class ReadableStreamBYOBReader { constructor(stream: ReadableStream); get closed(): Promise; cancel(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + /** + * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) + */ read(view: T): Promise>; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + /** + * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) + */ releaseLock(): void; readAtLeast( minElements: number, @@ -2150,119 +2646,263 @@ interface ReadableStreamGetReaderOptions { */ mode: "byob"; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +/** + * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) + */ declare abstract class ReadableStreamBYOBRequest { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + /** + * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) + */ get view(): Uint8Array | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + /** + * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) + */ respond(bytesWritten: number): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + /** + * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) + */ respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; get atLeast(): number | null; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +/** + * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) + */ declare abstract class ReadableStreamDefaultController { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + /** + * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) + */ get desiredSize(): number | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ close(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + /** + * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) + */ enqueue(chunk?: R): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) + */ error(reason: any): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +/** + * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) + */ declare abstract class ReadableByteStreamController { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + /** + * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) + */ get byobRequest(): ReadableStreamBYOBRequest | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + /** + * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) + */ get desiredSize(): number | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ close(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + /** + * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) + */ enqueue(chunk: ArrayBuffer | ArrayBufferView): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + /** + * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) + */ 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. + * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) */ declare abstract class WritableStreamDefaultController { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + /** + * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) + */ get signal(): AbortSignal; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) + */ error(reason?: any): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +/** + * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) + */ declare abstract class TransformStreamDefaultController { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + /** + * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) + */ get desiredSize(): number | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + /** + * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) + */ enqueue(chunk?: O): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + /** + * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) + */ error(reason: any): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + /** + * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) + */ terminate(): void; } interface ReadableWritablePair { + readable: ReadableStream; /** * 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; - readable: ReadableStream; } /** - * This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. + * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) */ declare class WritableStream { constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + /** + * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) + */ get locked(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + /** + * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) + */ abort(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ close(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + /** + * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) + */ getWriter(): WritableStreamDefaultWriter; } /** - * This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. + * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) */ declare class WritableStreamDefaultWriter { constructor(stream: WritableStream); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + /** + * The **`closed`** read-only property of the the stream errors or the writer's lock is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) + */ get closed(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + /** + * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) + */ get ready(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + /** + * The **`desiredSize`** read-only property of the to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) + */ get desiredSize(): number | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + /** + * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) + */ abort(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ close(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ write(chunk?: W): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ releaseLock(): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ +/** + * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) + */ declare class TransformStream { constructor( transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy, ); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + /** + * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) + */ get readable(): ReadableStream; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + /** + * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) + */ get writable(): WritableStream; } declare class FixedLengthStream extends IdentityTransformStream { @@ -2283,23 +2923,39 @@ interface IdentityTransformStreamQueuingStrategy { interface ReadableStreamValuesOptions { preventCancel?: boolean; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ +/** + * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) + */ declare class CompressionStream extends TransformStream { constructor(format: "gzip" | "deflate" | "deflate-raw"); } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ +/** + * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) + */ declare class DecompressionStream extends TransformStream< ArrayBuffer | ArrayBufferView, Uint8Array > { constructor(format: "gzip" | "deflate" | "deflate-raw"); } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */ +/** + * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) + */ declare class TextEncoderStream extends TransformStream { constructor(); get encoding(): string; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ +/** + * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) + */ declare class TextDecoderStream extends TransformStream { constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); get encoding(): string; @@ -2311,25 +2967,33 @@ interface TextDecoderStreamTextDecoderStreamInit { ignoreBOM?: boolean; } /** - * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. + * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) */ declare class ByteLengthQueuingStrategy implements QueuingStrategy { constructor(init: QueuingStrategyInit); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + /** + * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) + */ get highWaterMark(): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ get size(): (chunk?: any) => number; } /** - * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. + * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) */ declare class CountQueuingStrategy implements QueuingStrategy { constructor(init: QueuingStrategyInit); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + /** + * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) + */ get highWaterMark(): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ get size(): (chunk?: any) => number; @@ -2342,6 +3006,11 @@ interface QueuingStrategyInit { */ highWaterMark: number; } +interface TracePreviewInfo { + id: string; + slug: string; + name: string; +} interface ScriptVersion { id?: string; tag?: string; @@ -2356,6 +3025,7 @@ interface TraceItem { | ( | TraceItemFetchEventInfo | TraceItemJsRpcEventInfo + | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo @@ -2374,6 +3044,9 @@ interface TraceItem { readonly scriptVersion?: ScriptVersion; readonly dispatchNamespace?: string; readonly scriptTags?: string[]; + readonly tailAttributes?: Record; + readonly preview?: TracePreviewInfo; + readonly durableObjectId?: string; readonly outcome: string; readonly executionModel: string; readonly truncated: boolean; @@ -2383,6 +3056,7 @@ interface TraceItem { interface TraceItemAlarmEventInfo { readonly scheduledTime: Date; } +type TraceItemConnectEventInfo = {}; type TraceItemCustomEventInfo = {}; interface TraceItemScheduledEventInfo { readonly scheduledTime: number; @@ -2461,111 +3135,231 @@ interface UnsafeTraceMetrics { fromTrace(item: TraceItem): TraceMetrics; } /** - * The URL interface represents an object providing static methods used for creating object URLs. + * The **`URL`** interface is used to parse, construct, normalize, and encode URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) */ declare class URL { constructor(url: string | URL, base?: string | URL); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + /** + * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) + */ get origin(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ get href(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ set href(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ get protocol(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ set protocol(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ get username(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ set username(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ get password(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ set password(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ get host(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ set host(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ get hostname(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ set hostname(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ get port(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ set port(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ get pathname(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ set pathname(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ get search(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ set search(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ get hash(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ set hash(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + /** + * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) + */ get searchParams(): URLSearchParams; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + /** + * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) + */ toJSON(): string; /*function toString() { [native code] }*/ toString(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + /** + * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) + */ static canParse(url: string, base?: string): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */ + /** + * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) + */ static parse(url: string, base?: string): URL | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */ + /** + * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) + */ static createObjectURL(object: File | Blob): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */ + /** + * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) + */ static revokeObjectURL(object_url: string): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ +/** + * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) + */ declare class URLSearchParams { constructor(init?: Iterable> | Record | string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) */ + /** + * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) + */ get size(): number; /** - * Appends a specified key/value pair as a new search parameter. + * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. + * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) */ delete(name: string, value?: string): void; /** - * Returns the first value associated to the given search parameter. + * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. + * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. + * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) */ has(name: string, value?: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) */ set(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) */ + /** + * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) + */ sort(): void; /* Returns an array of key, value pairs for every entry in the search params. */ entries(): IterableIterator<[key: string, value: string]>; @@ -2577,7 +3371,7 @@ declare class URLSearchParams { callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This, ): void; - /*function toString() { [native code] } Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ + /*function toString() { [native code] }*/ toString(): string; [Symbol.iterator](): IterableIterator<[key: string, value: string]>; } @@ -2629,26 +3423,26 @@ interface URLPatternOptions { ignoreCase?: boolean; } /** - * A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. + * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) */ declare class CloseEvent extends Event { constructor(type: string, initializer?: CloseEventInit); /** - * Returns the WebSocket connection close code provided by the server. + * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) */ readonly code: number; /** - * Returns the WebSocket connection close reason provided by the server. + * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) */ readonly reason: string; /** - * Returns true if the connection closed cleanly; false otherwise. + * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) */ @@ -2666,7 +3460,7 @@ type WebSocketEventMap = { error: ErrorEvent; }; /** - * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ @@ -2683,20 +3477,20 @@ declare var WebSocket: { readonly CLOSED: number; }; /** - * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(): void; + accept(options?: WebSocketAcceptOptions): void; /** - * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) */ send(message: (ArrayBuffer | ArrayBufferView) | string): void; /** - * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) */ @@ -2704,29 +3498,45 @@ interface WebSocket extends EventTarget { serializeAttachment(attachment: any): void; deserializeAttachment(): any | null; /** - * Returns the state of the WebSocket object's connection. It can have the values described below. + * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) */ readyState: number; /** - * Returns the URL that was used to establish the WebSocket connection. + * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) */ 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. + * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) */ protocol: string | null; /** - * Returns the extensions selected by the server, if any. + * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) */ extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: "blob" | "arraybuffer"; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; } declare const WebSocketPair: { new (): { @@ -2789,29 +3599,33 @@ interface SocketInfo { remoteAddress?: string; localAddress?: string; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ +/** + * The **`EventSource`** interface is web content's interface to server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) + */ declare class EventSource extends EventTarget { constructor(url: string, init?: EventSourceEventSourceInit); /** - * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) */ close(): void; /** - * Returns the URL providing the event stream. + * The **`url`** read-only property of the URL of the source. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) */ get url(): string; /** - * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) */ get withCredentials(): boolean; /** - * Returns the state of this EventSource object's connection. It can have the values described below. + * The **`readyState`** read-only property of the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) */ @@ -2837,6 +3651,28 @@ interface EventSourceEventSourceInit { withCredentials?: boolean; fetcher?: Fetcher; } +interface ExecOutput { + readonly stdout: ArrayBuffer; + readonly stderr: ArrayBuffer; + readonly exitCode: number; +} +interface ContainerExecOptions { + cwd?: string; + env?: Record; + user?: string; + stdin?: ReadableStream | "pipe"; + stdout?: "pipe" | "ignore"; + stderr?: "pipe" | "ignore" | "combined"; +} +interface ExecProcess { + readonly stdin: WritableStream | null; + readonly stdout: ReadableStream | null; + readonly stderr: ReadableStream | null; + readonly pid: number; + readonly exitCode: Promise; + output(): Promise; + kill(signal?: number): void; +} interface Container { get running(): boolean; start(options?: ContainerStartupOptions): void; @@ -2844,34 +3680,66 @@ interface Container { destroy(error?: any): Promise; signal(signo: number): void; getTcpPort(port: number): Fetcher; + setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; + snapshotDirectory( + options: ContainerDirectorySnapshotOptions, + ): Promise; + snapshotContainer(options: ContainerSnapshotOptions): Promise; + interceptOutboundHttps(addr: string, binding: Fetcher): Promise; + exec(cmd: string[], options?: ContainerExecOptions): Promise; +} +interface ContainerDirectorySnapshot { + id: string; + size: number; + dir: string; + name?: string; +} +interface ContainerDirectorySnapshotOptions { + dir: string; + name?: string; +} +interface ContainerDirectorySnapshotRestoreParams { + snapshot: ContainerDirectorySnapshot; + mountPoint?: string; +} +interface ContainerSnapshot { + id: string; + size: number; + name?: string; +} +interface ContainerSnapshotOptions { + name?: string; } interface ContainerStartupOptions { entrypoint?: string[]; enableInternet: boolean; env?: Record; + labels?: Record; + directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; + containerSnapshot?: ContainerSnapshot; } /** - * This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. + * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ -interface MessagePort extends EventTarget { +declare abstract class MessagePort extends EventTarget { /** - * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. - * - * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. + * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) */ postMessage(data?: any, options?: any[] | MessagePortPostMessageOptions): void; /** - * Disconnects the port, so that it is no longer active. + * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) */ close(): void; /** - * Begins dispatching messages received on the port. + * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) */ @@ -2879,1371 +3747,2701 @@ interface MessagePort extends EventTarget { get onmessage(): any | null; set onmessage(value: any | null); } +/** + * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) + */ +declare class MessageChannel { + constructor(); + /** + * The **`port1`** read-only property of the the port attached to the context that originated the channel. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) + */ + readonly port1: MessagePort; + /** + * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) + */ + readonly port2: MessagePort; +} interface MessagePortPostMessageOptions { transfer?: any[]; } -type AiImageClassificationInput = { - image: number[]; -}; -type AiImageClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; +type LoopbackForExport< + T extends + | (new ( + ...args: any[] + ) => Rpc.EntrypointBranded) + | ExportedHandler + | undefined = undefined, +> = T extends new ( + ...args: any[] +) => Rpc.WorkerEntrypointBranded + ? LoopbackServiceStub> + : T extends new ( + ...args: any[] + ) => Rpc.DurableObjectBranded + ? LoopbackDurableObjectClass> + : T extends ExportedHandler + ? LoopbackServiceStub + : undefined; +type LoopbackServiceStub = + Fetcher & + (T extends CloudflareWorkersModule.WorkerEntrypoint + ? (opts: { props?: Props }) => Fetcher + : (opts: { props?: any }) => Fetcher); +type LoopbackDurableObjectClass = + DurableObjectClass & + (T extends CloudflareWorkersModule.DurableObject + ? (opts: { props?: Props }) => DurableObjectClass + : (opts: { props?: any }) => DurableObjectClass); +interface LoopbackDurableObjectNamespace extends DurableObjectNamespace {} +interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace {} +interface SyncKvStorage { + get(key: string): T | undefined; + list(options?: SyncKvListOptions): Iterable<[string, T]>; + put(key: string, value: T): void; + delete(key: string): boolean; +} +interface SyncKvListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; } -type AiImageToTextInput = { - image: number[]; - prompt?: string; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; +interface WorkerStub { + getEntrypoint( + name?: string, + options?: WorkerStubEntrypointOptions, + ): Fetcher; + getDurableObjectClass( + name?: string, + options?: WorkerStubEntrypointOptions, + ): DurableObjectClass; +} +interface WorkerStubEntrypointOptions { + props?: any; + limits?: workerdResourceLimits; +} +interface WorkerLoader { + get( + name: string | null, + getCode: () => WorkerLoaderWorkerCode | Promise, + ): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; +} +interface WorkerLoaderModule { + js?: string; + cjs?: string; + text?: string; + data?: ArrayBuffer; + json?: any; + py?: string; + wasm?: ArrayBuffer; +} +interface WorkerLoaderWorkerCode { + compatibilityDate: string; + compatibilityFlags?: string[]; + allowExperimental?: boolean; + limits?: workerdResourceLimits; + mainModule: string; + modules: Record; + env?: any; + globalOutbound?: Fetcher | null; + tails?: Fetcher[]; + streamingTails?: Fetcher[]; +} +interface workerdResourceLimits { + cpuMs?: number; + subRequests?: number; } -type AiImageTextToTextInput = { - image: string; - prompt?: string; - max_tokens?: number; - temperature?: number; - ignore_eos?: boolean; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageTextToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; +/** + * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, + * as well as timing of subrequests and other operations. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) + */ +declare abstract class Performance { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + get timeOrigin(): number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number; + /** + * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) + */ + toJSON(): object; } -type AiObjectDetectionInput = { - image: number[]; -}; -type AiObjectDetectionOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; +interface Tracing { + enterSpan( + name: string, + callback: (span: Span, ...args: A) => T, + ...args: A + ): T; + startActiveSpan( + name: string, + callback: (span: Span, ...args: A) => T, + ...args: A + ): T; + Span: typeof Span; } -type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; -}; -type AiSentenceSimilarityOutput = number[]; -declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; +declare abstract class Span { + get isTraced(): boolean; + setAttribute(key: string, value?: boolean | number | string): void; + end(): void; } -type AiAutomaticSpeechRecognitionInput = { - audio: number[]; -}; -type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; -}; -declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; +/** + * Represents the identity of a user authenticated via Cloudflare Access. + * This matches the result of calling /cdn-cgi/access/get-identity. + * + * The exact structure of the returned object depends on the identity provider + * configuration for the Access application. The fields below represent commonly + * available properties, but additional provider-specific fields may be present. + */ +interface CloudflareAccessIdentity extends Record { + /** The user's email address, if available from the identity provider. */ + email?: string; + /** The user's display name. */ + name?: string; + /** The user's unique identifier. */ + user_uuid?: string; + /** The Cloudflare account ID. */ + account_id?: string; + /** Login timestamp (Unix epoch seconds). */ + iat?: number; + /** The user's IP address at authentication time. */ + ip?: string; + /** Authentication methods used (e.g., "pwd"). */ + amr?: string[]; + /** Identity provider information. */ + idp?: { + id: string; + type: string; + }; + /** Geographic information about where the user authenticated. */ + geo?: { + country: string; + }; + /** Group memberships from the identity provider. */ + groups?: Array<{ + id: string; + name: string; + email?: string; + }>; + /** Device posture check results, keyed by check ID. */ + devicePosture?: Record; + /** True if the user connected via Cloudflare WARP. */ + is_warp?: boolean; + /** True if the user is authenticated via Cloudflare Gateway. */ + is_gateway?: boolean; +} +// ============================================================================ +// Agent Memory +// +// Public type surface for user Workers binding to an Agent Memory namespace. +// ============================================================================ +/** Memory type — every memory is classified into exactly one. */ +type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task"; +/** Search intensity for recall. */ +type AgentMemoryThinkingLevel = "low" | "medium" | "high"; +/** Response verbosity for recall. */ +type AgentMemoryResponseLength = "short" | "medium" | "long"; +/** A conversation message passed to ingest(). */ +interface AgentMemoryMessage { + role: "system" | "user" | "assistant"; + content: string; + /** Optional message timestamp. */ + timestamp?: Date; } -type AiSummarizationInput = { - input_text: string; - max_length?: number; -}; -type AiSummarizationOutput = { +/** Raw memory content passed to remember(). */ +interface AgentMemoryIncomingMemory { + /** Raw memory content. The service classifies and summarizes automatically. */ + content: string; + /** Optional session identifier to associate with this memory. */ + sessionId?: string | null | undefined; +} +/** A stored memory returned from remember(), get(), and delete(). */ +interface AgentMemoryMemory { + /** Memory ID. */ + id: string; + /** Memory type. */ + type: AgentMemoryMemoryType; + /** Text summary. */ summary: string; -}; -declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; + /** Memory text. */ + content: string; + /** Session that created this memory. */ + sessionId: string | null; + /** Memory creation time. */ + createdAt: Date; + /** Memory last-update time. */ + updatedAt: Date; +} +/** Single entry in a list() response. Same shape as Memory minus full content. */ +type AgentMemoryMemoryListEntry = Omit; +/** A scored memory candidate in a recall result. */ +interface AgentMemoryScoredCandidate { + /** Candidate ID. */ + id: string; + /** Text summary. */ + summary: string; + /** Session that created this candidate, when known. */ + sessionId: string | null; + /** Relevance score (higher is better). Comparable only within a single query. */ + score: number; } -type AiTextClassificationInput = { - text: string; -}; -type AiTextClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; +/** Options for the ingest() method. */ +interface AgentMemoryIngestOptions { + /** Session identifier to associate with memories created during ingestion. */ + sessionId?: string | null | undefined; } -type AiTextEmbeddingsInput = { - text: string | string[]; +/** Options for the getSummary() method. */ +interface AgentMemoryGetSummaryOptions { + /** Session identifier to retrieve session summary for. */ + sessionId?: string | null | undefined; +} +/** Response from the getSummary() method. */ +interface AgentMemoryGetSummaryResponse { + /** Markdown summary. */ + summary: string; +} +/** + * Options for the recall() method. + * + * `referenceDate` accepts a Date object, an ISO-8601 date string + * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this + * date is used as "today" for resolving relative time references + * ("how many days ago", "last week") instead of the server's wall-clock time. + */ +interface AgentMemoryRecallOptions { + /** Recall intensity: "low" (default), "medium", or "high". */ + thinkingLevel?: AgentMemoryThinkingLevel; + /** Response verbosity: "short", "medium" (default), or "long". */ + responseLength?: AgentMemoryResponseLength; + /** Temporal anchor for date arithmetic. */ + referenceDate?: Date | string; +} +/** Response from the recall() method. */ +interface AgentMemoryRecallResult { + /** Number of memories retrieved. */ + count: number; + /** LLM-generated answer synthesizing the matching memories. */ + answer: string; + /** Matching memories ranked by relevance. */ + candidates: AgentMemoryScoredCandidate[]; +} +/** + * Options for the list() method. + * + * `cursor` is the opaque continuation token returned by the previous page; + * pass it back unchanged to fetch the next page. `sessionId` and `type` + * are exact-match filters; combining them is allowed. + */ +interface AgentMemoryListMemoriesOptions { + /** Maximum number of memories to return. Default 20, max 500. */ + limit?: number; + /** Opaque cursor from a previous page. */ + cursor?: string; + /** Exact-match session filter. */ + sessionId?: string; + /** Exact-match memory-type filter. */ + type?: AgentMemoryMemoryType; +} +/** Response from the list() method. */ +interface AgentMemoryListMemoriesResult { + memories: AgentMemoryMemoryListEntry[]; + /** Continuation cursor; absent when this page exhausted the result set. */ + cursor?: string; +} +/** + * A single Agent Memory profile, scoped to a profile name. + * + * Returned by {@link AgentMemoryNamespace.getProfile}. + */ +declare abstract class AgentMemoryProfile { + /** + * Retrieve a memory by ID. + * + * @param memoryId - ULID of the memory to retrieve. + * @throws if the memory does not exist. + */ + get(memoryId: string): Promise; + /** + * Delete a memory by ID. + * + * Removes the memory and any source messages linked by the memory's + * source message IDs. + * + * @param memoryId - ULID of the memory to delete. + * @throws if the memory does not exist. + */ + delete(memoryId: string): Promise; + /** + * Store a memory in this profile. The content is automatically classified, + * summarized, and indexed. + * + * @param memory - Raw memory content to persist. + */ + remember(memory: AgentMemoryIncomingMemory): Promise; + /** + * Extract memories from a conversation. + * + * @param messages - Conversation messages to extract memories from. + * @param options - Optional ingest options. + */ + ingest(messages: Iterable, options?: AgentMemoryIngestOptions): Promise; + /** + * Get a profile summary. + * + * @param options - Optional getSummary options. + */ + getSummary(options?: AgentMemoryGetSummaryOptions): Promise; + /** + * Recall memories in this profile. + * + * @param query - Recall query matched against memory content and keywords. + * @param options - Optional recall parameters. + * @returns Matching memories with relevance scores and a synthesized answer. + */ + recall(query: string, options?: AgentMemoryRecallOptions): Promise; + /** + * List active memories in this profile. + * + * Returns a paginated, filterable view of stored memories. Superseded + * versions are excluded. Use the returned `cursor` (when present) to + * fetch the next page. + * + * @param options - Optional pagination and filter options. + */ + list(options?: AgentMemoryListMemoriesOptions): Promise; + /** + * Soft-delete every memory and message in this profile that is tagged + * with `sessionId`. + * + * Idempotent: deleting a sessionId that has no rows is a no-op. + * + * @param sessionId - Session to delete. + */ + deleteSession(sessionId: string): Promise; +} +/** + * Namespace-level Agent Memory binding. + * + * Used as the type of an `env.MEMORY`-style binding backed by the Agent + * Memory product. + * + * @example + * ```ts + * export default { + * async fetch(_request: Request, env: Env): Promise { + * const profile = await env.MEMORY.getProfile("wrangler-e2e"); + * const summary = await profile.getSummary(); + * return Response.json(summary); + * }, + * }; + * ``` + */ +declare abstract class AgentMemoryNamespace { + /** + * Get a memory profile by name. Profiles are isolated by namespace and + * addressed by a compound key (namespaceId:profileName). + * + * @param profileName - Profile name (validated against naming rules). + * @returns RPC target for interacting with the profile. + */ + getProfile(profileName: string): Promise; + /** + * Soft-delete a profile and schedule deferred purge. Marks all + * memories and messages as deleted. + * + * @param profileName - Name of the profile to delete. + */ + deleteProfile(profileName: string): Promise; +} +// ============ AI Search Error Interfaces ============ +interface AiSearchInternalError extends Error {} +interface AiSearchNotFoundError extends Error {} +// ============ AI Search Common Types ============ +/** A single message in a conversation-style search or chat request. */ +type AiSearchMessage = { + role: "system" | "developer" | "user" | "assistant" | "tool"; + content: string | null; }; -type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; +/** + * Common shape for `ai_search_options` used by both single-instance and multi-instance requests. + * Contains retrieval, query rewrite, reranking, and cache sub-options. + */ +type AiSearchOptions = { + retrieval?: { + /** Which retrieval backend to use. Defaults to the instance's configured index_method. */ + retrieval_type?: "vector" | "keyword" | "hybrid"; + /** Fusion method for combining vector + keyword results. */ + fusion_method?: "max" | "rrf"; + /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */ + keyword_match_mode?: "and" | "or"; + /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */ + match_threshold?: number; + /** Maximum number of results to return (1-50). Default 10. */ + max_num_results?: number; + /** Vectorize metadata filters applied to the search. */ + filters?: VectorizeVectorMetadataFilter; + /** Number of surrounding chunks to include for context (0-3). Default 0. */ + context_expansion?: number; + /** If true, return only item metadata without chunk text. */ + metadata_only?: boolean; + /** If true (default), return empty results on retrieval failure instead of throwing. */ + return_on_failure?: boolean; + /** Boost results by metadata field values. Max 3 entries. */ + boost_by?: Array<{ + field: string; + direction?: "asc" | "desc" | "exists" | "not_exists"; + }>; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: string; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + cache?: { + enabled?: boolean; + cache_threshold?: "super_strict_match" | "close_enough" | "flexible_friend" | "anything_goes"; + }; + [key: string]: unknown; }; -declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; -} -type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; +// ============ AI Search Request Types ============ +/** + * Request body for single-instance search. + * Exactly one of `query` or `messages` must be provided. + */ +type AiSearchSearchRequest = + | { + /** Simple query string. */ + query: string; + messages?: never; + ai_search_options?: AiSearchOptions; + } + | { + query?: never; + /** Conversation-style input. At least one user message with non-empty content is required. */ + messages: AiSearchMessage[]; + ai_search_options?: AiSearchOptions; + }; +type AiSearchChatCompletionsRequest = { + messages: AiSearchMessage[]; + model?: string; + stream?: boolean; + ai_search_options?: AiSearchOptions; + [key: string]: unknown; }; -type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; +// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============ +/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */ +type AiSearchMultiSearchOptions = AiSearchOptions & { + /** Instance IDs to search across (1-10). */ + instance_ids: string[]; +}; +/** + * Request for searching across multiple instances within a namespace. + * `ai_search_options` is required and must include `instance_ids`. + * Exactly one of `query` or `messages` must be provided. + */ +type AiSearchMultiSearchRequest = + | { + /** Simple query string. */ + query: string; + messages?: never; + ai_search_options: AiSearchMultiSearchOptions; + } + | { + query?: never; + /** Conversation-style input. */ + messages: AiSearchMessage[]; + ai_search_options: AiSearchMultiSearchOptions; + }; +/** A search result chunk tagged with the instance it originated from. */ +type AiSearchMultiSearchChunk = AiSearchSearchResponse["chunks"][number] & { + instance_id: string; +}; +/** Describes a per-instance error during a multi-instance operation. */ +type AiSearchMultiSearchError = { + instance_id: string; + message: string; +}; +/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */ +type AiSearchMultiSearchResponse = { + search_query: string; + chunks: AiSearchMultiSearchChunk[]; + errors?: AiSearchMultiSearchError[]; +}; +/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */ +type AiSearchMultiChatCompletionsRequest = Omit< + AiSearchChatCompletionsRequest, + "ai_search_options" +> & { + ai_search_options: AiSearchMultiSearchOptions; +}; +/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */ +type AiSearchMultiChatCompletionsResponse = Omit & { + chunks: AiSearchMultiSearchChunk[]; + errors?: AiSearchMultiSearchError[]; +}; +// ============ AI Search Response Types ============ +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; }; - required: string[]; - }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + /** Keyword rank position */ + keyword_rank?: number; + /** Vector rank position */ + vector_rank?: number; + /** Reranking model score */ + reranking_score?: number; + /** Fusion method used to combine results */ + fusion_method?: "rrf" | "max"; + [key: string]: unknown; + }; + }>; }; -type AiTextGenerationToolInput = { - type: "function" | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; +type AiSearchChatCompletionsResponse = { + id?: string; + object?: string; + model?: string; + choices: Array<{ + index?: number; + message: { + role: "system" | "developer" | "user" | "assistant" | "tool"; + content: string | null; + [key: string]: unknown; + }; + [key: string]: unknown; + }>; + chunks: AiSearchSearchResponse["chunks"]; + [key: string]: unknown; +}; +type AiSearchStatsResponse = { + queued?: number; + running?: number; + completed?: number; + error?: number; + skipped?: number; + outdated?: number; + last_activity?: string; + /** Storage engine statistics. */ + engine?: { + vectorize?: { + vectorsCount: number; + dimensions: number; + }; + r2?: { + payloadSizeBytes: number; + metadataSizeBytes: number; + objectCount: number; }; }; }; -type AiTextGenerationFunctionsInput = { - name: string; - code: string; +// ============ AI Search Instance Info Types ============ +type AiSearchInstanceInfo = { + id: string; + type?: "r2" | "web-crawler" | string; + source?: string; + source_params?: unknown; + paused?: boolean; + status?: string; + namespace?: string; + created_at?: string; + modified_at?: string; + token_id?: string; + ai_gateway_id?: string; + rewrite_query?: boolean; + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; + rewrite_model?: string; + reranking_model?: string; + /** @deprecated Use index_method instead. */ + hybrid_search_enabled?: boolean; + /** Controls which storage backends are active. */ + index_method?: { + vector?: boolean; + keyword?: boolean; + }; + /** Fusion method for combining vector and keyword results. */ + fusion_method?: "max" | "rrf"; + indexing_options?: { + keyword_tokenizer?: "porter" | "trigram"; + } | null; + retrieval_options?: { + keyword_match_mode?: "and" | "or"; + boost_by?: Array<{ + field: string; + direction?: "asc" | "desc" | "exists" | "not_exists"; + }>; + } | null; + chunk?: boolean; + chunk_size?: number; + chunk_overlap?: number; + score_threshold?: number; + max_num_results?: number; + cache?: boolean; + cache_threshold?: "super_strict_match" | "close_enough" | "flexible_friend" | "anything_goes"; + custom_metadata?: Array<{ + field_name: string; + data_type: "text" | "number" | "boolean" | "datetime"; + }>; + /** Sync interval in seconds. */ + sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; + metadata?: Record; + [key: string]: unknown; }; -type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; +/** Pagination, search, and ordering parameters for listing instances within a namespace. */ +type AiSearchListInstancesParams = { + page?: number; + per_page?: number; + /** Search instances by ID. */ + search?: string; + /** Field to sort by. */ + order_by?: "created_at"; + /** Sort direction. */ + order_by_direction?: "asc" | "desc"; }; -type AiTextGenerationInput = { - prompt?: string; - raw?: boolean; - stream?: boolean; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - messages?: RoleScopedChatInput[]; - response_format?: AiTextGenerationResponseFormat; - tools?: - | AiTextGenerationToolInput[] - | AiTextGenerationToolLegacyInput[] - | (object & NonNullable); - functions?: AiTextGenerationFunctionsInput[]; +type AiSearchListResponse = { + result: AiSearchInstanceInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; }; -type AiTextGenerationOutput = { - response?: string; - tool_calls?: { - name: string; - arguments: unknown; - }[]; +// ============ AI Search Config Types ============ +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + /** Instance type. Omit to create with built-in storage. */ + type?: "r2" | "web-crawler" | string; + /** Source URL (required for web-crawler type). */ + source?: string; + source_params?: unknown; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; + rewrite_model?: string; + reranking_model?: string; + /** @deprecated Use index_method instead. */ + hybrid_search_enabled?: boolean; + /** Controls which storage backends are used during indexing. Defaults to vector-only. */ + index_method?: { + vector?: boolean; + keyword?: boolean; + }; + /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */ + fusion_method?: "max" | "rrf"; + indexing_options?: { + keyword_tokenizer?: "porter" | "trigram"; + } | null; + retrieval_options?: { + keyword_match_mode?: "and" | "or"; + boost_by?: Array<{ + field: string; + direction?: "asc" | "desc" | "exists" | "not_exists"; + }>; + } | null; + chunk?: boolean; + chunk_size?: number; + chunk_overlap?: number; + /** Minimum similarity score (0-1) for a result to be included. */ + score_threshold?: number; + max_num_results?: number; + cache?: boolean; + /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */ + cache_threshold?: "super_strict_match" | "close_enough" | "flexible_friend" | "anything_goes"; + custom_metadata?: Array<{ + field_name: string; + data_type: "text" | "number" | "boolean" | "datetime"; + }>; + namespace?: string; + /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */ + sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; + metadata?: Record; + [key: string]: unknown; }; -declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; -} -type AiTextToSpeechInput = { - prompt: string; - lang?: string; +// ============ AI Search Item Types ============ +type AiSearchItemInfo = { + id: string; + key: string; + status: "completed" | "error" | "skipped" | "queued" | "running" | "outdated"; + next_action?: "INDEX" | "DELETE" | null; + error?: string; + checksum?: string; + namespace?: string; + chunks_count?: number | null; + file_size?: number | null; + source_id?: string | null; + last_seen_at?: string; + created_at?: string; + metadata?: Record; + [key: string]: unknown; }; -type AiTextToSpeechOutput = - | Uint8Array - | { - audio: string; - }; -declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; -} -type AiTextToImageInput = { - prompt: string; - negative_prompt?: string; - height?: number; - width?: number; - image?: number[]; - image_b64?: string; - mask?: number[]; - num_steps?: number; - strength?: number; - guidance?: number; - seed?: number; +type AiSearchItemContentResult = { + body: ReadableStream; + contentType: string; + filename: string; + size: number; }; -type AiTextToImageOutput = ReadableStream; -declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput; - postProcessedOutputs: AiTextToImageOutput; -} -type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; +type AiSearchUploadItemOptions = { + metadata?: Record; }; -type AiTranslationOutput = { - translated_text?: string; +type AiSearchListItemsParams = { + page?: number; + per_page?: number; + /** Search items by key name. */ + search?: string; + /** Sort order for results. */ + sort_by?: "status" | "modified_at"; + /** Filter items by processing status. */ + status?: "queued" | "running" | "completed" | "error" | "skipped" | "outdated"; + /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */ + source?: string; + /** JSON-encoded Vectorize filter for metadata filtering. */ + metadata_filter?: string; }; -declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; -} -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; - }; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; - } - | AsyncResponse; -interface AsyncResponse { +type AiSearchListItemsResponse = { + result: AiSearchItemInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Item Logs Types ============ +type AiSearchItemLogsParams = { + /** Maximum number of log entries to return (1-100, default 50). */ + limit?: number; + /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */ + cursor?: string; +}; +type AiSearchItemLog = { + timestamp: string; + action: string; + message: string; + fileKey?: string; + chunkCount?: number; + processingTimeMs?: number; + errorType?: string; +}; +/** Paginated response for item processing logs (cursor-based). */ +type AiSearchItemLogsResponse = { + result: AiSearchItemLog[]; + result_info: { + count: number; + per_page: number; + cursor: string | null; + truncated: boolean; + }; +}; +// ============ AI Search Item Chunks Types ============ +type AiSearchItemChunksParams = { + /** Maximum number of chunks to return (1-100, default 20). */ + limit?: number; + /** Offset into the chunks list (default 0). */ + offset?: number; +}; +/** A single indexed chunk belonging to an item, including its text content and byte range. */ +type AiSearchItemChunk = { + id: string; + text: string; + start_byte: number; + end_byte: number; + item?: { + timestamp?: number; + key: string; + metadata?: Record; + }; +}; +/** Paginated response for item chunks (offset-based). */ +type AiSearchItemChunksResponse = { + result: AiSearchItemChunk[]; + result_info: { + count: number; + total: number; + limit: number; + offset: number; + }; +}; +// ============ AI Search Job Types ============ +type AiSearchJobInfo = { + id: string; + source: "user" | "schedule"; + description?: string; + last_seen_at?: string; + started_at?: string; + ended_at?: string; + end_reason?: string; +}; +type AiSearchJobLog = { + id: number; + message: string; + message_type: number; + created_at: number; +}; +type AiSearchCreateJobParams = { + description?: string; +}; +type AiSearchListJobsParams = { + page?: number; + per_page?: number; +}; +type AiSearchListJobsResponse = { + result: AiSearchJobInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +type AiSearchJobLogsParams = { + page?: number; + per_page?: number; +}; +type AiSearchJobLogsResponse = { + result: AiSearchJobLog[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Sub-Service Classes ============ +/** + * Single item service for an AI Search instance. + * Provides info, download, sync, logs, and chunks operations on a specific item. + */ +declare abstract class AiSearchItem { + /** Get metadata about this item. */ + info(): Promise; /** - * The async request id that can be used to obtain the results. + * Download the item's content. + * @returns Object with body stream, content type, filename, and size. */ - request_id?: string; + download(): Promise; + /** + * Trigger re-indexing of this item. + * @returns The updated item info. + */ + sync(): Promise; + /** + * Retrieve processing logs for this item (cursor-based pagination). + * @param params Optional pagination parameters (limit, cursor). + * @returns Paginated log entries for this item. + */ + logs(params?: AiSearchItemLogsParams): Promise; + /** + * List indexed chunks for this item (offset-based pagination). + * @param params Optional pagination parameters (limit, offset). + * @returns Paginated chunk entries for this item. + */ + chunks(params?: AiSearchItemChunksParams): Promise; } -declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; +/** + * Items collection service for an AI Search instance. + * Provides list, upload, and access to individual items. + */ +declare abstract class AiSearchItems { + /** List items in this instance. */ + list(params?: AiSearchListItemsParams): Promise; + /** + * Upload a file as an item. Behaves as an upsert: if an item with the same + * filename already exists, it is overwritten and re-indexed. + * @param name Filename for the uploaded item. + * @param content File content as a ReadableStream, Blob, or string. + * @param options Optional metadata to attach to the item. + * @returns The created item info. + */ + upload( + name: string, + content: ReadableStream | Blob | string, + options?: AiSearchUploadItemOptions, + ): Promise; + /** + * Upload a file and poll until processing completes. + * Behaves as an upsert: if an item with the same filename already exists, + * it is overwritten and re-indexed. + * @param name Filename for the uploaded item. + * @param content File content as a ReadableStream, Blob, or string. + * @param options Optional metadata and polling configuration. + * @returns The item info after processing completes (or timeout). + */ + uploadAndPoll( + name: string, + content: ReadableStream | Blob | string, + options?: AiSearchUploadItemOptions & { + /** Polling interval in milliseconds (default 1000). */ + pollIntervalMs?: number; + /** Maximum time to wait in milliseconds (default 30000). */ + timeoutMs?: number; + }, + ): Promise; + /** + * Get an item by ID. + * @param itemId The item identifier. + * @returns Item service for info, download, sync, logs, and chunks operations. + */ + get(itemId: string): AiSearchItem; + /** + * Delete an item from the instance. + * @param itemId The item identifier. + */ + delete(itemId: string): Promise; } -type Ai_Cf_Openai_Whisper_Input = - | string - | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; - }; -interface Ai_Cf_Openai_Whisper_Output { +/** + * Single job service for an AI Search instance. + * Provides info, logs, and cancel operations for a specific job. + */ +declare abstract class AiSearchJob { + /** Get metadata about this job. */ + info(): Promise; + /** Get logs for this job. */ + logs(params?: AiSearchJobLogsParams): Promise; /** - * The transcription + * Cancel a running job. + * @returns The updated job info. + * @throws AiSearchNotFoundError if the job does not exist. */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; + cancel(): Promise; } -declare abstract class Base_Ai_Cf_Openai_Whisper { - inputs: Ai_Cf_Openai_Whisper_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +/** + * Jobs collection service for an AI Search instance. + * Provides list, create, and access to individual jobs. + */ +declare abstract class AiSearchJobs { + /** List jobs for this instance. */ + list(params?: AiSearchListJobsParams): Promise; + /** + * Create a new indexing job. + * @param params Optional job parameters. + * @returns The created job info. + */ + create(params?: AiSearchCreateJobParams): Promise; + /** + * Get a job by ID. + * @param jobId The job identifier. + * @returns Job service for info, logs, and cancel operations. + */ + get(jobId: string): AiSearchJob; } -type Ai_Cf_Meta_M2M100_1_2B_Input = - | { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - }[]; - }; -type Ai_Cf_Meta_M2M100_1_2B_Output = - | { - /** - * The translated text in the target language - */ - translated_text?: string; - } - | AsyncResponse; -declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input; - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; +// ============ AI Search Binding Classes ============ +/** + * Instance-level AI Search service. + * + * Used as: + * - The return type of `AiSearchNamespace.get(name)` (namespace binding) + * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`) + * + * Provides search, chat, update, stats, items, and jobs operations. + * + * @example + * ```ts + * // Via namespace binding + * const instance = env.AI_SEARCH.get("blog"); + * const results = await instance.search({ + * query: "How does caching work?", + * }); + * + * // Via single instance binding + * const results = await env.BLOG_SEARCH.search({ + * messages: [{ role: "user", content: "How does caching work?" }], + * }); + * ``` + */ +declare abstract class AiSearchInstance { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with query or messages and optional AI search options. + * @returns Search response with matching chunks and search query. + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context (streaming). + * @param params Chat completions request with stream: true. + * @returns ReadableStream of server-sent events. + */ + chatCompletions( + params: AiSearchChatCompletionsRequest & { + stream: true; + }, + ): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request. + * @returns Chat completion response with choices and RAG chunks. + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Update the instance configuration. + * @param config Partial configuration to update. + * @returns Updated instance info. + */ + update(config: Partial): Promise; + /** Get metadata about this instance. */ + info(): Promise; + /** + * Get instance statistics (item count, indexing status, etc.). + * @returns Statistics with counts per status, last activity time, and engine details. + */ + stats(): Promise; + /** Items collection — list, upload, and manage items in this instance. */ + get items(): AiSearchItems; + /** Jobs collection — list, create, and inspect indexing jobs. */ + get jobs(): AiSearchJobs; } -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; - }; -type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; - } - | AsyncResponse; -declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; +/** + * Namespace-level AI Search service. + * + * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`). + * Scoped to a single namespace. Provides dynamic instance access, creation, deletion, + * and multi-instance search/chat operations. + * + * @example + * ```ts + * // Access an instance within the namespace + * const blog = env.AI_SEARCH.get("blog"); + * const results = await blog.search({ query: "How does caching work?" }); + * + * // List all instances in the namespace + * const instances = await env.AI_SEARCH.list(); + * + * // Create a new instance with built-in storage + * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" }); + * + * // Upload items into the instance + * await tenant.items.upload("doc.pdf", fileContent); + * + * // Search across multiple instances + * const multi = await env.AI_SEARCH.search({ + * query: "caching", + * ai_search_options: { instance_ids: ["blog", "docs"] }, + * }); + * + * // Delete an instance + * await env.AI_SEARCH.delete("tenant-123"); + * ``` + */ +declare abstract class AiSearchNamespace { + /** + * Get an instance by name within the bound namespace. + * @param name Instance name. + * @returns Instance service for search, chat, update, stats, items, and jobs. + */ + get(name: string): AiSearchInstance; + /** + * List instances in the bound namespace. + * @param params Optional pagination, search, and ordering parameters. + * @returns Array of instance metadata with pagination info. + */ + list(params?: AiSearchListInstancesParams): Promise; + /** + * Create a new instance within the bound namespace. + * @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage. + * @returns Instance service for the newly created instance. + * + * @example + * ```ts + * // Create with built-in storage (upload items manually) + * const instance = await env.AI_SEARCH.create({ id: "my-search" }); + * + * // Create with web crawler source + * const instance = await env.AI_SEARCH.create({ + * id: "docs-search", + * type: "web-crawler", + * source: "https://developers.cloudflare.com", + * }); + * ``` + */ + create(config: AiSearchConfig): Promise; + /** + * Delete an instance from the bound namespace. + * @param name Instance name to delete. + */ + delete(name: string): Promise; + /** + * Search across multiple instances within the bound namespace. + * Fans out to the specified instance_ids and merges results. + * @param params Search request with required `ai_search_options.instance_ids`. + * @returns Search response with chunks tagged by instance_id and optional partial-failure errors. + */ + search(params: AiSearchMultiSearchRequest): Promise; + /** + * Generate chat completions across multiple instances within the bound namespace (streaming). + * Fans out to the specified instance_ids, merges context, and generates a response. + * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`. + * @returns ReadableStream of server-sent events. + */ + chatCompletions( + params: AiSearchMultiChatCompletionsRequest & { + stream: true; + }, + ): Promise; + /** + * Generate chat completions across multiple instances within the bound namespace. + * Fans out to the specified instance_ids, merges context, and generates a response. + * @param params Chat completions request with required `ai_search_options.instance_ids`. + * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors. + */ + chatCompletions( + params: AiSearchMultiChatCompletionsRequest, + ): Promise; } -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; - }; -type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; - } - | AsyncResponse; -declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; +type AiImageClassificationInput = { + image: number[]; +}; +type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; } -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = - | string - | { - /** - * The input text prompt for the model to generate a response. - */ - prompt?: string; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - image: number[] | (string & NonNullable); - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - }; -interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string; +type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; } -declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { - inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; - postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; +type AiImageTextToTextInput = { + image: string; + prompt?: string; + max_tokens?: number; + temperature?: number; + ignore_eos?: boolean; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageTextToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageTextToText { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } -type Ai_Cf_Openai_Whisper_Tiny_En_Input = - | string - | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; - }; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { - /** - * The transcription - */ - text: string; - word_count?: number; +type AiMultimodalEmbeddingsInput = { + image: string; + text: string[]; +}; +type AiIMultimodalEmbeddingsOutput = { + data: number[][]; + shape: number[]; +}; +declare abstract class BaseAiMultimodalEmbeddings { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiObjectDetectionInput = { + image: number[]; +}; +type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +type AiAutomaticSpeechRecognitionInput = { + audio: number[]; +}; +type AiAutomaticSpeechRecognitionOutput = { + text?: string; words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; + word: string; + start: number; + end: number; }[]; vtt?: string; +}; +declare abstract class BaseAiAutomaticSpeechRecognition { + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; } -declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - /** - * Base64 encoded value of the audio data. - */ - audio: string; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string; - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * Preprocess the audio with a voice activity detection model. - */ - vad_filter?: boolean; - /** - * A text prompt to help provide context to the model on the contents of the audio. - */ - initial_prompt?: string; - /** - * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. - */ - prefix?: string; +type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; } -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. - */ - language_probability?: number; - /** - * The total duration of the original audio file, in seconds. - */ - duration?: number; - /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. - */ - duration_after_vad?: number; - }; - /** - * The complete transcription of the audio. - */ +type AiTextClassificationInput = { text: string; - /** - * The total number of words in the transcription. - */ - word_count?: number; - segments?: { - /** - * The starting time of the segment within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the segment within the audio, in seconds. - */ - end?: number; - /** - * The transcription of the segment. - */ - text?: string; - /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. - */ - temperature?: number; - /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. - */ - avg_logprob?: number; - /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. - */ - compression_ratio?: number; - /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. - */ - no_speech_prob?: number; - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string; - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number; - }[]; - }[]; - /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. - */ - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; -} -type Ai_Cf_Baai_Bge_M3_Input = - | BGEM3InputQueryAndContexts - | BGEM3InputEmbedding - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; - }; -interface BGEM3InputQueryAndContexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface BGEM3InputEmbedding { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface BGEM3InputQueryAndContexts1 { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; +}; +type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; } -interface BGEM3InputEmbedding1 { +type AiTextEmbeddingsInput = { text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -type Ai_Cf_Baai_Bge_M3_Output = - | BGEM3OuputQuery - | BGEM3OutputEmbeddingForContexts - | BGEM3OuputEmbedding - | AsyncResponse; -interface BGEM3OuputQuery { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -interface BGEM3OutputEmbeddingForContexts { - response?: number[][]; - shape?: number[]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -interface BGEM3OuputEmbedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * The number of diffusion steps; higher values can improve quality but take longer. - */ - steps?: number; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { - inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +}; +type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; } -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages; -interface Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - image?: number[] | (string & NonNullable); - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ +type RoleScopedChatInput = { + role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); + content: string; + name?: string; +}; +type AiTextGenerationToolLegacyInput = { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; +}; +type AiTextGenerationToolInput = { + type: "function" | (string & NonNullable); + function: { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; + }; +}; +type AiTextGenerationFunctionsInput = { + name: string; + code: string; +}; +type AiTextGenerationResponseFormat = { + type: string; + json_schema?: any; +}; +type AiTextGenerationInput = { + prompt?: string; raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ presence_penalty?: number; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; -} -interface Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { + messages?: RoleScopedChatInput[]; + response_format?: AiTextGenerationResponseFormat; + tools?: + | AiTextGenerationToolInput[] + | AiTextGenerationToolLegacyInput[] + | (object & NonNullable); + functions?: AiTextGenerationFunctionsInput[]; +}; +type AiTextGenerationToolLegacyOutput = { + name: string; + arguments: unknown; +}; +type AiTextGenerationToolOutput = { + id: string; + type: "function"; + function: { name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { - /** - * The generated text response from the model - */ + arguments: string; + }; +}; +type UsageTags = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; +}; +type AiTextGenerationOutput = { response?: string; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; }; -declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { - inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; } -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = - | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt - | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages - | AsyncBatch; -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ +type AiTextToSpeechInput = { prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface JSONMode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; + lang?: string; +}; +type AiTextToSpeechOutput = + | Uint8Array + | { + audio: string; + }; +declare abstract class BaseAiTextToSpeech { + inputs: AiTextToSpeechInput; + postProcessedOutputs: AiTextToSpeechOutput; +} +type AiTextToImageInput = { + prompt: string; + negative_prompt?: string; + height?: number; + width?: number; + image?: number[]; + image_b64?: string; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; + seed?: number; +}; +type AiTextToImageOutput = ReadableStream; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +/** + * Workers AI support for OpenAI's Chat Completions API + */ +type ChatCompletionContentPartText = { + type: "text"; + text: string; +}; +type ChatCompletionContentPartImage = { + type: "image_url"; + image_url: { + url: string; + detail?: "auto" | "low" | "high"; + }; +}; +type ChatCompletionContentPartInputAudio = { + type: "input_audio"; + input_audio: { + /** Base64 encoded audio data. */ + data: string; + format: "wav" | "mp3"; + }; +}; +type ChatCompletionContentPartFile = { + type: "file"; + file: { + /** Base64 encoded file data. */ + file_data?: string; + /** The ID of an uploaded file. */ + file_id?: string; + filename?: string; + }; +}; +type ChatCompletionContentPartRefusal = { + type: "refusal"; + refusal: string; +}; +type ChatCompletionContentPart = + | ChatCompletionContentPartText + | ChatCompletionContentPartImage + | ChatCompletionContentPartInputAudio + | ChatCompletionContentPartFile; +type FunctionDefinition = { + name: string; + description?: string; + parameters?: Record; + strict?: boolean | null; +}; +type ChatCompletionFunctionTool = { + type: "function"; + function: FunctionDefinition; +}; +type ChatCompletionCustomToolGrammarFormat = { + type: "grammar"; + grammar: { + definition: string; + syntax: "lark" | "regex"; + }; +}; +type ChatCompletionCustomToolTextFormat = { + type: "text"; +}; +type ChatCompletionCustomToolFormat = + | ChatCompletionCustomToolTextFormat + | ChatCompletionCustomToolGrammarFormat; +type ChatCompletionCustomTool = { + type: "custom"; + custom: { + name: string; + description?: string; + format?: ChatCompletionCustomToolFormat; + }; +}; +type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool; +type ChatCompletionMessageFunctionToolCall = { + id: string; + type: "function"; + function: { + name: string; + /** JSON-encoded arguments string. */ + arguments: string; + }; +}; +type ChatCompletionMessageCustomToolCall = { + id: string; + type: "custom"; + custom: { + name: string; + input: string; + }; +}; +type ChatCompletionMessageToolCall = + | ChatCompletionMessageFunctionToolCall + | ChatCompletionMessageCustomToolCall; +type ChatCompletionToolChoiceFunction = { + type: "function"; + function: { + name: string; + }; +}; +type ChatCompletionToolChoiceCustom = { + type: "custom"; + custom: { + name: string; + }; +}; +type ChatCompletionToolChoiceAllowedTools = { + type: "allowed_tools"; + allowed_tools: { + mode: "auto" | "required"; + tools: Array>; + }; +}; +type ChatCompletionToolChoiceOption = + | "none" + | "auto" + | "required" + | ChatCompletionToolChoiceFunction + | ChatCompletionToolChoiceCustom + | ChatCompletionToolChoiceAllowedTools; +type DeveloperMessage = { + role: "developer"; + content: + | string + | Array<{ + type: "text"; + text: string; + }>; + name?: string; +}; +type SystemMessage = { + role: "system"; + content: + | string + | Array<{ + type: "text"; + text: string; + }>; + name?: string; +}; +/** + * Permissive merged content part used inside UserMessage arrays. + * + * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination + * inside nested array items does not correctly match different branches for + * different array elements, so the schema uses a single merged object. + */ +type UserMessageContentPart = { + type: "text" | "image_url" | "input_audio" | "file"; + text?: string; + image_url?: { + url?: string; + detail?: "auto" | "low" | "high"; + }; + input_audio?: { + data?: string; + format?: "wav" | "mp3"; + }; + file?: { + file_data?: string; + file_id?: string; + filename?: string; + }; +}; +type UserMessage = { + role: "user"; + content: string | Array; + name?: string; +}; +type AssistantMessageContentPart = { + type: "text" | "refusal"; + text?: string; + refusal?: string; +}; +type AssistantMessage = { + role: "assistant"; + content?: string | null | Array; + refusal?: string | null; + name?: string; + audio?: { + id: string; + }; + tool_calls?: Array; + function_call?: { + name: string; + arguments: string; + }; +}; +type ToolMessage = { + role: "tool"; + content: + | string + | Array<{ + type: "text"; + text: string; + }>; + tool_call_id: string; +}; +type FunctionMessage = { + role: "function"; + content: string; + name: string; +}; +type ChatCompletionMessageParam = + | DeveloperMessage + | SystemMessage + | UserMessage + | AssistantMessage + | ToolMessage + | FunctionMessage; +type ChatCompletionsResponseFormatText = { + type: "text"; +}; +type ChatCompletionsResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatJSONSchema = { + type: "json_schema"; + json_schema: { + name: string; + description?: string; + schema?: Record; + strict?: boolean | null; + }; +}; +type ResponseFormat = + | ChatCompletionsResponseFormatText + | ChatCompletionsResponseFormatJSONObject + | ResponseFormatJSONSchema; +type ChatCompletionsStreamOptions = { + include_usage?: boolean; + include_obfuscation?: boolean; +}; +type PredictionContent = { + type: "content"; + content: + | string + | Array<{ + type: "text"; + text: string; + }>; +}; +type AudioParams = { + voice: + | string + | { + id: string; + }; + format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; +}; +type WebSearchUserLocation = { + type: "approximate"; + approximate: { + city?: string; + country?: string; + region?: string; + timezone?: string; + }; +}; +type WebSearchOptions = { + search_context_size?: "low" | "medium" | "high"; + user_location?: WebSearchUserLocation; +}; +type ChatTemplateKwargs = { + /** Whether to enable reasoning, enabled by default. */ + enable_thinking?: boolean; + /** If false, preserves reasoning context between turns. */ + clear_thinking?: boolean; +}; +/** Shared optional properties used by both Prompt and Messages input branches. */ +type ChatCompletionsCommonOptions = { + model?: string; + audio?: AudioParams; + frequency_penalty?: number | null; + logit_bias?: Record | null; + logprobs?: boolean | null; + top_logprobs?: number | null; + max_tokens?: number | null; + max_completion_tokens?: number | null; + metadata?: Record | null; + modalities?: Array<"text" | "audio"> | null; + n?: number | null; + parallel_tool_calls?: boolean; + prediction?: PredictionContent; + presence_penalty?: number | null; + reasoning_effort?: "low" | "medium" | "high" | null; + chat_template_kwargs?: ChatTemplateKwargs; + response_format?: ResponseFormat; + seed?: number | null; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stop?: string | Array | null; + store?: boolean | null; + stream?: boolean | null; + stream_options?: ChatCompletionsStreamOptions; + temperature?: number | null; + tool_choice?: ChatCompletionToolChoiceOption; + tools?: Array; + top_p?: number | null; + user?: string; + web_search_options?: WebSearchOptions; + function_call?: + | "none" + | "auto" + | { + name: string; + }; + functions?: Array; +}; +type PromptTokensDetails = { + cached_tokens?: number; + audio_tokens?: number; +}; +type CompletionTokensDetails = { + reasoning_tokens?: number; + audio_tokens?: number; + accepted_prediction_tokens?: number; + rejected_prediction_tokens?: number; +}; +type CompletionUsage = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + prompt_tokens_details?: PromptTokensDetails; + completion_tokens_details?: CompletionTokensDetails; +}; +type ChatCompletionTopLogprob = { + token: string; + logprob: number; + bytes: Array | null; +}; +type ChatCompletionTokenLogprob = { + token: string; + logprob: number; + bytes: Array | null; + top_logprobs: Array; +}; +type ChatCompletionAudio = { + id: string; + /** Base64 encoded audio bytes. */ + data: string; + expires_at: number; + transcript: string; +}; +type ChatCompletionUrlCitation = { + type: "url_citation"; + url_citation: { + url: string; + title: string; + start_index: number; + end_index: number; + }; +}; +type ChatCompletionResponseMessage = { + role: "assistant"; + content: string | null; + refusal: string | null; + annotations?: Array; + audio?: ChatCompletionAudio; + tool_calls?: Array; + function_call?: { + name: string; + arguments: string; + } | null; +}; +type ChatCompletionLogprobs = { + content: Array | null; + refusal?: Array | null; +}; +type ChatCompletionChoice = { + index: number; + message: ChatCompletionResponseMessage; + finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; + logprobs: ChatCompletionLogprobs | null; +}; +type ChatCompletionsMessagesInput = { + messages: Array; +} & ChatCompletionsCommonOptions; +type ChatCompletionsOutput = { + id: string; + object: string; + created: number; + model: string; + choices: Array; + usage?: CompletionUsage; + system_fingerprint?: string | null; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; +}; +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: "max_output_tokens" | "content_filter"; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = + | ResponseInputText + | ResponseInputImage + | ResponseOutputText + | ResponseOutputRefusal + | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: "reasoning_text"; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: "response.created"; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; +}; +type ResponseError = { + code: + | "server_error" + | "rate_limit_exceeded" + | "invalid_prompt" + | "vector_store_timeout" + | "invalid_image" + | "invalid_image_format" + | "invalid_base64_image" + | "invalid_image_url" + | "image_too_large" + | "image_too_small" + | "image_parse_error" + | "image_content_policy_violation" + | "invalid_image_mode" + | "image_file_too_large" + | "unsupported_image_media_type" + | "empty_image_file" + | "failed_to_download_image" + | "image_file_not_found"; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: "response.failed"; +}; +type ResponseFormatText = { + type: "text"; +}; +type ResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatTextConfig = + | ResponseFormatText + | ResponseFormatTextJSONSchemaConfig + | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; } -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: "response.incomplete"; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: "low" | "high" | "auto"; + type: "input_image"; /** - * An array of message objects representing the conversation history. + * Base64 encoded image */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; + image_url?: string | null; +}; +type ResponseInputImageContent = { + type: "input_image"; + detail?: "low" | "high" | "auto" | null; /** - * A list of tools available for the assistant to use. + * Base64 encoded image */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. + image_url?: string | null; +}; +type ResponseInputItem = + | EasyInputMessage + | ResponseInputItemMessage + | ResponseOutputMessage + | ResponseFunctionToolCall + | ResponseInputItemFunctionCallOutput + | ResponseReasoningItem; +type ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputText = { + text: string; + type: "input_text"; +}; +type ResponseInputTextContent = { + text: string; + type: "input_text"; +}; +type ResponseItem = + | ResponseInputMessageItem + | ResponseOutputMessage + | ResponseFunctionToolCallItem + | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; +}; +type ResponseOutputRefusal = { + refusal: string; + type: "refusal"; +}; +type ResponseOutputText = { + text: string; + type: "output_text"; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: "summary_text"; +}; +type ResponseReasoningContentItem = { + text: string; + type: "reasoning_text"; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = + | "completed" + | "failed" + | "in_progress" + | "cancelled" + | "queued" + | "incomplete"; +type ResponseStreamEvent = + | ResponseCompletedEvent + | ResponseCreatedEvent + | ResponseErrorEvent + | ResponseFunctionCallArgumentsDeltaEvent + | ResponseFunctionCallArgumentsDoneEvent + | ResponseFailedEvent + | ResponseIncompleteEvent + | ResponseOutputItemAddedEvent + | ResponseOutputItemDoneEvent + | ResponseReasoningTextDeltaEvent + | ResponseReasoningTextDoneEvent + | ResponseRefusalDeltaEvent + | ResponseRefusalDoneEvent + | ResponseTextDeltaEvent + | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: "response.completed"; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: "function"; +}; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; +/** Marks keys from T that aren't in U as optional never */ +type Without = { + [P in Exclude]?: never; +}; +/** Either T or U, but not both (mutually exclusive) */ +type XOR = (T & Without) | (U & Without); +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = + | { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; + pooling?: "mean" | "cls"; + }[]; + }; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = + | { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; + } + | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * The async request id that can be used to obtain the results. */ - frequency_penalty?: number; + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; +} +type Ai_Cf_Openai_Whisper_Input = + | string + | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; + }; +interface Ai_Cf_Openai_Whisper_Output { /** - * Increases the likelihood of the model introducing new topics. + * The transcription */ - presence_penalty?: number; -} -interface AsyncBatch { - requests?: { - /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. - */ - external_reference?: string; - /** - * Prompt for the text generation model - */ - prompt?: string; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; + text: string; + word_count?: number; + words?: { + word?: string; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * The second this word begins in the recording */ - frequency_penalty?: number; + start?: number; /** - * Increases the likelihood of the model introducing new topics. + * The ending second when the word completes */ - presence_penalty?: number; - response_format?: JSONMode; + end?: number; }[]; + vtt?: string; } -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = +declare abstract class Base_Ai_Cf_Openai_Whisper { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +type Ai_Cf_Meta_M2M100_1_2B_Input = | { /** - * The generated text response from the model + * The text to be translated */ - response: string; + text: string; /** - * Usage statistics for the inference request + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified */ - usage?: { + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { /** - * Total number of tokens in input + * The text to be translated */ - prompt_tokens?: number; + text: string; /** - * Total number of tokens in output + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified */ - completion_tokens?: number; + source_lang?: string; /** - * Total number of input and output tokens + * The language code to translate the text into (e.g., 'es' for Spanish) */ - total_tokens?: number; - }; + target_lang: string; + }[]; + }; +type Ai_Cf_Meta_M2M100_1_2B_Output = + | { /** - * An array of tool calls requests made during the response generation + * The translated text in the target language */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request + translated_text?: string; + } + | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { + inputs: Ai_Cf_Meta_M2M100_1_2B_Input; + postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; +} +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = + | { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - arguments?: object; + pooling?: "mean" | "cls"; + }[]; + }; +type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = + | { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; + } + | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; +} +type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = + | { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; /** - * The name of the tool to be called + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - name?: string; + pooling?: "mean" | "cls"; }[]; + }; +type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = + | { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; } - | AsyncResponse; -declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; + | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; } -interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { +declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; +} +type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = + | string + | { + /** + * The input text prompt for the model to generate a response. + */ + prompt?: string; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + image: number[] | (string & NonNullable); + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + }; +interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { + description?: string; +} +declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; +} +type Ai_Cf_Openai_Whisper_Tiny_En_Input = + | string + | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; + }; +interface Ai_Cf_Openai_Whisper_Tiny_En_Output { /** - * An array of message objects representing the conversation history. + * The transcription */ - messages: { + text: string; + word_count?: number; + words?: { + word?: string; /** - * The role of the message sender must alternate between 'user' and 'assistant'. + * The second this word begins in the recording */ - role: "user" | "assistant"; + start?: number; /** - * The content of the message as a string. + * The ending second when the word completes */ - content: string; + end?: number; }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { + audio: + | string + | { + body?: object; + contentType?: string; + }; /** - * The maximum number of tokens to generate in the response. + * Supported tasks are 'translate' or 'transcribe'. */ - max_tokens?: number; + task?: string; /** - * Controls the randomness of the output; higher values produce more random results. + * The language of the audio being transcribed or translated. */ - temperature?: number; + language?: string; /** - * Dictate the output format of the generated response. + * Preprocess the audio with a voice activity detection model. */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: - | string - | { - /** - * Whether the conversation is safe or not. - */ - safe?: boolean; - /** - * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. - */ - categories?: string[]; - }; + vad_filter?: boolean; /** - * Usage statistics for the inference request + * A text prompt to help provide context to the model on the contents of the audio. */ - usage?: { + initial_prompt?: string; + /** + * The prefix appended to the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string; + /** + * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed. + */ + beam_size?: number; + /** + * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops. + */ + condition_on_previous_text?: boolean; + /** + * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped. + */ + no_speech_threshold?: number; + /** + * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text. + */ + compression_ratio_threshold?: number; + /** + * Threshold for filtering out segments with low average log probability, indicating low confidence. + */ + log_prob_threshold?: number; + /** + * Optional threshold (in seconds) to skip silent periods that may cause hallucinations. + */ + hallucination_silence_threshold?: number; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { /** - * Total number of tokens in input + * The language of the audio being transcribed or translated. */ - prompt_tokens?: number; + language?: string; /** - * Total number of tokens in output + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. */ - completion_tokens?: number; + language_probability?: number; /** - * Total number of input and output tokens + * The total duration of the original audio file, in seconds. */ - total_tokens?: number; + duration?: number; + /** + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. + */ + duration_after_vad?: number; }; -} -declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Input { /** - * A query you wish to perform against the provided contexts. + * The complete transcription of the audio. */ - query: string; + text: string; /** - * Number of returned results starting with the best score. + * The total number of words in the transcription. */ - top_k?: number; + word_count?: number; + segments?: { + /** + * The starting time of the segment within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the segment within the audio, in seconds. + */ + end?: number; + /** + * The transcription of the segment. + */ + text?: string; + /** + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + */ + temperature?: number; + /** + * The average log probability of the predictions for the words in this segment, indicating overall confidence. + */ + avg_logprob?: number; + /** + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + */ + compression_ratio?: number; + /** + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + */ + no_speech_prob?: number; + words?: { + /** + * The individual word transcribed from the audio. + */ + word?: string; + /** + * The starting time of the word within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the word within the audio, in seconds. + */ + end?: number; + }[]; + }[]; + /** + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + */ + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { + inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; +} +type Ai_Cf_Baai_Bge_M3_Input = + | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts + | Ai_Cf_Baai_Bge_M3_Input_Embedding + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: ( + | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 + | Ai_Cf_Baai_Bge_M3_Input_Embedding_1 + )[]; + }; +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; /** * List of provided contexts. Note that the index in this array is important, as the response will refer to it. */ @@ -4253,8 +6451,50 @@ interface Ai_Cf_Baai_Bge_Reranker_Base_Input { */ text?: string; }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; } -interface Ai_Cf_Baai_Bge_Reranker_Base_Output { +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +type Ai_Cf_Baai_Bge_M3_Output = + | Ai_Cf_Baai_Bge_M3_Output_Query + | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts + | Ai_Cf_Baai_Bge_M3_Output_Embedding + | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Output_Query { response?: { /** * Index of the context in the request @@ -4266,23 +6506,64 @@ interface Ai_Cf_Baai_Bge_Reranker_Base_Output { score?: number; }[]; } -declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { - inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = - | Qwen2_5_Coder_32B_Instruct_Prompt - | Qwen2_5_Coder_32B_Instruct_Messages; -interface Qwen2_5_Coder_32B_Instruct_Prompt { +interface Ai_Cf_Baai_Bge_M3_Output_Embedding { + shape?: number[]; /** - * The input text prompt for the model to generate a response. + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_M3 { + inputs: Ai_Cf_Baai_Bge_M3_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { + /** + * A text description of the image you want to generate. */ prompt: string; /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + * The number of diffusion steps; higher values can improve quality but take longer. */ - lora?: string; - response_format?: JSONMode; + steps?: number; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = + | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt + | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + image?: number[] | (string & NonNullable); /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4323,8 +6604,12 @@ interface Qwen2_5_Coder_32B_Instruct_Prompt { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; } -interface Qwen2_5_Coder_32B_Instruct_Messages { +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4332,12 +6617,41 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - role: string; + role?: string; /** - * The content of the message as a string. + * The tool call id. If you don't know what to put here you can fall back to 000000001 */ - content: string; + tool_call_id?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; }[]; + image?: number[] | (string & NonNullable); functions?: { name: string; code: string; @@ -4432,13 +6746,8 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { }; } )[]; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * If true, the response will be streamed back incrementally. */ stream?: boolean; /** @@ -4450,7 +6759,7 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { */ temperature?: number; /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number; /** @@ -4474,28 +6783,11 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { */ presence_penalty?: number; } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { /** * The generated text response from the model */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; + response?: string; /** * An array of tool calls requests made during the response generation */ @@ -4510,20 +6802,24 @@ type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { name?: string; }[]; }; -declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; +declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { + inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; } -type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; -interface Qwen_Qwq_32B_Prompt { +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = + | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt + | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages + | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string; /** - * JSON schema that should be fulfilled for the response. + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ - guided_json?: object; + lora?: string; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4565,7 +6861,11 @@ interface Qwen_Qwq_32B_Prompt { */ presence_penalty?: number; } -interface Qwen_Qwq_32B_Messages { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { /** * An array of message objects representing the conversation history. */ @@ -4573,39 +6873,19 @@ interface Qwen_Qwq_32B_Messages { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: + role: string; + content: | string | { /** - * Type of the content provided + * Type of the content (text) */ type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { /** - * Type of the content provided + * Text content */ - type?: string; text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; + }[]; }[]; functions?: { name: string; @@ -4701,10 +6981,7 @@ interface Qwen_Qwq_32B_Messages { }; } )[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4746,11 +7023,153 @@ interface Qwen_Qwq_32B_Messages { */ presence_penalty?: number; } -type Ai_Cf_Qwen_Qwq_32B_Output = { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { + requests?: { + /** + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + */ + external_reference?: string; + /** + * Prompt for the text generation model + */ + prompt?: string; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; + }[]; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = + | { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; + } + | string + | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { /** - * The generated text response from the model + * The async request id that can be used to obtain the results. */ - response: string; + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender must alternate between 'user' and 'assistant'. + */ + role: "user" | "assistant"; + /** + * The content of the message as a string. + */ + content: string; + }[]; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Dictate the output format of the generated response. + */ + response_format?: { + /** + * Set to json_object to process and output generated text as JSON. + */ + type?: string; + }; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { + response?: + | string + | { + /** + * Whether the conversation is safe or not. + */ + safe?: boolean; + /** + * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. + */ + categories?: string[]; + }; /** * Usage statistics for the inference request */ @@ -4768,36 +7187,58 @@ type Ai_Cf_Qwen_Qwq_32B_Output = { */ total_tokens?: number; }; +} +declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Input { /** - * An array of tool calls requests made during the response generation + * A query you wish to perform against the provided contexts. */ - tool_calls?: { + /** + * Number of returned results starting with the best score. + */ + top_k?: number; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { /** - * The arguments passed to be passed to the tool call request + * One of the provided context content */ - arguments?: object; + text?: string; + }[]; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Output { + response?: { /** - * The name of the tool to be called + * Index of the context in the request */ - name?: string; + id?: number; + /** + * Score of the context under the index. + */ + score?: number; }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = - | Mistral_Small_3_1_24B_Instruct_Prompt - | Mistral_Small_3_1_24B_Instruct_Messages; -interface Mistral_Small_3_1_24B_Instruct_Prompt { +declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = + | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt + | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string; /** - * JSON schema that should be fulfilled for the response. + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ - guided_json?: object; + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4839,7 +7280,11 @@ interface Mistral_Small_3_1_24B_Instruct_Prompt { */ presence_penalty?: number; } -interface Mistral_Small_3_1_24B_Instruct_Messages { +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4847,39 +7292,11 @@ interface Mistral_Small_3_1_24B_Instruct_Messages { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - role?: string; + role: string; /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + * The content of the message as a string. */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; + content: string; }[]; functions?: { name: string; @@ -4975,10 +7392,7 @@ interface Mistral_Small_3_1_24B_Instruct_Messages { }; } )[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5020,7 +7434,11 @@ interface Mistral_Small_3_1_24B_Instruct_Messages { */ presence_penalty?: number; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { /** * The generated text response from the model */ @@ -5056,20 +7474,18 @@ type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { name?: string; }[]; }; -declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; +declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; } -type Ai_Cf_Google_Gemma_3_12B_It_Input = - | Google_Gemma_3_12B_It_Prompt - | Google_Gemma_3_12B_It_Messages; -interface Google_Gemma_3_12B_It_Prompt { +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5113,7 +7529,7 @@ interface Google_Gemma_3_12B_It_Prompt { */ presence_penalty?: number; } -interface Google_Gemma_3_12B_It_Messages { +interface Ai_Cf_Qwen_Qwq_32B_Messages { /** * An array of message objects representing the conversation history. */ @@ -5122,7 +7538,11 @@ interface Google_Gemma_3_12B_It_Messages { * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role?: string; - content?: + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: | string | { /** @@ -5290,7 +7710,7 @@ interface Google_Gemma_3_12B_It_Messages { */ presence_penalty?: number; } -type Ai_Cf_Google_Gemma_3_12B_It_Output = { +type Ai_Cf_Qwen_Qwq_32B_Output = { /** * The generated text response from the model */ @@ -5326,14 +7746,14 @@ type Ai_Cf_Google_Gemma_3_12B_It_Output = { name?: string; }[]; }; -declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = - | Ai_Cf_Meta_Llama_4_Prompt - | Ai_Cf_Meta_Llama_4_Messages; -interface Ai_Cf_Meta_Llama_4_Prompt { +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = + | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt + | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5342,7 +7762,6 @@ interface Ai_Cf_Meta_Llama_4_Prompt { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: JSONMode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5384,7 +7803,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages { +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5394,7 +7813,7 @@ interface Ai_Cf_Meta_Llama_4_Messages { */ role?: string; /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 */ tool_call_id?: string; content?: @@ -5520,7 +7939,6 @@ interface Ai_Cf_Meta_Llama_4_Messages { }; } )[]; - response_format?: JSONMode; /** * JSON schema that should be fufilled for the response. */ @@ -5566,7 +7984,7 @@ interface Ai_Cf_Meta_Llama_4_Messages { */ presence_penalty?: number; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { /** * The generated text response from the model */ @@ -5593,2150 +8011,7328 @@ type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { */ tool_calls?: { /** - * The tool call id. - */ - id?: string; - /** - * Specifies the type of tool (e.g., 'function'). + * The arguments passed to be passed to the tool call request */ - type?: string; + arguments?: object; /** - * Details of the function tool. + * The name of the tool to be called */ - function?: { - /** - * The name of the tool to be called - */ - name?: string; - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - }; + name?: string; }[]; }; -declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { - inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; +declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { + inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; } -interface AiModels { - "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; - "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; - "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; - "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; - "@cf/myshell-ai/melotts": BaseAiTextToSpeech; - "@cf/microsoft/resnet-50": BaseAiImageClassification; - "@cf/facebook/detr-resnet-50": BaseAiObjectDetection; - "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; - "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; - "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; - "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; - "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; - "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; - "@hf/thebloke/llamaguard-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; - "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; - "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; - "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; - "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; - "@cf/microsoft/phi-2": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; - "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; - "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; - "@hf/google/gemma-7b-it": BaseAiTextGeneration; - "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; - "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; - "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; - "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; - "@cf/facebook/bart-large-cnn": BaseAiSummarization; - "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; - "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; - "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; - "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; - "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; - "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; - "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; - "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; - "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; - "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; - "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; - "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; - "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; - "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; - "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; - "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; - "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; - "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; - "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; - "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; +type Ai_Cf_Google_Gemma_3_12B_It_Input = + | Ai_Cf_Google_Gemma_3_12B_It_Prompt + | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -type AiOptions = { +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api + * An array of message objects representing the conversation history. */ - queueRequest?: boolean; - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; -}; -type ConversionResponse = { - name: string; - mimeType: string; - format: "markdown"; - tokens: number; - data: string; -}; -type AiModelsSearchParams = { - author?: string; - hide_experimental?: boolean; - page?: number; - per_page?: number; - search?: string; - source?: number; - task?: string; -}; -type AiModelsSearchObject = { - id: string; - source: number; - name: string; - description: string; - task: { - id: string; + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[]; + }[]; + functions?: { name: string; - description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; + code: string; }[]; -}; -interface InferenceUpstreamError extends Error {} -interface AiInternalError extends Error {} -type AiModelListType = Record; -declare abstract class Ai { - aiGatewayLogId: string | null; - gateway(gatewayId: string): AiGateway; - autorag(autoragId?: string): AutoRAG; - run< - Name extends keyof AiModelList, - Options extends AiOptions, - InputOptions extends AiModelList[Name]["inputs"], - >( - model: Name, - inputs: InputOptions, - options?: Options, - ): Promise< - Options extends { - returnRawResponse: true; - } - ? Response - : InputOptions extends { - stream: true; - } - ? ReadableStream - : AiModelList[Name]["postProcessedOutputs"] - >; - models(params?: AiModelsSearchParams): Promise; - toMarkdown( - files: { - name: string; - blob: Blob; - }[], - options?: { - gateway?: GatewayOptions; - extraHeaders?: object; - }, - ): Promise; - toMarkdown( - files: { - name: string; - blob: Blob; - }, - options?: { - gateway?: GatewayOptions; - extraHeaders?: object; - }, - ): Promise; -} -type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5; - retryDelayMs?: number; - backoff?: "constant" | "linear" | "exponential"; -}; -type GatewayOptions = { - id: string; - cacheKey?: string; - cacheTtl?: number; - skipCache?: boolean; - metadata?: Record; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; -type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | null; -}; -type AiGatewayLog = { - id: string; - provider: string; - model: string; - model_type?: string; - path: string; - duration: number; - request_type?: string; - request_content_type?: string; - status_code: number; - response_content_type?: string; - success: boolean; - cached: boolean; - tokens_in?: number; - tokens_out?: number; - metadata?: Record; - step?: number; - cost?: number; - custom_cost?: boolean; - request_size: number; - request_head?: string; - request_head_complete: boolean; - response_size: number; - response_head?: string; - response_head_complete: boolean; - created_at: Date; -}; -type AIGatewayProviders = - | "workers-ai" - | "anthropic" - | "aws-bedrock" - | "azure-openai" - | "google-vertex-ai" - | "huggingface" - | "openai" - | "perplexity-ai" - | "replicate" - | "groq" - | "cohere" - | "google-ai-studio" - | "mistral" - | "grok" - | "openrouter" - | "deepseek" - | "cerebras" - | "cartesia" - | "elevenlabs" - | "adobe-firefly"; -type AIGatewayHeaders = { - "cf-aig-metadata": Record | string; - "cf-aig-custom-cost": + /** + * A list of tools available for the assistant to use. + */ + tools?: ( | { - per_token_in?: number; - per_token_out?: number; + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; } | { - total_cost?: number; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; } - | string; - "cf-aig-cache-ttl": number | string; - "cf-aig-skip-cache": boolean | string; - "cf-aig-cache-key": string; - "cf-aig-event-id": string; - "cf-aig-request-timeout": number | string; - "cf-aig-max-attempts": number | string; - "cf-aig-retry-delay": number | string; - "cf-aig-backoff": string; - "cf-aig-collect-log": boolean | string; - Authorization: string; - "Content-Type": string; - [key: string]: string | number | boolean | object; -}; -type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string; // eslint-disable-line - endpoint: string; - headers: Partial; - query: unknown; -}; -interface AiGatewayInternalError extends Error {} -interface AiGatewayLogNotFound extends Error {} -declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run( - data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], - options?: { - gateway?: GatewayOptions; - extraHeaders?: object; - }, - ): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line -} -interface AutoRAGInternalError extends Error {} -interface AutoRAGNotFoundError extends Error {} -interface AutoRAGUnauthorizedError extends Error {} -interface AutoRAGNameNotSetError extends Error {} -type ComparisonFilter = { - key: string; - type: "eq" | "ne" | "gt" | "gte" | "lt" | "lte"; - value: string | number | boolean; -}; -type CompoundFilter = { - type: "and" | "or"; - filters: ComparisonFilter[]; -}; -type AutoRagSearchRequest = { - query: string; - filters?: CompoundFilter | ComparisonFilter; - max_num_results?: number; - ranking_options?: { - ranker?: string; - score_threshold?: number; - }; - rewrite_query?: boolean; -}; -type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; -}; -type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; -}; -type AutoRagSearchResponse = { - object: "vector_store.search_results.page"; - search_query: string; - data: { - file_id: string; - filename: string; - score: number; - attributes: Record; - content: { - type: "text"; - text: string; - }[]; - }[]; - has_more: boolean; - next_page: string | null; -}; -type AutoRagListResponse = { - id: string; - enable: boolean; - type: string; - source: string; - vectorize_name: string; - paused: boolean; - status: string; -}[]; -type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; -}; -declare abstract class AutoRAG { - list(): Promise; - search(params: AutoRagSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; -} -interface BasicImageTransformations { + )[]; /** - * Maximum width in image pixels. The value must be an integer. + * JSON schema that should be fufilled for the response. */ - width?: number; + guided_json?: object; /** - * Maximum height in image pixels. The value must be an integer. + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - height?: number; + raw?: boolean; /** - * 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. - * - squeeze: Stretches and deforms to the width and height given, even if it - * breaks aspect ratio + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; + stream?: boolean; /** - * 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. + * The maximum number of tokens to generate in the response. */ - gravity?: - | "left" - | "right" - | "top" - | "bottom" - | "center" - | "auto" - | "entropy" - | BasicImageTransformationsGravityCoordinates; + max_tokens?: number; /** - * Background color to add underneath the image. Applies only to images with - * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), - * hsl(…), etc.) + * Controls the randomness of the output; higher values produce more random results. */ - background?: string; + temperature?: number; /** - * Number of degrees (90, 180, 270) to rotate the image by. width and height - * options refer to axes after rotation. + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - rotate?: 0 | 90 | 180 | 270 | 360; -} -interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: "remainder" | "box-center"; -} -/** - * 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. - */ -interface RequestInitCfProperties extends Record { - cacheEverything?: boolean; + top_p?: number; /** - * 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. + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - cacheKey?: string; + top_k?: number; /** - * 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. + * Random seed for reproducibility of the generation. */ - cacheTags?: string[]; + seed?: number; /** - * Force response to be cached for a given number of seconds. (e.g. 300) + * Penalty for repeated tokens; higher values discourage repetition. */ - cacheTtl?: number; + repetition_penalty?: 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 }) + * Decreases the likelihood of the model repeating the same lines verbatim. */ - cacheTtlByStatus?: Record; - scrapeShield?: boolean; - apps?: boolean; - image?: RequestInitCfPropertiesImage; - minify?: RequestInitCfPropertiesImageMinify; - mirage?: boolean; - polish?: "lossy" | "lossless" | "off"; - r2?: RequestInitCfPropertiesR2; + frequency_penalty?: number; /** - * 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. + * Increases the likelihood of the model introducing new topics. */ - resolveOverride?: string; + presence_penalty?: number; } -interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { +type Ai_Cf_Google_Gemma_3_12B_It_Output = { /** - * 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. + * The generated text response from the model */ - url: string; + response: string; /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. + * Usage statistics for the inference request */ - opacity?: number; + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: 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). + * An array of tool calls requests made during the response generation */ - repeat?: true | "x" | "y"; + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { + inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; + postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { /** - * 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. + * The input text prompt for the model to generate a response. */ - top?: number; - left?: number; - bottom?: number; - right?: number; -} -interface RequestInitCfPropertiesImage extends BasicImageTransformations { + prompt: string; /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . + * JSON schema that should be fulfilled for the response. */ - dpr?: number; + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * Allows you to trim your image. Takes dpr into account and is performed before - * resizing or rotation. - * - * It can be used as: - * - left, top, right, bottom - it will specify the number of pixels to cut - * off each side - * - width, height - the width/height you'd like to end up with - can be used - * in combination with the properties above - * - border - this will automatically trim the surroundings of an image based on - * it's color. It consists of three properties: - * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) - * - tolerance: difference from color to treat as color - * - keep: the number of pixels of border to keep + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - trim?: - | "border" - | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: - | boolean - | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; + raw?: boolean; /** - * 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. + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - quality?: number | "low" | "medium-low" | "medium-high" | "high"; + stream?: boolean; /** - * 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. + * The maximum number of tokens to generate in the response. */ - format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; + max_tokens?: number; /** - * 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. + * Controls the randomness of the output; higher values produce more random results. */ - anim?: boolean; + temperature?: number; /** - * 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. + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - metadata?: "keep" | "copyright" | "none"; + top_p?: number; /** - * 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. + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - sharpen?: number; + top_k?: number; /** - * Radius of a blur filter (approximate gaussian). Maximum supported radius - * is 250. + * Random seed for reproducibility of the generation. */ - blur?: number; + seed?: number; /** - * Overlays are drawn in the order they appear in the array (last array - * entry is the topmost layer). + * Penalty for repeated tokens; higher values discourage repetition. */ - draw?: RequestInitCfPropertiesImageDraw[]; + repetition_penalty?: number; /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * the origin. + * Decreases the likelihood of the model repeating the same lines verbatim. */ - "origin-auth"?: "share-publicly"; + frequency_penalty?: number; /** - * 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. + * Increases the likelihood of the model introducing new topics. */ - border?: + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( | { - color: string; - width: number; + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; } | { - color: string; - top: number; - right: number; - bottom: number; - left: number; - }; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * 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. + * JSON schema that should be fufilled for the response. */ - brightness?: number; + guided_json?: object; /** - * 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. + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - contrast?: number; + raw?: boolean; /** - * 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. + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - gamma?: number; + stream?: boolean; /** - * 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. + * The maximum number of tokens to generate in the response. */ - saturation?: number; + max_tokens?: number; /** - * Flips the images horizontally, vertically, or both. Flipping is applied before - * rotation, so if you apply flip=h,rotate=90 then the image will be flipped - * horizontally, then rotated by 90 degrees. + * Controls the randomness of the output; higher values produce more random results. */ - flip?: "h" | "v" | "hv"; + temperature?: 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. + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - compression?: "fast"; -} -interface RequestInitCfPropertiesImageMinify { - javascript?: boolean; - css?: boolean; - html?: boolean; -} -interface RequestInitCfPropertiesR2 { + top_p?: number; /** - * Colo id of bucket that an object is stored in + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - bucketColoId?: number; -} -/** - * Request metadata provided by Cloudflare's edge. - */ -type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & - IncomingRequestCfPropertiesBotManagementEnterprise & - IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & - IncomingRequestCfPropertiesGeographicInformation & - IncomingRequestCfPropertiesCloudflareAccessOrApiShield; -interface IncomingRequestCfPropertiesBase extends Record { + top_k?: number; /** - * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. - * - * @example 395747 + * Random seed for reproducibility of the generation. */ - asn?: number; + seed?: number; /** - * The organization which owns the ASN of the incoming request. - * - * @example "Google Cloud" + * Penalty for repeated tokens; higher values discourage repetition. */ - asOrganization?: string; + repetition_penalty?: number; /** - * The original value of the `Accept-Encoding` header if Cloudflare modified it. - * - * @example "gzip, deflate, br" + * Decreases the likelihood of the model repeating the same lines verbatim. */ - clientAcceptEncoding?: string; + frequency_penalty?: number; /** - * The number of milliseconds it took for the request to reach your worker. - * - * @example 22 + * Increases the likelihood of the model introducing new topics. */ - clientTcpRtt?: number; + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: ( + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner + )[]; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { /** - * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) - * airport code of the data center that the request hit. - * - * @example "DFW" + * The input text prompt for the model to generate a response. */ - colo: string; + prompt: 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 + * JSON schema that should be fulfilled for the response. */ - edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * The HTTP Protocol the request used. - * - * @example "HTTP/2" + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - httpProtocol: string; + raw?: boolean; /** - * 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 "" + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - requestPriority: string; + stream?: boolean; /** - * The TLS version of the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "TLSv1.3" + * The maximum number of tokens to generate in the response. */ - tlsVersion: string; + max_tokens?: number; /** - * 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" + * Controls the randomness of the output; higher values produce more random results. */ - tlsCipher: string; + temperature?: number; /** - * 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. + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; -} -interface IncomingRequestCfPropertiesBotManagementBase { + top_p?: number; /** - * 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 + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - score: number; + top_k?: 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). + * Random seed for reproducibility of the generation. */ - verifiedBot: boolean; + seed?: number; /** - * A boolean value that is true if the request originates from a - * Cloudflare-verified proxy service. + * Penalty for repeated tokens; higher values discourage repetition. */ - corporateProxy: boolean; + repetition_penalty?: number; /** - * 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. + * Decreases the likelihood of the model repeating the same lines verbatim. */ - staticResource: boolean; + frequency_penalty?: number; /** - * 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). + * Increases the likelihood of the model introducing new topics. */ - detectionIds: number[]; + presence_penalty?: number; } -interface IncomingRequestCfPropertiesBotManagement { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { /** - * Results of Cloudflare's Bot Management analysis + * An array of message objects representing the conversation history. */ - botManagement: IncomingRequestCfPropertiesBotManagementBase; + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * Duplicate of `botManagement.score`. - * - * @deprecated + * A list of tools available for the assistant to use. */ - clientTrustScore: number; -} -interface IncomingRequestCfPropertiesBotManagementEnterprise - extends IncomingRequestCfPropertiesBotManagement { + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * Results of Cloudflare's Bot Management analysis + * JSON schema that should be fufilled for the response. */ - 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; - }; -} -interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { + guided_json?: object; /** - * 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/)). + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - hostMetadata?: HostMetadata; -} -interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + raw?: boolean; /** - * 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). + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - tlsClientAuth: - | IncomingRequestCfPropertiesTLSClientAuth - | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; -} -/** - * Metadata about the request's TLS handshake - */ -interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + stream?: boolean; /** - * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + * The maximum number of tokens to generate in the response. */ - clientHandshake: string; + max_tokens?: number; /** - * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + * Controls the randomness of the output; higher values produce more random results. */ - serverHandshake: string; + temperature?: number; /** - * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - clientFinished: string; + top_p?: number; /** - * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - serverFinished: string; -} -/** - * Geographic data about the request's origin. - */ -interface IncomingRequestCfPropertiesGeographicInformation { + top_k?: number; /** - * 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" + * Random seed for reproducibility of the generation. */ - country?: Iso3166Alpha2Code | "T1"; + seed?: number; /** - * If present, this property indicates that the request originated in the EU - * - * @example "1" + * Penalty for repeated tokens; higher values discourage repetition. */ - isEUCountry?: "1"; + repetition_penalty?: number; /** - * A two-letter code indicating the continent the request originated from. - * - * @example "AN" + * Decreases the likelihood of the model repeating the same lines verbatim. */ - continent?: ContinentCode; + frequency_penalty?: number; /** - * The city the request originated from - * - * @example "Austin" + * Increases the likelihood of the model introducing new topics. */ - city?: string; + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { /** - * Postal code of the incoming request - * - * @example "78701" + * The generated text response from the model */ - postalCode?: string; + response: string; /** - * Latitude of the incoming request - * - * @example "30.27130" + * Usage statistics for the inference request */ - latitude?: string; + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; /** - * Longitude of the incoming request - * - * @example "-97.74260" + * An array of tool calls requests made during the response generation */ - longitude?: string; + tool_calls?: { + /** + * The tool call id. + */ + id?: string; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type?: string; + /** + * Details of the function tool. + */ + function?: { + /** + * The name of the tool to be called + */ + name?: string; + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + }; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { + inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { /** - * Timezone of the incoming request - * - * @example "America/Chicago" + * The input text prompt for the model to generate a response. */ - timezone?: string; + prompt: string; /** - * If known, the ISO 3166-2 name for the first level region associated with - * the IP address of the incoming request - * - * @example "Texas" + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ - region?: string; + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; /** - * If known, the ISO 3166-2 code for the first-level region associated with - * the IP address of the incoming request - * - * @example "TX" + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - regionCode?: string; + raw?: boolean; /** - * Metro code (DMA) of the incoming request - * - * @example "635" + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - metroCode?: string; -} -/** Data about the incoming request's TLS certificate */ -interface IncomingRequestCfPropertiesTLSClientAuth { - /** Always `"1"`, indicating that the certificate was presented */ - certPresented: "1"; + stream?: boolean; /** - * Result of certificate verification. - * - * @example "FAILED:self signed certificate" - */ - certVerified: Exclude; - /** 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 + * The maximum number of tokens to generate in the response. */ - certRevoked: "1" | "0"; + max_tokens?: number; /** - * 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" + * Controls the randomness of the output; higher values produce more random results. */ - certIssuerDN: string; + temperature?: number; /** - * 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" + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - certSubjectDN: string; + top_p?: number; /** - * 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" + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - certIssuerDNRFC2253: string; + top_k?: number; /** - * 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" + * Random seed for reproducibility of the generation. */ - certSubjectDNRFC2253: string; - /** The certificate issuer's distinguished name (legacy policies) */ - certIssuerDNLegacy: string; - /** The certificate subject's distinguished name (legacy policies) */ - certSubjectDNLegacy: string; + seed?: number; /** - * The certificate's serial number - * - * @example "00936EACBE07F201DF" + * Penalty for repeated tokens; higher values discourage repetition. */ - certSerial: string; + repetition_penalty?: number; /** - * The certificate issuer's serial number - * - * @example "2489002934BDFEA34" + * Decreases the likelihood of the model repeating the same lines verbatim. */ - certIssuerSerial: string; + frequency_penalty?: number; /** - * 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" + * Increases the likelihood of the model introducing new topics. */ - certSKI: string; + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { /** - * 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" + * An array of message objects representing the conversation history. */ - certIssuerSKI: string; + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: + | string + | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * The certificate's SHA-1 fingerprint - * - * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + * A list of tools available for the assistant to use. */ - certFingerprintSHA1: string; + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; /** - * The certificate's SHA-256 fingerprint - * - * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - certFingerprintSHA256: string; + raw?: boolean; /** - * The effective starting date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - certNotBefore: string; + stream?: boolean; /** - * The effective expiration date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" + * The maximum number of tokens to generate in the response. */ - certNotAfter: string; + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -/** Placeholder values for TLS Client Authorization */ -interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { - certPresented: "0"; - certVerified: "NONE"; - certRevoked: "0"; - certIssuerDN: ""; - certSubjectDN: ""; - certIssuerDNRFC2253: ""; - certSubjectDNRFC2253: ""; - certIssuerDNLegacy: ""; - certSubjectDNLegacy: ""; - certSerial: ""; - certIssuerSerial: ""; - certSKI: ""; - certIssuerSKI: ""; - certFingerprintSHA1: ""; - certFingerprintSHA256: ""; - certNotBefore: ""; - certNotAfter: ""; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } -/** 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"; -type CfProperties = - | IncomingRequestCfProperties - | RequestInitCfProperties; -interface D1Meta { - duration: number; - size_after: number; - rows_read: number; - rows_written: number; - last_row_id: number; - changed_db: boolean; - changes: number; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { /** - * The region of the database instance that executed the query. + * The input text prompt for the model to generate a response. */ - served_by_region?: string; + prompt: string; /** - * True if-and-only-if the database instance that executed the query was the primary. + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ - served_by_primary?: boolean; - timings?: { - /** - * The duration of the SQL query execution by the database instance. It doesn't include any network time. - */ - sql_duration_ms: number; - }; -} -interface D1Response { - success: true; - meta: D1Meta & Record; - error?: never; -} -type D1Result = D1Response & { - results: T[]; -}; -interface D1ExecResult { - count: number; - duration: number; -} -type D1SessionConstraint = - // Indicates that the first query should go to the primary, and the rest queries - // using the same D1DatabaseSession will go to any replica that is consistent with - // the bookmark maintained by the session (returned by the first query). - | "first-primary" - // Indicates that the first query can go anywhere (primary or replica), and the rest queries - // using the same D1DatabaseSession will go to any replica that is consistent with - // the bookmark maintained by the session (returned by the first query). - | "first-unconstrained"; -type D1SessionBookmark = string; -declare abstract class D1Database { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; /** - * Creates a new D1 Session anchored at the given constraint or the bookmark. - * All queries executed using the created session will have sequential consistency, - * meaning that all writes done through the session will be visible in subsequent reads. - * - * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; + raw?: boolean; /** - * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - dump(): Promise; -} -declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; + stream?: boolean; /** - * @returns The latest session bookmark across all executed queries on the session. - * If no query has been executed yet, `null` is returned. + * The maximum number of tokens to generate in the response. */ - getBookmark(): D1SessionBookmark | null; -} -declare abstract class D1PreparedStatement { - bind(...values: unknown[]): D1PreparedStatement; - first(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { columnNames: true }): Promise<[string[], ...T[]]>; - raw(options?: { columnNames?: false }): Promise; -} -// `Disposable` was added to TypeScript's standard lib types in version 5.2. -// To support older TypeScript versions, define an empty `Disposable` interface. -// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, -// but this will ensure type checking on older versions still passes. -// TypeScript's interface merging will ensure our empty interface is effectively -// ignored when `Disposable` is included in the standard lib. -type Disposable = {}; -/** - * An email message that can be sent from a Worker. - */ -interface EmailMessage { - /** - * Envelope From attribute of the email message. - */ - readonly from: string; + max_tokens?: number; /** - * Envelope To attribute of the email message. + * Controls the randomness of the output; higher values produce more random results. */ - readonly to: string; -} -/** - * An email message that is sent to a consumer Worker and can be rejected/forwarded. - */ -interface ForwardableEmailMessage extends EmailMessage { + temperature?: number; /** - * Stream of the email message content. + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - readonly raw: ReadableStream; + top_p?: number; /** - * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - readonly headers: Headers; + top_k?: number; /** - * Size of the email message content. + * Random seed for reproducibility of the generation. */ - readonly rawSize: number; + seed?: 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 + * Penalty for repeated tokens; higher values discourage repetition. */ - setReject(reason: string): void; + repetition_penalty?: number; /** - * 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. + * Decreases the likelihood of the model repeating the same lines verbatim. */ - forward(rcptTo: string, headers?: Headers): Promise; + frequency_penalty?: number; /** - * Reply to the sender of this email message with a new EmailMessage object. - * @param message The reply message. - * @returns A promise that resolves when the email message is replied. + * Increases the likelihood of the model introducing new topics. */ - reply(message: EmailMessage): Promise; -} -/** - * A binding that allows a Worker to send email messages. - */ -interface SendEmail { - send(message: EmailMessage): Promise; -} -declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; + presence_penalty?: number; } -declare type EmailExportedHandler = ( - message: ForwardableEmailMessage, - env: Env, - ctx: ExecutionContext, -) => void | Promise; -declare module "cloudflare:email" { - let _EmailMessage: { - prototype: EmailMessage; - new (from: string, to: string, raw: ReadableStream | string): EmailMessage; - }; - - export { _EmailMessage as EmailMessage }; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } -/** - * Hello World binding to serve as an explanatory example. DO NOT USE - */ -interface HelloWorldBinding { +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { /** - * Retrieve the current stored value + * An array of message objects representing the conversation history. */ - get(): Promise<{ - value: string; - ms?: number; - }>; + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: + | string + | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * Set a new stored value + * A list of tools available for the assistant to use. */ - set(value: string): Promise; -} -interface Hyperdrive { + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; /** - * 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. + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - connect(): Socket; + raw?: boolean; /** - * 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. + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - 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. + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. */ - readonly host: string; - /* - * The port that must be paired the the host field when connecting. + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. */ - readonly port: number; - /* - * The username to use when authenticating to your database via Hyperdrive. - * Unlike the host and password, this will be the same every time + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - 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. + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - readonly password: string; - /* - * The name of the database to connect to. + top_k?: number; + /** + * Random seed for reproducibility of the generation. */ - readonly database: string; + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -// Copyright (c) 2024 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -type ImageInfoResponse = +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response + | string + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; +} +interface Ai_Cf_Deepgram_Nova_3_Input { + audio: { + body: object; + contentType: string; + }; + /** + * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. + */ + custom_topic_mode?: "extended" | "strict"; + /** + * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 + */ + custom_topic?: string; + /** + * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param + */ + custom_intent_mode?: "extended" | "strict"; + /** + * Custom intents you want the model to detect within your input audio if present + */ + custom_intent?: string; + /** + * Identifies and extracts key entities from content in submitted audio + */ + detect_entities?: boolean; + /** + * Identifies the dominant language spoken in submitted audio + */ + detect_language?: boolean; + /** + * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 + */ + diarize?: boolean; + /** + * Identify and extract key entities from content in submitted audio + */ + dictation?: boolean; + /** + * Specify the expected encoding of your submitted audio + */ + encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; + /** + * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing + */ + extra?: string; + /** + * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' + */ + filler_words?: boolean; + /** + * Key term prompting can boost or suppress specialized terminology and brands. + */ + keyterm?: string; + /** + * Keywords can boost or suppress specialized terminology and brands. + */ + keywords?: string; + /** + * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. + */ + language?: string; + /** + * Spoken measurements will be converted to their corresponding abbreviations. + */ + measurements?: boolean; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. + */ + mip_opt_out?: boolean; + /** + * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio + */ + mode?: "general" | "medical" | "finance"; + /** + * Transcribe each audio channel independently. + */ + multichannel?: boolean; + /** + * Numerals converts numbers from written format to numerical format. + */ + numerals?: boolean; + /** + * Splits audio into paragraphs to improve transcript readability. + */ + paragraphs?: boolean; + /** + * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. + */ + profanity_filter?: boolean; + /** + * Add punctuation and capitalization to the transcript. + */ + punctuate?: boolean; + /** + * Redaction removes sensitive information from your transcripts. + */ + redact?: string; + /** + * Search for terms or phrases in submitted audio and replaces them. + */ + replace?: string; + /** + * Search for terms or phrases in submitted audio. + */ + search?: string; + /** + * Recognizes the sentiment throughout a transcript or text. + */ + sentiment?: boolean; + /** + * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. + */ + smart_format?: boolean; + /** + * Detect topics throughout a transcript or text. + */ + topics?: boolean; + /** + * Segments speech into meaningful semantic units. + */ + utterances?: boolean; + /** + * Seconds to wait before detecting a pause between words in submitted audio. + */ + utt_split?: number; + /** + * The number of channels in the submitted audio + */ + channels?: number; + /** + * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. + */ + interim_results?: boolean; + /** + * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing + */ + endpointing?: string; + /** + * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. + */ + vad_events?: boolean; + /** + * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. + */ + utterance_end_ms?: boolean; +} +interface Ai_Cf_Deepgram_Nova_3_Output { + results?: { + channels?: { + alternatives?: { + confidence?: number; + transcript?: string; + words?: { + confidence?: number; + end?: number; + start?: number; + word?: string; + }[]; + }[]; + }[]; + summary?: { + result?: string; + short?: string; + }; + sentiments?: { + segments?: { + text?: string; + start_word?: number; + end_word?: number; + sentiment?: string; + sentiment_score?: number; + }[]; + average?: { + sentiment?: string; + sentiment_score?: number; + }; + }; + }; +} +declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { + inputs: Ai_Cf_Deepgram_Nova_3_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; + /** + * Optional instruction for the task + */ + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} +type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = | { - format: "image/svg+xml"; + /** + * readable stream with audio data and content-type specified for that data + */ + audio: { + body: object; + contentType: string; + }; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; } | { - format: string; - fileSize: number; - width: number; - height: number; + /** + * base64 encoded audio data + */ + audio: string; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; }; -type ImageTransform = { - width?: number; - height?: number; - background?: string; - blur?: number; - border?: - | { - color?: string; - width?: number; - } - | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - brightness?: number; - contrast?: number; - fit?: "scale-down" | "contain" | "pad" | "squeeze" | "cover" | "crop"; - flip?: "h" | "v" | "hv"; - gamma?: number; - gravity?: - | "left" - | "right" - | "top" - | "bottom" - | "center" - | "auto" - | "entropy" +interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { + /** + * if true, end-of-turn was detected + */ + is_complete?: boolean; + /** + * probability of the end-of-turn detection + */ + probability?: number; +} +declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { + inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; + postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; +} +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { + inputs: XOR; + postProcessedOutputs: XOR; +} +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { + inputs: XOR; + postProcessedOutputs: XOR; +} +interface Ai_Cf_Leonardo_Phoenix_1_0_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * Specify what to exclude from the generated images + */ + negative_prompt?: string; +} +/** + * The generated image in JPEG format + */ +type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; +declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { + inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + steps?: number; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { + inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; +} +interface Ai_Cf_Deepgram_Aura_1_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: + | "angus" + | "asteria" + | "arcas" + | "orion" + | "orpheus" + | "athena" + | "luna" + | "zeus" + | "perseus" + | "helios" + | "hera" + | "stella"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_1_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { + inputs: Ai_Cf_Deepgram_Aura_1_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target langauge to translate to + */ + target_language: + | "asm_Beng" + | "awa_Deva" + | "ben_Beng" + | "bho_Deva" + | "brx_Deva" + | "doi_Deva" + | "eng_Latn" + | "gom_Deva" + | "gon_Deva" + | "guj_Gujr" + | "hin_Deva" + | "hne_Deva" + | "kan_Knda" + | "kas_Arab" + | "kas_Deva" + | "kha_Latn" + | "lus_Latn" + | "mag_Deva" + | "mai_Deva" + | "mal_Mlym" + | "mar_Deva" + | "mni_Beng" + | "mni_Mtei" + | "npi_Deva" + | "ory_Orya" + | "pan_Guru" + | "san_Deva" + | "sat_Olck" + | "snd_Arab" + | "snd_Deva" + | "tam_Taml" + | "tel_Telu" + | "urd_Arab" + | "unr_Deva"; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; +} +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: + | string + | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( | { - x?: number; - y?: number; - mode: "remainder" | "box-center"; - }; - rotate?: 0 | 90 | 180 | 270; - saturation?: number; - sharpen?: number; - trim?: - | "border" + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: - | boolean - | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; -}; -type ImageDrawOptions = { - opacity?: number; - repeat?: boolean | string; - top?: number; - left?: number; - bottom?: number; - right?: number; -}; -type ImageInputOptions = { - encoding?: "base64"; -}; -type ImageOutputOptions = { - format: "image/jpeg" | "image/png" | "image/gif" | "image/webp" | "image/avif" | "rgb" | "rgba"; - quality?: number; - background?: string; -}; -interface ImagesBinding { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: ( + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 + )[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: + | string + | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response + | string + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [number, number]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: + | "amalthea" + | "andromeda" + | "apollo" + | "arcas" + | "aries" + | "asteria" + | "athena" + | "atlas" + | "aurora" + | "callista" + | "cora" + | "cordelia" + | "delia" + | "draco" + | "electra" + | "harmonia" + | "helena" + | "hera" + | "hermes" + | "hyperion" + | "iris" + | "janus" + | "juno" + | "jupiter" + | "luna" + | "mars" + | "minerva" + | "neptune" + | "odysseus" + | "ophelia" + | "orion" + | "orpheus" + | "pandora" + | "phoebe" + | "pluto" + | "saturn" + | "thalia" + | "theia" + | "vesta" + | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: + | "sirio" + | "nestor" + | "carina" + | "celeste" + | "alvaro" + | "diana" + | "aquila" + | "selena" + | "estrella" + | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output; +} +declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +interface AiModels { + "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; + "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; + "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; + "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; + "@cf/myshell-ai/melotts": BaseAiTextToSpeech; + "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; + "@cf/microsoft/resnet-50": BaseAiImageClassification; + "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; + "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; + "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; + "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; + "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; + "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; + "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; + "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; + "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; + "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; + "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; + "@cf/microsoft/phi-2": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; + "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; + "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; + "@hf/google/gemma-7b-it": BaseAiTextGeneration; + "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; + "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; + "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; + "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; + "@cf/facebook/bart-large-cnn": BaseAiSummarization; + "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; + "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; + "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; + "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; + "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; + "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; + "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; + "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; + "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; + "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; + "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; + "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; + "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; + "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; + "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; + "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; + "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; + "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; + "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; + "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; + "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; + "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; + "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; + "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; + "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; + "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; + "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; + "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev; + "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B; + "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B; + "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash; + "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5; + "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6; + "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B; + "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT; +} +type AiOptions = { + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean; + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; + signal?: AbortSignal; +}; +type AiModelsSearchParams = { + author?: string; + hide_experimental?: boolean; + page?: number; + per_page?: number; + search?: string; + source?: number; + task?: string; +}; +type AiModelsSearchObject = { + id: string; + source: number; + name: string; + description: string; + task: { + id: string; + name: string; + description: string; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; +}; +type ChatCompletionsBase = ChatCompletionsMessagesInput; +type ChatCompletionsInput = ChatCompletionsMessagesInput; +interface InferenceUpstreamError extends Error {} +interface AiInternalError extends Error {} +type AiModelListType = Record; +type AiAsyncBatchResponse = { + request_id: string; +}; +declare abstract class Ai { + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + /** + * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(): AiSearchNamespace; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + * + * @param autoragId Instance ID + */ + autorag(autoragId: string): AutoRAG; + // Batch request + run( + model: Name, + inputs: { + requests: AiModelList[Name]["inputs"][]; + }, + options: AiOptions & { + queueRequest: true; + }, + ): Promise; + // Raw response + run( + model: Name, + inputs: AiModelList[Name]["inputs"], + options: AiOptions & { + returnRawResponse: true; + }, + ): Promise; + // WebSocket + run( + model: Name, + inputs: AiModelList[Name]["inputs"], + options: AiOptions & { + websocket: true; + }, + ): Promise; + // Streaming + run( + model: Name, + inputs: AiModelList[Name]["inputs"] & { + stream: true; + }, + options?: AiOptions, + ): Promise; + // Normal (default) - known model + run( + model: Name, + inputs: AiModelList[Name]["inputs"], + options?: AiOptions, + ): Promise; + // Unknown model (fallback). + // + // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to + // route any model name that is a literal key of `AiModelList` to one of + // the known-model overloads above (so input/output mismatches surface as + // type errors rather than silently falling back to `Record`). + // Names that aren't in `AiModelList` — e.g. third-party gateway models + // like `"google/nano-banana"` — still hit this overload. + run( + model: Model extends keyof AiModelList ? never : Model, + inputs: Record, + options?: AiOptions, + ): Promise>; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(): ToMarkdownService; + toMarkdown( + files: MarkdownDocument[], + options?: ConversionRequestOptions, + ): Promise; + toMarkdown( + files: MarkdownDocument, + options?: ConversionRequestOptions, + ): Promise; +} +type GatewayRetries = { + maxAttempts?: 1 | 2 | 3 | 4 | 5; + retryDelayMs?: number; + backoff?: "constant" | "linear" | "exponential"; +}; +type GatewayOptions = { + id: string; + cacheKey?: string; + cacheTtl?: number; + skipCache?: boolean; + metadata?: Record; + collectLog?: boolean; + eventId?: string; + requestTimeoutMs?: number; + retries?: GatewayRetries; +}; +type UniversalGatewayOptions = Exclude & { + /** + ** @deprecated + */ + id?: string; +}; +type AiGatewayPatchLog = { + score?: number | null; + feedback?: -1 | 1 | null; + metadata?: Record | null; +}; +type AiGatewayLog = { + id: string; + provider: string; + model: string; + model_type?: string; + path: string; + duration: number; + request_type?: string; + request_content_type?: string; + status_code: number; + response_content_type?: string; + success: boolean; + cached: boolean; + tokens_in?: number; + tokens_out?: number; + metadata?: Record; + step?: number; + cost?: number; + custom_cost?: boolean; + request_size: number; + request_head?: string; + request_head_complete: boolean; + response_size: number; + response_head?: string; + response_head_complete: boolean; + created_at: Date; +}; +type AIGatewayProviders = + | "workers-ai" + | "anthropic" + | "aws-bedrock" + | "azure-openai" + | "google-vertex-ai" + | "huggingface" + | "openai" + | "perplexity-ai" + | "replicate" + | "groq" + | "cohere" + | "google-ai-studio" + | "mistral" + | "grok" + | "openrouter" + | "deepseek" + | "cerebras" + | "cartesia" + | "elevenlabs" + | "adobe-firefly"; +type AIGatewayHeaders = { + "cf-aig-metadata": Record | string; + "cf-aig-custom-cost": + | { + per_token_in?: number; + per_token_out?: number; + } + | { + total_cost?: number; + } + | string; + "cf-aig-cache-ttl": number | string; + "cf-aig-skip-cache": boolean | string; + "cf-aig-cache-key": string; + "cf-aig-event-id": string; + "cf-aig-request-timeout": number | string; + "cf-aig-max-attempts": number | string; + "cf-aig-retry-delay": number | string; + "cf-aig-backoff": string; + "cf-aig-collect-log": boolean | string; + Authorization: string; + "Content-Type": string; + [key: string]: string | number | boolean | object; +}; +type AIGatewayUniversalRequest = { + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; +}; +interface AiGatewayInternalError extends Error {} +interface AiGatewayLogNotFound extends Error {} +declare abstract class AiGateway { + patchLog(logId: string, data: AiGatewayPatchLog): Promise; + getLog(logId: string): Promise; + run( + data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], + options?: { + gateway?: UniversalGatewayOptions; + extraHeaders?: object; + signal?: AbortSignal; + }, + ): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line +} +// Copyright (c) 2022-2025 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Artifacts — Git-compatible file storage on Cloudflare Workers. + * + * Provides programmatic access to create, manage, and fork repositories, + * and to issue and revoke scoped access tokens. + */ +/** Information about a repository. */ +interface ArtifactsRepoInfo { + /** Unique repository ID. */ + id: string; + /** Repository name. */ + name: string; + /** Repository description, or null if not set. */ + description: string | null; + /** Default branch name (e.g. "main"). */ + defaultBranch: string; + /** ISO 8601 creation timestamp. */ + createdAt: string; + /** ISO 8601 last-updated timestamp. */ + updatedAt: string; + /** ISO 8601 timestamp of the last push, or null if never pushed. */ + lastPushAt: string | null; + /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */ + source: string | null; + /** Whether the repository is read-only. */ + readOnly: boolean; + /** HTTPS git remote URL. */ + remote: string; +} +/** Result of creating a repository — includes the initial access token. */ +interface ArtifactsCreateRepoResult { + /** Unique repository ID. */ + id: string; + /** Repository name. */ + name: string; + /** Repository description, or null if not set. */ + description: string | null; + /** Default branch name. */ + defaultBranch: string; + /** HTTPS git remote URL. */ + remote: string; + /** Plaintext access token (only returned at creation time). */ + token: string; + /** ISO 8601 token expiry timestamp. */ + tokenExpiresAt: string; +} +/** Paginated list of repositories. */ +interface ArtifactsRepoListResult { + /** Repositories in this page (without the `remote` field). */ + repos: Omit[]; + /** Total number of repositories in the namespace. */ + total: number; + /** Cursor for the next page, if there are more results. */ + cursor?: string; +} +/** Result of creating an access token. */ +interface ArtifactsCreateTokenResult { + /** Unique token ID. */ + id: string; + /** Plaintext token (only returned at creation time). */ + plaintext: string; + /** Token scope: "read" or "write". */ + scope: "read" | "write"; + /** ISO 8601 token expiry timestamp. */ + expiresAt: string; +} +/** Token metadata (no plaintext). */ +interface ArtifactsTokenInfo { + /** Unique token ID. */ + id: string; + /** Token scope: "read" or "write". */ + scope: "read" | "write"; + /** Token state: "active", "expired", or "revoked". */ + state: "active" | "expired" | "revoked"; + /** ISO 8601 creation timestamp. */ + createdAt: string; + /** ISO 8601 expiry timestamp. */ + expiresAt: string; +} +/** Paginated list of tokens for a repository. */ +interface ArtifactsTokenListResult { + /** Tokens in this page. */ + tokens: ArtifactsTokenInfo[]; + /** Total number of tokens for the repository. */ + total: number; +} +/** + * Handle for a single repository. Returned by Artifacts.get(). + * + * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs. + */ +interface ArtifactsRepo extends ArtifactsRepoInfo { + /** + * Create an access token for this repo. + * @param scope Token scope: "write" (default) or "read". + * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000). + * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range. + */ + createToken(scope?: "write" | "read", ttl?: number): Promise; + /** List tokens for this repo (metadata only, no plaintext). */ + listTokens(): Promise; + /** + * Revoke a token by plaintext or ID. + * @param tokenOrId Plaintext token or token ID. + * @returns true if revoked, false if not found. + * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty. + */ + revokeToken(tokenOrId: string): Promise; + // ── Fork ── + /** + * Fork this repo to a new repo. + * @param name Target repository name. + * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true). + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists. + * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running. + */ + fork( + name: string, + opts?: { + description?: string; + readOnly?: boolean; + defaultBranchOnly?: boolean; + }, + ): Promise; +} +// ── Error types ────────────────────────────────────────────────────────────── +/** + * Error codes returned by Artifacts binding operations. + * + * Each code maps to a numeric code available on `ArtifactsError.numericCode`. + */ +type ArtifactsErrorCode = + | "ALREADY_EXISTS" + | "NOT_FOUND" + | "IMPORT_IN_PROGRESS" + | "FORK_IN_PROGRESS" + | "INVALID_INPUT" + | "INVALID_REPO_NAME" + | "INVALID_TTL" + | "INVALID_URL" + | "REMOTE_AUTH_REQUIRED" + | "UPSTREAM_UNAVAILABLE" + | "MEMORY_LIMIT" + | "INTERNAL_ERROR"; +/** + * Error thrown by Artifacts binding operations. + * + * Uses a string `.code` discriminator following the Cloudflare platform + * convention (StreamError, ImagesError, etc.). The `.numericCode` matches + * the REST API `errors[].code` values. + */ +interface ArtifactsError extends Error { + readonly name: "ArtifactsError"; + /** String error code for programmatic matching. */ + readonly code: ArtifactsErrorCode; + /** Numeric error code matching the REST API. */ + readonly numericCode: number; +} +// ── Binding ────────────────────────────────────────────────────────────────── +/** + * Artifacts binding — namespace-level operations. + * + * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs. + */ +interface Artifacts { + /** + * Create a new repository with an initial access token. + * @param name Repository name (alphanumeric, dots, hyphens, underscores). + * @param opts Optional: readOnly flag, description, default branch name. + * @returns Repo metadata with initial token. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists. + */ + create( + name: string, + opts?: { + readOnly?: boolean; + description?: string; + setDefaultBranch?: string; + }, + ): Promise; + /** + * Get a handle to an existing repository. + * @param name Repository name. + * @returns Repo handle. + * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist. + * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing. + * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking. + */ + get(name: string): Promise; + /** + * Import a repository from an external git remote. + * @param params Source URL and optional branch/depth, plus target name and options. + * @returns Repo metadata with initial token. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid. + * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS. + * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository. + * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication. + * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist. + * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached. + * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists. + */ + import(params: { + source: { + url: string; + branch?: string; + depth?: number; + }; + target: { + name: string; + opts?: { + description?: string; + readOnly?: boolean; + }; + }; + }): Promise; + /** + * List repositories with cursor-based pagination. + * @param opts Optional: limit (1–200, default 50), cursor for next page. + */ + list(opts?: { limit?: number; cursor?: string }): Promise; + /** + * Delete a repository and all associated tokens. + * @param name Repository name. + * @returns true if deleted, false if not found. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + */ + delete(name: string): Promise; +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGInternalError extends Error {} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGNotFoundError extends Error {} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGUnauthorizedError extends Error {} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGNameNotSetError extends Error {} +type ComparisonFilter = { + key: string; + type: "eq" | "ne" | "gt" | "gte" | "lt" | "lte"; + value: string | number | boolean; +}; +type CompoundFilter = { + type: "and" | "or"; + filters: ComparisonFilter[]; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagSearchRequest = { + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + reranking?: { + enabled?: boolean; + model?: string; + }; + rewrite_query?: boolean; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchRequest = AutoRagSearchRequest & { + stream?: boolean; + system_prompt?: string; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchRequestStreaming = Omit & { + stream: true; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagSearchResponse = { + object: "vector_store.search_results.page"; + search_query: string; + data: { + file_id: string; + filename: string; + score: number; + attributes: Record; + content: { + type: "text"; + text: string; + }[]; + }[]; + has_more: boolean; + next_page: string | null; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagListResponse = { + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; +}[]; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchResponse = AutoRagSearchResponse & { + response: string; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +declare abstract class AutoRAG { + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + list(): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; +} +type BrowserRunLifecycleEvent = "load" | "domcontentloaded" | "networkidle0" | "networkidle2"; +type BrowserRunResourceType = + | "document" + | "stylesheet" + | "image" + | "media" + | "font" + | "script" + | "texttrack" + | "xhr" + | "fetch" + | "prefetch" + | "eventsource" + | "websocket" + | "manifest" + | "signedexchange" + | "ping" + | "cspviolationreport" + | "preflight" + | "other"; +/** Options fields shared by all quick actions. */ +interface BrowserRunBaseOptions { + /** Adds `