From fa6fcd3c7c99c95a16e5da6ea29c09bcaa36c1c7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 14 Aug 2026 10:20:32 +0000 Subject: [PATCH 1/4] Migrate the UI onto the create-webapp stack and unslop chrome. SvelteKit 3, Alchemy, Effect Schema remotes, Vite+, pnpm, and shadcn under #lib replace the Bun/wrangler/svelte.config.js setup. Local sidecar and Node sqlite stay for `codeview ui`. Chrome drops Google Fonts, tracked-out labels, and the generic checkmark mark. Co-authored-by: themixednuts --- .gitignore | 4 +- AGENTS.md | 9 + CLAUDE.md | 20 +- codeview-cli/build.rs | 10 +- codeview-cli/src/publisher/r2.rs | 21 +- codeview-ui/.node-version | 1 + codeview-ui/.npmrc | 2 + codeview-ui/alchemy.run.ts | 115 + codeview-ui/bun.lock | 2155 ---- codeview-ui/components.json | 17 +- codeview-ui/e2e/run-cf-dev-supervisor.mjs | 4 +- codeview-ui/package.json | 218 +- codeview-ui/playwright.config.ts | 2 +- codeview-ui/pnpm-lock.yaml | 10691 ++++++++++++++++ codeview-ui/pnpm-workspace.yaml | 55 + codeview-ui/scripts/bulk-put-local.ts | 4 +- .../scripts/retain-cloudflare-assets.ts | 2 +- codeview-ui/scripts/with-env.ts | 2 +- codeview-ui/scripts/with-platform.ts | 2 +- codeview-ui/src/app.css | 55 +- codeview-ui/src/app.d.ts | 36 +- codeview-ui/src/app.html | 6 - codeview-ui/src/hooks.client.ts | 4 +- codeview-ui/src/hooks.server.ts | 9 +- .../lib/components/AdminForceParseForm.svelte | 20 +- .../src/lib/components/Breadcrumbs.svelte | 4 +- .../src/lib/components/CodeBlock.svelte | 4 +- .../src/lib/components/CrateGrid.svelte | 8 +- .../src/lib/components/CrateParseState.svelte | 2 +- .../src/lib/components/CrateSunburst.svelte | 6 +- .../src/lib/components/CrateTreemap.svelte | 6 +- .../src/lib/components/DetailView.svelte | 42 +- .../src/lib/components/DocsUnavailable.svelte | 14 +- .../src/lib/components/Documentation.svelte | 13 +- .../lib/components/GlobalCrateCommand.svelte | 10 +- .../src/lib/components/NodeDetails.svelte | 24 +- .../src/lib/components/ParseError.svelte | 6 +- .../src/lib/components/SearchResults.svelte | 10 +- .../src/lib/components/SettingsDrawer.svelte | 14 +- .../lib/components/SettingsRadioOption.svelte | 4 +- .../src/lib/components/SignatureBlock.svelte | 4 +- .../src/lib/components/SourceActions.svelte | 4 +- .../src/lib/components/SourceViewer.svelte | 12 +- .../lib/components/StablePagination.svelte | 6 +- .../src/lib/components/StdDocsPrompt.svelte | 4 +- .../src/lib/components/VizSwitcher.svelte | 2 +- .../lib/components/design/CodeBlock.svelte | 6 +- .../components/design/GraphNodePill.svelte | 16 +- .../src/lib/components/design/Icon.svelte | 2 +- .../lib/components/design/KindBadge.svelte | 8 +- .../lib/components/design/LiveExplorer.svelte | 50 +- .../lib/components/design/Signature.svelte | 4 +- .../components/design/docs/DocArticle.svelte | 10 +- .../components/design/docs/DocClassic.svelte | 6 +- .../design/docs/DocReadAloud.svelte | 6 +- .../components/design/docs/DocReading.svelte | 4 +- .../components/design/docs/DocSplit.svelte | 12 +- .../design/graph/CrateModuleNode.svelte | 6 +- .../design/graph/CrateOverviewFlow.svelte | 8 +- .../design/graph/FocusGraphFlow.svelte | 16 +- .../design/graph/GraphNodePillFlow.svelte | 4 +- .../lib/components/design/graph/flow-types.ts | 4 +- .../components/design/graph/focus-layout.ts | 4 +- .../ui/button-group/button-group.svelte | 2 +- .../ui/button-group/index.ts | 0 .../ui/button/button.svelte | 2 +- .../{shadcn => components}/ui/button/index.ts | 0 .../ui/command/command-dialog.svelte | 4 +- .../ui/command/command-empty.svelte | 2 +- .../ui/command/command-group.svelte | 2 +- .../ui/command/command-input.svelte | 4 +- .../ui/command/command-item.svelte | 2 +- .../ui/command/command-link-item.svelte | 2 +- .../ui/command/command-list.svelte | 2 +- .../ui/command/command-loading.svelte | 0 .../ui/command/command-separator.svelte | 2 +- .../ui/command/command-shortcut.svelte | 2 +- .../ui/command/command.svelte | 2 +- .../ui/command/index.ts | 0 .../ui/dialog/dialog-close.svelte | 0 .../ui/dialog/dialog-content.svelte | 4 +- .../ui/dialog/dialog-description.svelte | 2 +- .../ui/dialog/dialog-footer.svelte | 4 +- .../ui/dialog/dialog-header.svelte | 2 +- .../ui/dialog/dialog-overlay.svelte | 2 +- .../ui/dialog/dialog-portal.svelte | 0 .../ui/dialog/dialog-title.svelte | 2 +- .../ui/dialog/dialog-trigger.svelte | 0 .../ui/dialog/dialog.svelte | 0 .../{shadcn => components}/ui/dialog/index.ts | 0 .../ui/field/field-content.svelte | 2 +- .../ui/field/field-description.svelte | 2 +- .../ui/field/field-error.svelte | 2 +- .../ui/field/field-group.svelte | 2 +- .../ui/field/field-label.svelte | 4 +- .../ui/field/field-legend.svelte | 2 +- .../ui/field/field-separator.svelte | 4 +- .../ui/field/field-set.svelte | 2 +- .../ui/field/field-title.svelte | 2 +- .../ui/field/field.svelte | 2 +- .../{shadcn => components}/ui/field/index.ts | 0 .../ui/input-group/index.ts | 0 .../ui/input-group/input-group-addon.svelte | 2 +- .../ui/input-group/input-group-button.svelte | 4 +- .../ui/input-group/input-group-input.svelte | 4 +- .../ui/input-group/input-group-text.svelte | 2 +- .../input-group/input-group-textarea.svelte | 4 +- .../ui/input-group/input-group.svelte | 2 +- .../{shadcn => components}/ui/input/index.ts | 0 .../ui/input/input.svelte | 2 +- .../{shadcn => components}/ui/label/index.ts | 0 .../ui/label/label.svelte | 2 +- .../ui/native-select/index.ts | 0 .../native-select-opt-group.svelte | 2 +- .../native-select/native-select-option.svelte | 2 +- .../ui/native-select/native-select.svelte | 2 +- .../ui/pagination/index.ts | 0 .../ui/pagination/pagination-content.svelte | 2 +- .../ui/pagination/pagination-ellipsis.svelte | 2 +- .../ui/pagination/pagination-item.svelte | 2 +- .../ui/pagination/pagination-link.svelte | 4 +- .../pagination/pagination-next-button.svelte | 2 +- .../ui/pagination/pagination-next.svelte | 4 +- .../pagination/pagination-prev-button.svelte | 2 +- .../ui/pagination/pagination-previous.svelte | 4 +- .../ui/pagination/pagination.svelte | 2 +- .../ui/radio-group/index.ts | 0 .../ui/radio-group/radio-group-item.svelte | 2 +- .../ui/radio-group/radio-group.svelte | 2 +- .../ui/resizable/index.ts | 0 .../ui/resizable/resizable-handle.svelte | 2 +- .../ui/resizable/resizable-pane-group.svelte | 2 +- .../ui/separator/index.ts | 0 .../ui/separator/separator.svelte | 2 +- .../{shadcn => components}/ui/sheet/index.ts | 0 .../ui/sheet/sheet-close.svelte | 0 .../ui/sheet/sheet-content.svelte | 4 +- .../ui/sheet/sheet-description.svelte | 2 +- .../ui/sheet/sheet-footer.svelte | 2 +- .../ui/sheet/sheet-header.svelte | 2 +- .../ui/sheet/sheet-overlay.svelte | 2 +- .../ui/sheet/sheet-portal.svelte | 0 .../ui/sheet/sheet-title.svelte | 2 +- .../ui/sheet/sheet-trigger.svelte | 0 .../ui/sheet/sheet.svelte | 0 .../{shadcn => components}/ui/sonner/index.ts | 0 .../ui/sonner/sonner.svelte | 0 .../{shadcn => components}/ui/switch/index.ts | 0 .../ui/switch/switch.svelte | 2 +- .../ui/textarea/index.ts | 0 .../ui/textarea/textarea.svelte | 2 +- .../lib/{shadcn => components/ui}/theme.css | 0 codeview-ui/src/lib/context.ts | 4 +- codeview-ui/src/lib/design/live-node.ts | 8 +- .../lib/design/relationship-groups.test.ts | 2 +- .../src/lib/design/relationship-groups.ts | 4 +- codeview-ui/src/lib/detail-model.test.ts | 2 +- codeview-ui/src/lib/detail-model.ts | 6 +- codeview-ui/src/lib/display-names.ts | 2 +- codeview-ui/src/lib/docs.ts | 4 +- .../src/lib/exporters/excalidraw.test.ts | 8 +- codeview-ui/src/lib/exporters/excalidraw.ts | 12 +- codeview-ui/src/lib/graph.ts | 2 +- codeview-ui/src/lib/graph/crate-map.test.ts | 2 +- codeview-ui/src/lib/graph/crate-map.ts | 4 +- codeview-ui/src/lib/graph/index.ts | 2 +- codeview-ui/src/lib/graph/labels/compute.ts | 4 +- codeview-ui/src/lib/graph/labels/providers.ts | 2 +- codeview-ui/src/lib/graph/labels/types.ts | 2 +- codeview-ui/src/lib/graph/layout/collision.ts | 6 +- codeview-ui/src/lib/graph/layout/compute.ts | 4 +- codeview-ui/src/lib/graph/layout/ego.ts | 4 +- .../src/lib/graph/layout/force.test.ts | 2 +- codeview-ui/src/lib/graph/layout/force.ts | 2 +- .../src/lib/graph/layout/hierarchical.ts | 4 +- codeview-ui/src/lib/graph/layout/radial.ts | 2 +- codeview-ui/src/lib/graph/layout/types.ts | 2 +- codeview-ui/src/lib/graph/projection.test.ts | 2 +- codeview-ui/src/lib/graph/projection.ts | 6 +- codeview-ui/src/lib/graph/tree-index.ts | 6 +- .../src/lib/graph/visual/edge-anchor.ts | 6 +- .../src/lib/graph/visual/node-visual.ts | 2 +- codeview-ui/src/lib/graph/visual/palette.ts | 2 +- codeview-ui/src/lib/graph/visual/shapes.ts | 2 +- codeview-ui/src/lib/hosted-contract.ts | 2 +- codeview-ui/src/lib/index.ts | 7 + codeview-ui/src/lib/node-order.ts | 2 +- codeview-ui/src/lib/node-summary.test.ts | 2 +- codeview-ui/src/lib/node-summary.ts | 2 +- .../src/lib/realtime/processing.svelte.ts | 4 +- .../src/lib/realtime/progress.svelte.ts | 2 +- codeview-ui/src/lib/realtime/queue.svelte.ts | 6 +- codeview-ui/src/lib/realtime/status.svelte.ts | 6 +- .../src/lib/realtime/updates.svelte.ts | 2 +- codeview-ui/src/lib/renderers/graph.test.ts | 4 +- codeview-ui/src/lib/renderers/graph.ts | 10 +- codeview-ui/src/lib/rpc/ancestors.remote.ts | 10 +- codeview-ui/src/lib/rpc/children.remote.ts | 9 +- codeview-ui/src/lib/rpc/crate.remote.ts | 8 +- codeview-ui/src/lib/rpc/crateMap.remote.ts | 6 +- codeview-ui/src/lib/rpc/detail.remote.ts | 4 +- codeview-ui/src/lib/rpc/helpers.ts | 24 +- codeview-ui/src/lib/rpc/meta.remote.ts | 6 +- codeview-ui/src/lib/rpc/nodeView.remote.ts | 6 +- codeview-ui/src/lib/rpc/remote-utils.ts | 2 +- codeview-ui/src/lib/rpc/roots.remote.ts | 6 +- codeview-ui/src/lib/rpc/schemas.ts | 137 +- codeview-ui/src/lib/rpc/search.remote.ts | 8 +- codeview-ui/src/lib/rpc/source.remote.ts | 7 +- codeview-ui/src/lib/server/auth.ts | 6 +- .../src/lib/server/cloudflare/catalog.ts | 4 +- .../src/lib/server/cloudflare/provider.ts | 22 +- codeview-ui/src/lib/server/cross-edges.ts | 2 +- codeview-ui/src/lib/server/db/schema.ts | 2 +- codeview-ui/src/lib/server/local/cache.ts | 44 +- codeview-ui/src/lib/server/local/provider.ts | 35 +- codeview-ui/src/lib/server/local/sysroot.ts | 4 +- codeview-ui/src/lib/server/local/ws.ts | 24 +- .../src/lib/server/parsing/parse-rustdoc.ts | 10 +- codeview-ui/src/lib/server/provider.ts | 6 +- codeview-ui/src/lib/server/validation.ts | 6 +- codeview-ui/src/lib/signature-format.test.ts | 2 +- codeview-ui/src/lib/signature-format.ts | 2 +- codeview-ui/src/lib/source-links.ts | 4 +- codeview-ui/src/lib/sse/client.ts | 2 +- codeview-ui/src/lib/sse/index.ts | 2 +- codeview-ui/src/lib/sse/processing.svelte.ts | 2 +- codeview-ui/src/lib/sse/progress.svelte.ts | 2 +- codeview-ui/src/lib/sse/shared.client.ts | 4 +- codeview-ui/src/lib/sse/status.svelte.ts | 2 +- codeview-ui/src/lib/sse/updates.svelte.ts | 2 +- .../src/lib/trait-member-hydration.test.ts | 2 +- codeview-ui/src/lib/trait-member-hydration.ts | 2 +- codeview-ui/src/lib/tree.ts | 6 +- codeview-ui/src/lib/type-render.ts | 2 +- codeview-ui/src/lib/url-state.ts | 4 +- codeview-ui/src/lib/url.ts | 4 +- codeview-ui/src/lib/{shadcn => }/utils.ts | 6 +- codeview-ui/src/lib/ws/client.ts | 4 +- codeview-ui/src/lib/ws/index.ts | 2 +- codeview-ui/src/lib/ws/processing.svelte.ts | 2 +- codeview-ui/src/lib/ws/progress.svelte.ts | 2 +- codeview-ui/src/lib/ws/status.svelte.ts | 2 +- codeview-ui/src/routes/+layout.server.ts | 2 +- codeview-ui/src/routes/+layout.svelte | 35 +- codeview-ui/src/routes/+page.server.ts | 4 +- codeview-ui/src/routes/+page.svelte | 12 +- .../[crate]/[version]/+layout.server.ts | 12 +- .../routes/[crate]/[version]/+layout.svelte | 34 +- codeview-ui/src/routes/admin/+page.server.ts | 8 +- codeview-ui/src/routes/admin/+page.svelte | 14 +- codeview-ui/src/routes/auth/github/+server.ts | 4 +- .../src/routes/auth/sign-out/+server.ts | 4 +- .../src/routes/go/crate-version/+server.ts | 2 +- codeview-ui/src/routes/queue/+page.server.ts | 2 +- codeview-ui/src/routes/queue/+page.svelte | 12 +- .../src/routes/settings/+page.server.ts | 4 +- codeview-ui/src/routes/settings/+page.svelte | 13 +- codeview-ui/svelte.config.js | 46 - codeview-ui/tools/oxlint/anti-slop/index.ts | 41 + .../rules/no-chained-type-assertions.ts | 77 + .../no-conditional-empty-object-spread.ts | 49 + .../rules/no-known-value-widening.ts | 247 + .../anti-slop/rules/no-module-mocking.ts | 91 + .../anti-slop/rules/no-object-parameters.ts | 137 + .../anti-slop/rules/no-reflect-apply.ts | 28 + .../oxlint/anti-slop/rules/no-reflect-get.ts | 28 + .../anti-slop/rules/no-runtime-typeof.ts | 25 + .../rules/no-shape-in-symbol-names.ts | 39 + .../anti-slop/rules/no-unknown-parameters.ts | 83 + .../anti-slop/rules/no-unknown-returns.ts | 120 + .../rules/no-unknown-type-aliases.ts | 70 + .../rules/no-unsafe-dictionary-type.ts | 134 + .../anti-slop/rules/no-widen-then-assert.ts | 366 + ...quire-safety-comment-for-type-assertion.ts | 62 + .../anti-slop/shared/dictionary-types.ts | 502 + .../oxlint/anti-slop/shared/reflect-method.ts | 35 + codeview-ui/tsconfig.json | 19 +- codeview-ui/vite.config.ts | 277 +- 279 files changed, 14011 insertions(+), 3235 deletions(-) create mode 100644 AGENTS.md create mode 100644 codeview-ui/.node-version create mode 100644 codeview-ui/.npmrc create mode 100644 codeview-ui/alchemy.run.ts delete mode 100644 codeview-ui/bun.lock create mode 100644 codeview-ui/pnpm-lock.yaml create mode 100644 codeview-ui/pnpm-workspace.yaml rename codeview-ui/src/lib/{shadcn => components}/ui/button-group/button-group.svelte (87%) rename codeview-ui/src/lib/{shadcn => components}/ui/button-group/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/button/button.svelte (98%) rename codeview-ui/src/lib/{shadcn => components}/ui/button/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-dialog.svelte (89%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-empty.svelte (88%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-group.svelte (95%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-input.svelte (90%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-item.svelte (95%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-link-item.svelte (94%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-list.svelte (89%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-loading.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-separator.svelte (88%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command-shortcut.svelte (87%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/command.svelte (90%) rename codeview-ui/src/lib/{shadcn => components}/ui/command/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-close.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-content.svelte (92%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-description.svelte (90%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-footer.svelte (86%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-header.svelte (85%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-overlay.svelte (91%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-portal.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-title.svelte (88%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog-trigger.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/dialog.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/dialog/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-content.svelte (86%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-description.svelte (90%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-error.svelte (94%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-group.svelte (87%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-label.svelte (88%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-legend.svelte (88%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-separator.svelte (85%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-set.svelte (87%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field-title.svelte (87%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/field.svelte (95%) rename codeview-ui/src/lib/{shadcn => components}/ui/field/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/input-group/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/input-group/input-group-addon.svelte (95%) rename codeview-ui/src/lib/{shadcn => components}/ui/input-group/input-group-button.svelte (91%) rename codeview-ui/src/lib/{shadcn => components}/ui/input-group/input-group-input.svelte (83%) rename codeview-ui/src/lib/{shadcn => components}/ui/input-group/input-group-text.svelte (87%) rename codeview-ui/src/lib/{shadcn => components}/ui/input-group/input-group-textarea.svelte (83%) rename codeview-ui/src/lib/{shadcn => components}/ui/input-group/input-group.svelte (95%) rename codeview-ui/src/lib/{shadcn => components}/ui/input/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/input/input.svelte (96%) rename codeview-ui/src/lib/{shadcn => components}/ui/label/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/label/label.svelte (92%) rename codeview-ui/src/lib/{shadcn => components}/ui/native-select/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/native-select/native-select-opt-group.svelte (84%) rename codeview-ui/src/lib/{shadcn => components}/ui/native-select/native-select-option.svelte (86%) rename codeview-ui/src/lib/{shadcn => components}/ui/native-select/native-select.svelte (95%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination-content.svelte (85%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination-ellipsis.svelte (96%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination-item.svelte (83%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination-link.svelte (85%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination-next-button.svelte (94%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination-next.svelte (84%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination-prev-button.svelte (94%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination-previous.svelte (84%) rename codeview-ui/src/lib/{shadcn => components}/ui/pagination/pagination.svelte (92%) rename codeview-ui/src/lib/{shadcn => components}/ui/radio-group/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/radio-group/radio-group-item.svelte (94%) rename codeview-ui/src/lib/{shadcn => components}/ui/radio-group/radio-group.svelte (89%) rename codeview-ui/src/lib/{shadcn => components}/ui/resizable/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/resizable/resizable-handle.svelte (93%) rename codeview-ui/src/lib/{shadcn => components}/ui/resizable/resizable-pane-group.svelte (90%) rename codeview-ui/src/lib/{shadcn => components}/ui/separator/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/separator/separator.svelte (93%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-close.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-content.svelte (94%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-description.svelte (88%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-footer.svelte (85%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-header.svelte (85%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-overlay.svelte (89%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-portal.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-title.svelte (88%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet-trigger.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/sheet/sheet.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/sonner/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/sonner/sonner.svelte (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/switch/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/switch/switch.svelte (96%) rename codeview-ui/src/lib/{shadcn => components}/ui/textarea/index.ts (100%) rename codeview-ui/src/lib/{shadcn => components}/ui/textarea/textarea.svelte (97%) rename codeview-ui/src/lib/{shadcn => components/ui}/theme.css (100%) create mode 100644 codeview-ui/src/lib/index.ts rename codeview-ui/src/lib/{shadcn => }/utils.ts (65%) delete mode 100644 codeview-ui/svelte.config.js create mode 100644 codeview-ui/tools/oxlint/anti-slop/index.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-chained-type-assertions.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-conditional-empty-object-spread.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-known-value-widening.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-module-mocking.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-object-parameters.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-reflect-apply.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-reflect-get.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-runtime-typeof.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-shape-in-symbol-names.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-unknown-parameters.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-unknown-returns.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-unknown-type-aliases.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-unsafe-dictionary-type.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/no-widen-then-assert.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/rules/require-safety-comment-for-type-assertion.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/shared/dictionary-types.ts create mode 100644 codeview-ui/tools/oxlint/anti-slop/shared/reflect-method.ts diff --git a/.gitignore b/.gitignore index ffc5c36..2b2ea66 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,9 @@ Cargo.lock /codeview-ui/.svelte-kit /codeview-ui/build /codeview-ui/.vite +/codeview-ui/.vite-plus +/codeview-ui/.alchemy +/codeview-ui/coverage /codeview-ui/.env # Local/IDE @@ -29,7 +32,6 @@ opencode.json /design-input/ /design-input-v2/ /.codemogger/ -AGENTS.md # Playwright /codeview-ui/test-results/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..13561df --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,9 @@ +# Agents + +SvelteKit 3, Effect v4, Cloudflare via Alchemy, Better Auth, Drizzle, Tailwind v4, shadcn-svelte, Vite+, pnpm. Celld is an optional self-hosted host instead of Cloudflare. + +App imports use `#lib`. Kit config lives in `codeview-ui/vite.config.ts`. The host lives in `codeview-ui/alchemy.run.ts`. Auth, sqlite, and bindings share one Effect runtime through Alchemy. Pages are shadcn plus Tailwind, progressive enhancement, remote functions with Effect Schema. + +Local `codeview ui` still builds a sidecar with `@jesterkit/exe-sveltekit`. Alchemy injects the Cloudflare adapter for hosted builds. + +Follow the effect skill. Follow create-webapp conventions when adding packages or rewriting config. diff --git a/CLAUDE.md b/CLAUDE.md index abdd87e..3695a69 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,23 +42,21 @@ cargo run -p codeview-cli -- analyze --manifest-path {path/Cargo.toml} --out {ou ## Package Manager -Use **bun** for all package management operations: -- Install: `bun add ` or `bun add -D ` for dev dependencies -- Run scripts: `bun run - - - %sveltekit.head% diff --git a/codeview-ui/src/hooks.client.ts b/codeview-ui/src/hooks.client.ts index a145db4..1d7e492 100644 --- a/codeview-ui/src/hooks.client.ts +++ b/codeview-ui/src/hooks.client.ts @@ -1,5 +1,5 @@ -import type { HandleClientError } from '@sveltejs/kit'; -import { getLogger, setupLogging } from '$lib/log'; +import type { HandleClientError } from '@sveltejs/kit/hooks'; +import { getLogger, setupLogging } from '#lib/log'; const log = getLogger('client-hooks'); diff --git a/codeview-ui/src/hooks.server.ts b/codeview-ui/src/hooks.server.ts index 532e6b1..68fa298 100644 --- a/codeview-ui/src/hooks.server.ts +++ b/codeview-ui/src/hooks.server.ts @@ -1,7 +1,8 @@ -import type { Cookies, Handle } from '@sveltejs/kit'; -import { setupLogging } from '$lib/log.server'; +import type { Cookies } from '$app/server'; +import type { Handle } from '@sveltejs/kit/hooks'; +import { setupLogging } from '#lib/log.server'; import { handleWsUpgrade } from '$provider'; -import { getAuthState, handleAuthRequest } from '$lib/server/auth'; +import { getAuthState, handleAuthRequest } from '#lib/server/auth'; import { ACCENT_KEY, ACCENT_VALUES, @@ -20,7 +21,7 @@ import { VOICE_KEY, VOICE_VALUES, readAllowedPreference, -} from '$lib/preferences'; +} from '#lib/preferences'; await setupLogging(); diff --git a/codeview-ui/src/lib/components/AdminForceParseForm.svelte b/codeview-ui/src/lib/components/AdminForceParseForm.svelte index cb1c88f..419357f 100644 --- a/codeview-ui/src/lib/components/AdminForceParseForm.svelte +++ b/codeview-ui/src/lib/components/AdminForceParseForm.svelte @@ -1,14 +1,14 @@
{#if label} diff --git a/codeview-ui/src/lib/components/design/GraphNodePill.svelte b/codeview-ui/src/lib/components/design/GraphNodePill.svelte index 4ed0fff..ef9b8d6 100644 --- a/codeview-ui/src/lib/components/design/GraphNodePill.svelte +++ b/codeview-ui/src/lib/components/design/GraphNodePill.svelte @@ -1,8 +1,8 @@ '); + const input = page.locator("#global-search"); + await input.fill(''); - await page.waitForTimeout(500); + await page.waitForTimeout(500); - const dropdown = page.locator('.corner-squircle.z-30'); - if (await dropdown.isVisible()) { - const html = await dropdown.innerHTML(); - expect(html).not.toContain(' - %sveltekit.head% - - -
%sveltekit.body%
- + document.documentElement.dataset.accent = accent; + document.documentElement.dataset.density = density; + document.documentElement.dataset.textSize = textSize; + document.documentElement.dataset.voice = voice; + document.documentElement.dataset.docLayout = docLayout; + document.documentElement.dataset.codeThemeLight = codeLight; + document.documentElement.dataset.codeThemeDark = codeDark; + document.documentElement.dataset.codeTheme = mode === "dark" ? codeDark : codeLight; + } catch (e) { + document.documentElement.dataset.theme = "light"; + document.documentElement.dataset.accent = "orange"; + document.documentElement.dataset.density = "comfortable"; + document.documentElement.dataset.textSize = "standard"; + document.documentElement.dataset.voice = "editorial"; + document.documentElement.dataset.docLayout = "classic"; + document.documentElement.dataset.codeTheme = "solarized-light"; + } + })(); + + %sveltekit.head% + + +
%sveltekit.body%
+ diff --git a/codeview-ui/src/cloudflare.d.ts b/codeview-ui/src/cloudflare.d.ts index 185c350..27e7f2c 100644 --- a/codeview-ui/src/cloudflare.d.ts +++ b/codeview-ui/src/cloudflare.d.ts @@ -2,36 +2,49 @@ // Generated by Wrangler by running `wrangler types --config=./wrangler.toml src/cloudflare.d.ts` (hash: ca1425fc6151bfc021b3aa361900d47e) // Runtime types generated with workerd@1.20260706.1 2026-07-08 nodejs_compat interface __BaseEnv_Env { - CRATE_GRAPHS: R2Bucket; - AUTH_DB: D1Database; - PARSE_REQUESTS: Queue; - RATE_LIMIT_API: RateLimit; - RATE_LIMIT_PARSE_ANON: RateLimit; - RATE_LIMIT_PARSE_AUTH: RateLimit; - ASSETS: Fetcher; - BETTER_AUTH_URL: "https://codeview.codes"; - GITHUB_OAUTH_CLIENT_ID: "Ov23liaAIxx0Vmp8F0zE"; - GITHUB_ADMIN_LOGINS: "themixednuts"; - GITHUB_REPO: "themixednuts/codeview"; - GITHUB_REF: "main"; - GITHUB_WORKFLOW_FILE: "parse.yml"; - PLAN_DRAIN_ACTIVE_TARGET: "4"; - PLAN_DRAIN_BATCH_SIZE: "0"; - GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT: "35"; - PARSE_STATUS: DurableObjectNamespace /* ParseStatusDurableObject from codeview-parser */; + CRATE_GRAPHS: R2Bucket; + AUTH_DB: D1Database; + PARSE_REQUESTS: Queue; + RATE_LIMIT_API: RateLimit; + RATE_LIMIT_PARSE_ANON: RateLimit; + RATE_LIMIT_PARSE_AUTH: RateLimit; + ASSETS: Fetcher; + BETTER_AUTH_URL: "https://codeview.codes"; + GITHUB_OAUTH_CLIENT_ID: "Ov23liaAIxx0Vmp8F0zE"; + GITHUB_ADMIN_LOGINS: "themixednuts"; + GITHUB_REPO: "themixednuts/codeview"; + GITHUB_REF: "main"; + GITHUB_WORKFLOW_FILE: "parse.yml"; + PLAN_DRAIN_ACTIVE_TARGET: "4"; + PLAN_DRAIN_BATCH_SIZE: "0"; + GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT: "35"; + PARSE_STATUS: DurableObjectNamespace /* ParseStatusDurableObject from codeview-parser */; } declare namespace Cloudflare { - interface GlobalProps { - mainModule: typeof import("../.svelte-kit/cloudflare/_worker"); - } - interface Env extends __BaseEnv_Env {} + interface GlobalProps { + mainModule: typeof import("../.svelte-kit/cloudflare/_worker"); + } + interface Env extends __BaseEnv_Env {} } interface Env extends __BaseEnv_Env {} type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; + [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; }; declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} + interface ProcessEnv extends StringifyValues< + Pick< + Cloudflare.Env, + | "BETTER_AUTH_URL" + | "GITHUB_OAUTH_CLIENT_ID" + | "GITHUB_ADMIN_LOGINS" + | "GITHUB_REPO" + | "GITHUB_REF" + | "GITHUB_WORKFLOW_FILE" + | "PLAN_DRAIN_ACTIVE_TARGET" + | "PLAN_DRAIN_BATCH_SIZE" + | "GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT" + > + > {} } // Begin runtime types @@ -58,63 +71,63 @@ declare var onmessage: never; * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) */ declare class DOMException extends Error { - constructor(message?: string, name?: string); - /** - * 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; - /** - * 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) - */ - readonly code: number; - static readonly INDEX_SIZE_ERR: number; - static readonly DOMSTRING_SIZE_ERR: number; - static readonly HIERARCHY_REQUEST_ERR: number; - static readonly WRONG_DOCUMENT_ERR: number; - static readonly INVALID_CHARACTER_ERR: number; - static readonly NO_DATA_ALLOWED_ERR: number; - static readonly NO_MODIFICATION_ALLOWED_ERR: number; - static readonly NOT_FOUND_ERR: number; - static readonly NOT_SUPPORTED_ERR: number; - static readonly INUSE_ATTRIBUTE_ERR: number; - static readonly INVALID_STATE_ERR: number; - static readonly SYNTAX_ERR: number; - static readonly INVALID_MODIFICATION_ERR: number; - static readonly NAMESPACE_ERR: number; - static readonly INVALID_ACCESS_ERR: number; - static readonly VALIDATION_ERR: number; - static readonly TYPE_MISMATCH_ERR: number; - static readonly SECURITY_ERR: number; - static readonly NETWORK_ERR: number; - static readonly ABORT_ERR: number; - static readonly URL_MISMATCH_ERR: number; - static readonly QUOTA_EXCEEDED_ERR: number; - static readonly TIMEOUT_ERR: number; - static readonly INVALID_NODE_TYPE_ERR: number; - static readonly DATA_CLONE_ERR: number; - get stack(): any; - set stack(value: any); + constructor(message?: string, name?: string); + /** + * 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; + /** + * 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) + */ + readonly code: number; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; + get stack(): any; + set stack(value: any); } type WorkerGlobalScopeEventMap = { - fetch: FetchEvent; - scheduled: ScheduledEvent; - queue: QueueEvent; - unhandledrejection: PromiseRejectionEvent; - rejectionhandled: PromiseRejectionEvent; + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; }; declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget; + EventTarget: typeof EventTarget; } /* 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). @@ -122,186 +135,197 @@ declare abstract class WorkerGlobalScope extends EventTarget; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - class Instance { - constructor(module: Module, imports?: Imports); - readonly exports: Exports; - } - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - class Memory { - constructor(descriptor: MemoryDescriptor); - readonly buffer: ArrayBuffer; - grow(delta: number): number; - } - type ImportExportKind = "function" | "global" | "memory" | "table"; - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[]; - static exports(module: Module): ModuleExportDescriptor[]; - static imports(module: Module): ModuleImportDescriptor[]; - } - type TableKind = "anyfunc" | "externref"; - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - class Table { - constructor(descriptor: TableDescriptor, value?: any); - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; - } - function instantiate(module: Module, imports?: Imports): Promise; - function validate(bytes: BufferSource): boolean; + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; } /** * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. @@ -310,94 +334,112 @@ declare namespace WebAssembly { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) */ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException; - WorkerGlobalScope: typeof WorkerGlobalScope; - btoa(data: string): string; - atob(data: string): string; - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; - setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - self: ServiceWorkerGlobalScope; - crypto: Crypto; - caches: CacheStorage; - scheduler: Scheduler; - performance: Performance; - Cloudflare: Cloudflare; - readonly origin: string; - Event: typeof Event; - ExtendableEvent: typeof ExtendableEvent; - CustomEvent: typeof CustomEvent; - PromiseRejectionEvent: typeof PromiseRejectionEvent; - FetchEvent: typeof FetchEvent; - TailEvent: typeof TailEvent; - TraceEvent: typeof TailEvent; - ScheduledEvent: typeof ScheduledEvent; - MessageEvent: typeof MessageEvent; - CloseEvent: typeof CloseEvent; - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; - ReadableStream: typeof ReadableStream; - WritableStream: typeof WritableStream; - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; - TransformStream: typeof TransformStream; - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; - CountQueuingStrategy: typeof CountQueuingStrategy; - ErrorEvent: typeof ErrorEvent; - MessageChannel: typeof MessageChannel; - MessagePort: typeof MessagePort; - EventSource: typeof EventSource; - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; - ReadableStreamDefaultController: typeof ReadableStreamDefaultController; - ReadableByteStreamController: typeof ReadableByteStreamController; - WritableStreamDefaultController: typeof WritableStreamDefaultController; - TransformStreamDefaultController: typeof TransformStreamDefaultController; - CompressionStream: typeof CompressionStream; - DecompressionStream: typeof DecompressionStream; - TextEncoderStream: typeof TextEncoderStream; - TextDecoderStream: typeof TextDecoderStream; - Headers: typeof Headers; - Body: typeof Body; - Request: typeof Request; - Response: typeof Response; - WebSocket: typeof WebSocket; - WebSocketPair: typeof WebSocketPair; - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; - AbortController: typeof AbortController; - AbortSignal: typeof AbortSignal; - TextDecoder: typeof TextDecoder; - TextEncoder: typeof TextEncoder; - navigator: Navigator; - Navigator: typeof Navigator; - URL: typeof URL; - URLSearchParams: typeof URLSearchParams; - URLPattern: typeof URLPattern; - Blob: typeof Blob; - File: typeof File; - FormData: typeof FormData; - Crypto: typeof Crypto; - SubtleCrypto: typeof SubtleCrypto; - CryptoKey: typeof CryptoKey; - CacheStorage: typeof CacheStorage; - Cache: typeof Cache; - FixedLengthStream: typeof FixedLengthStream; - IdentityTransformStream: typeof IdentityTransformStream; - HTMLRewriter: typeof HTMLRewriter; -} -declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; -declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + Cloudflare: Cloudflare; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + MessageChannel: typeof MessageChannel; + MessagePort: typeof MessagePort; + EventSource: typeof EventSource; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + TransformStreamDefaultController: typeof TransformStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | boolean, +): void; /** * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ -declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ declare function btoa(data: string): string; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ @@ -405,13 +447,21 @@ declare function atob(data: string): string; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ declare function clearTimeout(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ declare function clearInterval(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ @@ -421,245 +471,313 @@ declare function structuredClone(value: T, options?: StructuredSerializeOptio /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ declare function reportError(error: any): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +declare function fetch( + input: RequestInfo | URL, + init?: RequestInit, +): Promise; declare const self: ServiceWorkerGlobalScope; /** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ + * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. + * The Workers runtime implements the full surface of this API, but with some differences in + * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) + * compared to those implemented in most browsers. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) + */ declare const crypto: Crypto; /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ declare const caches: CacheStorage; declare const scheduler: Scheduler; /** -* 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/) -*/ + * 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 const performance: Performance; declare const Cloudflare: Cloudflare; declare const origin: string; declare const navigator: Navigator; -interface TestController { -} +interface TestController {} interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - cache?: CacheContext; - readonly access?: CloudflareAccessContext; - tracing: Tracing; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerConnectHandler = (socket: Socket, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - connect?: ExportedHandlerConnectHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; + waitUntil(promise: Promise): void; + passThroughOnException(): void; + readonly exports: Cloudflare.Exports; + readonly props: Props; + cache?: CacheContext; + readonly access?: CloudflareAccessContext; + tracing: Tracing; +} +type ExportedHandlerFetchHandler = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +type ExportedHandlerConnectHandler = ( + socket: Socket, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTailStreamHandler = ( + event: TailStream.TailEvent, + env: Env, + ctx: ExecutionContext, +) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +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[]; + transfer?: any[]; } declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean; - readonly userAgent: string; - readonly hardwareConcurrency: number; - readonly platform: string; - readonly language: string; - readonly languages: string[]; + sendBeacon(url: string, body?: BodyInit): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; + readonly platform: string; + readonly language: string; + readonly languages: string[]; } interface AlarmInvocationInfo { - readonly isRetry: boolean; - readonly retryCount: number; - readonly scheduledTime: number; + readonly isRetry: boolean; + readonly retryCount: number; + readonly scheduledTime: number; } interface Cloudflare { - readonly compatibilityFlags: Record; + readonly compatibilityFlags: Record; } interface CachePurgeError { - code: number; - message: string; + code: number; + message: string; } interface CachePurgeResult { - success: boolean; - errors: CachePurgeError[]; + success: boolean; + errors: CachePurgeError[]; } interface CachePurgeOptions { - tags?: string[]; - pathPrefixes?: string[]; - purgeEverything?: boolean; + tags?: string[]; + pathPrefixes?: string[]; + purgeEverything?: boolean; } interface CacheContext { - purge(options: CachePurgeOptions): Promise; + purge(options: CachePurgeOptions): Promise; } interface CloudflareAccessContext { - readonly aud: string; - getIdentity(): Promise; + readonly aud: string; + getIdentity(): Promise; } declare abstract class ColoLocalActorNamespace { - get(actorId: string): Fetcher; + 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?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher & { - readonly id: DurableObjectId; - readonly name?: string; + fetch(request: Request): Response | Promise; + connect?(socket: Socket): void | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +type DurableObjectStub = Fetcher< + T, + "alarm" | "connect" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; }; interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; - readonly jurisdiction?: string; -} -declare abstract class DurableObjectNamespace { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; + readonly jurisdiction?: string; +} +declare abstract class DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + getByName( + name: string, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; } type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us"; interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me"; + jurisdiction?: DurableObjectJurisdiction; +} +type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "apac-ne" + | "apac-se" + | "oc" + | "afr" + | "me"; type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { + locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; } +interface 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[]; - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; - getHibernatableWebSocketEventTimeout(): number | null; - getTags(ws: WebSocket): string[]; - abort(reason?: string): void; + 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[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; } interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; } interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + kv: SyncKvStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; } interface DurableObjectListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; - allowConcurrency?: boolean; - noCache?: boolean; + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; + allowConcurrency?: boolean; } interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; } interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; } declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; + constructor(request: string, response: string); + 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; + 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; + id?: DurableObjectId | string; + class: DurableObjectClass; } interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; + writeDataPoint(event?: AnalyticsEngineDataPoint): void; } interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; } /** * The **`Event`** interface represents an event which takes place on an `EventTarget`. @@ -667,171 +785,181 @@ interface AnalyticsEngineDataPoint { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ declare class Event { - constructor(type: string, init?: EventInit); - /** - * 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; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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) - */ - composedPath(): EventTarget[]; - static readonly NONE: number; - static readonly CAPTURING_PHASE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; + constructor(type: string, init?: EventInit); + /** + * 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; + /** + * The **`eventPhase`** read-only property of the being evaluated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; } interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; } type EventListener = (event: EventType) => void; interface EventListenerObject { - handleEvent(event: EventType): void; + handleEvent(event: EventType): void; } -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +type EventListenerOrEventListenerObject = + | EventListener + | EventListenerObject; /** * 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(); - /** - * 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) - */ - addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean; + constructor(); + /** + * 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) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | boolean, + ): void; + /** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; } interface EventTargetEventListenerOptions { - capture?: boolean; + capture?: boolean; } interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; } interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; + handleEvent: (event: Event) => any | undefined; } /** * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. @@ -839,19 +967,19 @@ interface EventTargetHandlerObject { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) */ declare class AbortController { - constructor(); - /** - * 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; - /** - * 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; + constructor(); + /** + * 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; + /** + * 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; } /** * 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. @@ -859,52 +987,52 @@ declare class AbortController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) */ declare abstract class AbortSignal extends EventTarget { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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); - /** - * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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); + /** + * 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 { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; } interface SchedulerWaitOptions { - signal?: AbortSignal; + signal?: AbortSignal; } /** * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. @@ -912,12 +1040,12 @@ interface SchedulerWaitOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ declare abstract class ExtendableEvent extends Event { - /** - * 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; + /** + * 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; } /** * The **`CustomEvent`** interface represents events initialized by an application for any purpose. @@ -925,19 +1053,19 @@ declare abstract class ExtendableEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit); - /** - * 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) - */ - get detail(): T; + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * 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) + */ + get detail(): T; } interface CustomEventCustomEventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; - detail?: any; + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; } /** * 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. @@ -945,52 +1073,52 @@ interface CustomEventCustomEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ declare class Blob { - 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + type?: string; } /** * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. @@ -998,84 +1126,98 @@ interface BlobOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ declare class File extends Blob { - constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); - /** - * 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; - /** - * 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; + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** + * 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; + /** + * 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 { - type?: string; - lastModified?: number; + type?: string; + lastModified?: number; } /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ declare abstract class CacheStorage { - /** - * 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; + /** + * 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; } /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise; } interface CacheQueryOptions { - ignoreMethod?: boolean; + ignoreMethod?: boolean; } /** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ + * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. + * The Workers runtime implements the full surface of this API, but with some differences in + * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) + * compared to those implemented in most browsers. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) + */ 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; - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues(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) - */ - randomUUID(): string; - DigestStream: typeof DigestStream; + /** + * 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; + /** + * 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 + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | 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) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; } /** * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. @@ -1084,79 +1226,132 @@ declare abstract class Crypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) */ declare abstract class SubtleCrypto { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * 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; - /** - * 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, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * 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; - /** - * 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; - /** - * 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, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** + * 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; + /** + * 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, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** + * 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; + /** + * 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; + /** + * 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, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; } /** * 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. @@ -1165,133 +1360,139 @@ declare abstract class SubtleCrypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) */ declare abstract class CryptoKey { - /** - * 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; - /** - * 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; - /** - * 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 | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; - /** - * 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[]; + /** + * 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; + /** + * 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; + /** + * 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 + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** + * 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 { - publicKey: CryptoKey; - privateKey: CryptoKey; + publicKey: CryptoKey; + privateKey: CryptoKey; } interface JsonWebKey { - kty: string; - use?: string; - key_ops?: string[]; - alg?: string; - ext?: boolean; - crv?: string; - x?: string; - y?: string; - d?: string; - n?: string; - e?: string; - p?: string; - q?: string; - dp?: string; - dq?: string; - qi?: string; - oth?: RsaOtherPrimesInfo[]; - k?: string; + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; } interface RsaOtherPrimesInfo { - r?: string; - d?: string; - t?: string; + r?: string; + d?: string; + t?: string; } interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: (ArrayBuffer | ArrayBufferView); - iterations?: number; - hash?: (string | SubtleCryptoHashAlgorithm); - $public?: CryptoKey; - info?: (ArrayBuffer | ArrayBufferView); + name: string; + salt?: ArrayBuffer | ArrayBufferView; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer | ArrayBufferView; } interface SubtleCryptoEncryptAlgorithm { - name: string; - iv?: (ArrayBuffer | ArrayBufferView); - additionalData?: (ArrayBuffer | ArrayBufferView); - tagLength?: number; - counter?: (ArrayBuffer | ArrayBufferView); - length?: number; - label?: (ArrayBuffer | ArrayBufferView); + name: string; + iv?: ArrayBuffer | ArrayBufferView; + additionalData?: ArrayBuffer | ArrayBufferView; + tagLength?: number; + counter?: ArrayBuffer | ArrayBufferView; + length?: number; + label?: ArrayBuffer | ArrayBufferView; } interface SubtleCryptoGenerateKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - modulusLength?: number; - publicExponent?: (ArrayBuffer | ArrayBufferView); - length?: number; - namedCurve?: string; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer | ArrayBufferView; + length?: number; + namedCurve?: string; } interface SubtleCryptoHashAlgorithm { - name: string; + name: string; } interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - length?: number; - namedCurve?: string; - compressed?: boolean; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; } interface SubtleCryptoSignAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - dataLength?: number; - saltLength?: number; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; } interface CryptoKeyKeyAlgorithm { - name: string; + name: string; } interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; + name: string; + length: number; } interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; } interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; } interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; + name: string; + namedCurve: string; } interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; } declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; + get bytesWritten(): number | bigint; } /** * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. @@ -1299,16 +1500,16 @@ declare class DigestStream extends WritableStream * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) */ declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions); - /** - * 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) - */ - decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * 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) + */ + decode(input?: ArrayBuffer | ArrayBufferView, options?: TextDecoderDecodeOptions): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } /** * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. @@ -1316,31 +1517,31 @@ declare class TextDecoder { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) */ declare class TextEncoder { - constructor(); - /** - * 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; - /** - * 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: Uint8Array): TextEncoderEncodeIntoResult; - get encoding(): string; + constructor(); + /** + * 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; + /** + * 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: Uint8Array): TextEncoderEncodeIntoResult; + get encoding(): string; } interface TextDecoderConstructorOptions { - fatal: boolean; - ignoreBOM: boolean; + fatal: boolean; + ignoreBOM: boolean; } interface TextDecoderDecodeOptions { - stream: boolean; + stream: boolean; } interface TextEncoderEncodeIntoResult { - read: number; - written: number; + read: number; + written: number; } /** * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. @@ -1348,44 +1549,44 @@ interface TextEncoderEncodeIntoResult { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) */ declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + constructor(type: string, init?: ErrorEventErrorEventInit); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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 { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; } /** * The **`MessageEvent`** interface represents a message received by a target object. @@ -1393,40 +1594,40 @@ interface ErrorEventErrorEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) */ declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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) - */ - readonly ports: MessagePort[]; + constructor(type: string, initializer: MessageEventInit); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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) + */ + readonly ports: MessagePort[]; } interface MessageEventInit { - data: ArrayBuffer | string; + data: ArrayBuffer | string; } /** * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. @@ -1434,18 +1635,18 @@ interface MessageEventInit { * [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 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. @@ -1453,151 +1654,148 @@ declare abstract class PromiseRejectionEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ declare class FormData { - constructor(); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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 - ]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator<(File | string)>; - forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: File | string - ]>; + constructor(); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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]>; + /* Returns a list of keys in the list. */ + keys(): IterableIterator; + /* Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: (this: This, value: File | string, key: string, parent: FormData) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; } interface ContentOptions { - html?: boolean; + html?: boolean; } declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; + constructor(); + on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; } interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; } interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; } interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; } interface Element { - tagName: string; - readonly attributes: IterableIterator; - readonly removed: boolean; - readonly namespaceURI: string; - getAttribute(name: string): string | null; - hasAttribute(name: string): boolean; - setAttribute(name: string, value: string): Element; - removeAttribute(name: string): Element; - before(content: string | ReadableStream | Response, options?: ContentOptions): Element; - after(content: string | ReadableStream | Response, options?: ContentOptions): Element; - prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; - append(content: string | ReadableStream | Response, options?: ContentOptions): Element; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; - remove(): Element; - removeAndKeepContent(): Element; - setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; - onEndTag(handler: (tag: EndTag) => void | Promise): void; + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string | ReadableStream | Response, options?: ContentOptions): Element; + after(content: string | ReadableStream | Response, options?: ContentOptions): Element; + prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; + append(content: string | ReadableStream | Response, options?: ContentOptions): Element; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; } interface EndTag { - name: string; - before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - remove(): EndTag; + name: string; + before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + remove(): EndTag; } interface Comment { - text: string; - readonly removed: boolean; - before(content: string, options?: ContentOptions): Comment; - after(content: string, options?: ContentOptions): Comment; - replace(content: string, options?: ContentOptions): Comment; - remove(): Comment; + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; } interface Text { - readonly text: string; - readonly lastInTextNode: boolean; - readonly removed: boolean; - before(content: string | ReadableStream | Response, options?: ContentOptions): Text; - after(content: string | ReadableStream | Response, options?: ContentOptions): Text; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; - remove(): Text; + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string | ReadableStream | Response, options?: ContentOptions): Text; + after(content: string | ReadableStream | Response, options?: ContentOptions): Text; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; + remove(): Text; } interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd; + append(content: string, options?: ContentOptions): DocumentEnd; } /** * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. @@ -1605,19 +1803,19 @@ interface DocumentEnd { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) */ declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * 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; + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ + readonly request: Request; + /** + * 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; /** @@ -1626,77 +1824,83 @@ type HeadersInit = Headers | Iterable> | Record * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) */ declare class Headers { - constructor(init?: HeadersInit); - /** - * 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[]; - /** - * 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[]; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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, thisArg?: This): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable | AsyncIterable; + constructor(init?: HeadersInit); + /** + * 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[]; + /** + * 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[]; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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, + thisArg?: This, + ): void; + /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData + | Iterable + | AsyncIterable; declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; } /** * The **`Response`** interface of the Fetch API represents the response to a request. @@ -1704,11 +1908,11 @@ declare abstract class Body { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ declare var Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; - json(any: any, maybeInit?: (ResponseInit | Response)): Response; + prototype: Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; + json(any: any, maybeInit?: ResponseInit | Response): Response; }; /** * The **`Response`** interface of the Fetch API represents the response to a request. @@ -1716,74 +1920,79 @@ declare var Response: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ interface Response extends Body { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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"; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ + headers: Headers; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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 { - status?: number; - statusText?: string; - headers?: HeadersInit; - cf?: any; - webSocket?: (WebSocket | null); - encodeBody?: "automatic" | "manual"; + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; } -type RequestInfo> = Request | string; +type RequestInfo> = + | Request + | string; /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ declare var Request: { - prototype: Request; - new >(input: RequestInfo | URL, init?: RequestInit): Request; + prototype: Request; + new >( + input: RequestInfo | URL, + init?: RequestInit, + ): Request; }; /** * The **`Request`** interface of the Fetch API represents a resource request. @@ -1791,498 +2000,606 @@ declare var Request: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ interface Request> extends Body { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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" | "no-cache"; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * The **`headers`** read-only property of the with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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" | "no-cache"; } interface RequestInit { - /* A string to set request's method. */ - method?: string; - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string; - fetcher?: (Fetcher | null); - cf?: Cf; - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - 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. */ - signal?: (AbortSignal | null); - encodeResponseBody?: "automatic" | "manual"; -} -type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; + /* A string to set request's method. */ + method?: string; + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /* A string indicating how the request will interact with the browser's cache to set request's cache. */ + 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. */ + signal?: AbortSignal | null; + encodeResponseBody?: "automatic" | "manual"; +} +type Service< + T extends + | (new (...args: any[]) => Rpc.WorkerEntrypointBranded) + | Rpc.WorkerEntrypointBranded + | ExportedHandler + | undefined = undefined, +> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded + ? Fetcher> + : T extends Rpc.WorkerEntrypointBranded + ? Fetcher + : T extends Exclude + ? never + : Fetcher; +type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; }; interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; + name: Key; + expiration?: number; + metadata?: Metadata; +} +type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: "text"): Promise; - get(key: Key, type: "json"): Promise; - get(key: Key, type: "arrayBuffer"): Promise; - get(key: Key, type: "stream"): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; - get(key: Array, type: "text"): Promise>; - get(key: Array, type: "json"): Promise>; - get(key: Array, options?: Partial>): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; - list(options?: KVNamespaceListOptions): Promise>; - put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; - getWithMetadata(key: Key, options?: Partial>): Promise>; - getWithMetadata(key: Key, type: "text"): Promise>; - getWithMetadata(key: Key, type: "json"): Promise>; - getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; - getWithMetadata(key: Key, type: "stream"): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; - getWithMetadata(key: Array, type: "text"): Promise>>; - getWithMetadata(key: Array, type: "json"): Promise>>; - getWithMetadata(key: Array, options?: Partial>): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; - delete(key: Key): Promise; + get(key: Key, options?: Partial>): Promise; + get(key: Key, type: "text"): Promise; + get(key: Key, type: "json"): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; + get(key: Array, type: "text"): Promise>; + get( + key: Array, + type: "json", + ): Promise>; + get( + key: Array, + options?: Partial>, + ): Promise>; + get( + key: Array, + options?: KVNamespaceGetOptions<"text">, + ): Promise>; + get( + key: Array, + options?: KVNamespaceGetOptions<"json">, + ): Promise>; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + getWithMetadata( + key: Array, + type: "text", + ): Promise>>; + getWithMetadata( + key: Array, + type: "json", + ): Promise>>; + getWithMetadata( + key: Array, + options?: Partial>, + ): Promise>>; + getWithMetadata( + key: Array, + options?: KVNamespaceGetOptions<"text">, + ): Promise>>; + getWithMetadata( + key: Array, + options?: KVNamespaceGetOptions<"json">, + ): Promise>>; + delete(key: Key): Promise; } interface KVNamespaceListOptions { - limit?: number; - prefix?: (string | null); - cursor?: (string | null); + limit?: number; + prefix?: string | null; + cursor?: string | null; } interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; + type: Type; + cacheTtl?: number; } interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); + expiration?: number; + expirationTtl?: number; + metadata?: any | null; } interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; } type QueueContentType = "text" | "bytes" | "json" | "v8"; interface Queue { - metrics(): Promise; - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; + metrics(): Promise; + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; } interface QueueSendMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; } interface QueueSendMetadata { - metrics: QueueSendMetrics; + metrics: QueueSendMetrics; } interface QueueSendResponse { - metadata: QueueSendMetadata; + metadata: QueueSendMetadata; } interface QueueSendBatchMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; } interface QueueSendBatchMetadata { - metrics: QueueSendBatchMetrics; + metrics: QueueSendBatchMetrics; } interface QueueSendBatchResponse { - metadata: QueueSendBatchMetadata; + metadata: QueueSendBatchMetadata; } interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueSendBatchOptions { - delaySeconds?: number; + delaySeconds?: number; } interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; } interface MessageBatchMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; } interface MessageBatchMetadata { - metrics: MessageBatchMetrics; + metrics: MessageBatchMetrics; } interface QueueRetryOptions { - delaySeconds?: number; + delaySeconds?: number; } interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; } interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - readonly metadata: MessageBatchMetadata; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; + 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; + readonly messages: readonly Message[]; + readonly queue: string; + readonly metadata: MessageBatchMetadata; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; } interface R2Error extends Error { - readonly name: string; - readonly code: number; - readonly message: string; - readonly action: string; - readonly stack: any; + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; } interface R2ListOptions { - limit?: number; - prefix?: string; - cursor?: string; - delimiter?: string; - startAfter?: string; - include?: ("httpMetadata" | "customMetadata")[]; + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; } interface R2Bucket { - head(key: string): Promise; - get(key: string, options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - get(key: string, options?: R2GetOptions): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; } interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + options?: R2UploadPartOptions, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; } interface R2UploadedPart { - partNumber: number; - etag: string; + partNumber: number; + etag: string; } declare abstract class R2Object { - readonly key: string; - readonly version: string; - readonly size: number; - readonly etag: string; - readonly httpEtag: string; - readonly checksums: R2Checksums; - readonly uploaded: Date; - readonly httpMetadata?: R2HTTPMetadata; - readonly customMetadata?: Record; - readonly range?: R2Range; - readonly storageClass: string; - readonly ssecKeyMd5?: string; - writeHttpMetadata(headers: Headers): void; + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + readonly ssecKeyMd5?: string; + writeHttpMetadata(headers: Headers): void; } interface R2ObjectBody extends R2Object { - get body(): ReadableStream; - get bodyUsed(): boolean; - arrayBuffer(): Promise; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -type R2Range = { - offset: number; - length?: number; -} | { - offset?: number; - length: number; -} | { - suffix: number; -}; + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + bytes(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; } interface R2GetOptions { - onlyIf?: (R2Conditional | Headers); - range?: (R2Range | Headers); - ssecKey?: (ArrayBuffer | string); + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; + ssecKey?: ArrayBuffer | string; } interface R2PutOptions { - onlyIf?: (R2Conditional | Headers); - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - md5?: ((ArrayBuffer | ArrayBufferView) | string); - sha1?: ((ArrayBuffer | ArrayBufferView) | string); - sha256?: ((ArrayBuffer | ArrayBufferView) | string); - sha384?: ((ArrayBuffer | ArrayBufferView) | string); - sha512?: ((ArrayBuffer | ArrayBufferView) | string); - storageClass?: string; - ssecKey?: (ArrayBuffer | string); + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: (ArrayBuffer | ArrayBufferView) | string; + sha1?: (ArrayBuffer | ArrayBufferView) | string; + sha256?: (ArrayBuffer | ArrayBufferView) | string; + sha384?: (ArrayBuffer | ArrayBufferView) | string; + sha512?: (ArrayBuffer | ArrayBufferView) | string; + storageClass?: string; + ssecKey?: ArrayBuffer | string; } interface R2MultipartOptions { - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - storageClass?: string; - ssecKey?: (ArrayBuffer | string); + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; + ssecKey?: ArrayBuffer | string; } interface R2Checksums { - readonly md5?: ArrayBuffer; - readonly sha1?: ArrayBuffer; - readonly sha256?: ArrayBuffer; - readonly sha384?: ArrayBuffer; - readonly sha512?: ArrayBuffer; - toJSON(): R2StringChecksums; + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; } interface R2StringChecksums { - md5?: string; - sha1?: string; - sha256?: string; - sha384?: string; - sha512?: string; + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; } interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; } type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ({ - truncated: true; - cursor: string; -} | { - truncated: false; -}); + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); interface R2UploadPartOptions { - ssecKey?: (ArrayBuffer | string); + ssecKey?: ArrayBuffer | string; } declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface QueuingStrategy { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; } interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; } interface UnderlyingByteSource { - type: "bytes"; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; } interface UnderlyingSource { - type?: "" | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: (number | bigint); + type?: "" | undefined; + start?: (controller: ReadableStreamDefaultController) => void | Promise; + pull?: (controller: ReadableStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; } interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number; + readableType?: string; + writableType?: string; + start?: (controller: TransformStreamDefaultController) => void | Promise; + transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; + flush?: (controller: TransformStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + 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. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - signal?: AbortSignal; -} -type ReadableStreamReadResult = { - done: false; - value: R; -} | { - done: true; - value?: undefined; -}; + 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + signal?: AbortSignal; +} +type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; /** * 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 { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; } /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. @@ -2290,9 +2607,15 @@ interface ReadableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ declare const ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; }; /** * 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). @@ -2300,21 +2623,21 @@ declare const ReadableStream: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * 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>; - /** - * 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; + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * 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>; + /** + * 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; } /** * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. @@ -2322,33 +2645,36 @@ declare class ReadableStreamDefaultReader { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * 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>; - /** - * 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, view: T): Promise>; + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * 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>; + /** + * 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, + view: T, + ): Promise>; } interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number; + min?: number; } interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: "byob"; + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; } /** * 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). @@ -2356,25 +2682,25 @@ interface ReadableStreamGetReaderOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ declare abstract class ReadableStreamBYOBRequest { - /** - * 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; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; + /** + * 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; } /** * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. @@ -2382,30 +2708,30 @@ declare abstract class ReadableStreamBYOBRequest { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ declare abstract class ReadableStreamDefaultController { - /** - * 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; - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ + close(): void; + /** + * 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; + /** + * 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; } /** * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. @@ -2413,36 +2739,36 @@ declare abstract class ReadableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ declare abstract class ReadableByteStreamController { - /** - * 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; - /** - * 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; - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ + close(): void; + /** + * 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; + /** + * 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; } /** * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. @@ -2450,18 +2776,18 @@ declare abstract class ReadableByteStreamController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) */ declare abstract class WritableStreamDefaultController { - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; } /** * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. @@ -2469,39 +2795,39 @@ declare abstract class WritableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ declare abstract class TransformStreamDefaultController { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -2509,31 +2835,31 @@ interface ReadableWritablePair { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) */ declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /** - * 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; - /** - * 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; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * 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; + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /** + * 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; + /** + * 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; + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ + close(): Promise; + /** + * 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; } /** * 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. @@ -2541,49 +2867,49 @@ declare class WritableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) */ declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void; + constructor(stream: WritableStream); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ + close(): Promise; + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ + write(chunk?: W): Promise; + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ + releaseLock(): void; } /** * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. @@ -2591,31 +2917,41 @@ declare class WritableStreamDefaultWriter { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ declare class TransformStream { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /** - * 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; - /** - * 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; + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** + * 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; + /** + * 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 { - constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); } -declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); } interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); + highWaterMark?: number | bigint; } interface ReadableStreamValuesOptions { - preventCancel?: boolean; + preventCancel?: boolean; } /** * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. @@ -2623,15 +2959,18 @@ interface ReadableStreamValuesOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); + constructor(format: "gzip" | "deflate" | "deflate-raw"); } /** * 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 { - constructor(format: "gzip" | "deflate" | "deflate-raw"); +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); } /** * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. @@ -2639,8 +2978,8 @@ declare class DecompressionStream extends TransformStream { - constructor(); - get encoding(): string; + constructor(); + get encoding(): string; } /** * 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. @@ -2648,14 +2987,14 @@ declare class TextEncoderStream extends TransformStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ declare class TextDecoderStream extends TransformStream { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; + fatal?: boolean; + ignoreBOM?: boolean; } /** * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. @@ -2663,15 +3002,15 @@ interface TextDecoderStreamTextDecoderStreamInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) */ declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * 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; + constructor(init: QueuingStrategyInit); + /** + * 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; } /** * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. @@ -2679,137 +3018,151 @@ declare class ByteLengthQueuingStrategy implements QueuingStrategy number; + constructor(init: QueuingStrategyInit); + /** + * 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; } interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; } interface TracePreviewInfo { - id: string; - slug: string; - name: string; + id: string; + slug: string; + name: string; } interface ScriptVersion { - id?: string; - tag?: string; - message?: string; + id?: string; + tag?: string; + message?: string; } declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; + readonly events: TraceItem[]; + readonly traces: TraceItem[]; } interface TraceItem { - readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; - readonly eventTimestamp: number | null; - readonly logs: TraceLog[]; - readonly exceptions: TraceException[]; - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; - readonly scriptName: string | null; - readonly entrypoint?: string; - 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; - readonly cpuTime: number; - readonly wallTime: number; + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemConnectEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + 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; + readonly cpuTime: number; + readonly wallTime: number; } interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date; -} -interface TraceItemConnectEventInfo { -} -interface TraceItemCustomEventInfo { + readonly scheduledTime: Date; } +interface TraceItemConnectEventInfo {} +interface TraceItemCustomEventInfo {} interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; + readonly scheduledTime: number; + readonly cron: string; } interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; + readonly queue: string; + readonly batchSize: number; } interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; } interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; } interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; + readonly scriptName: string | null; } interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoResponse { - readonly status: number; + readonly status: number; } interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; + readonly rpcMethod: string; } interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; } interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; } interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; + readonly timestamp: number; + readonly level: string; + readonly message: any; } interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; } interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; + readonly timestamp: number; + readonly channel: string; + readonly message: any; } interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; + readonly cpuTime: number; + readonly wallTime: number; } interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; + fromTrace(item: TraceItem): TraceMetrics; } /** * The **`URL`** interface is used to parse, construct, normalize, and encode URL. @@ -2817,171 +3170,171 @@ interface UnsafeTraceMetrics { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) */ declare class URL { - constructor(url: string | URL, base?: string | URL); - /** - * 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; - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + constructor(url: string | URL, base?: string | URL); + /** + * 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; + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; } /** * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. @@ -2989,114 +3342,115 @@ declare class URL { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ declare class URLSearchParams { - constructor(init?: (Iterable> | Record | string)); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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[]; - /** - * 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; - /** - * 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; - /** - * 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 - ]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; - /*function toString() { [native code] }*/ - toString(): string; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; + constructor(init?: Iterable> | Record | string); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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[]; + /** + * 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; + /** + * 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; + /** + * 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]>; + /* Returns a list of keys in the search params. */ + keys(): IterableIterator; + /* Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, + thisArg?: This, + ): void; + /*function toString() { [native code] }*/ + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; } declare class URLPattern { - constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; + constructor( + input?: string | URLPatternInit, + baseURL?: string | URLPatternOptions, + patternOptions?: URLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + get hasRegExpGroups(): boolean; + test(input?: string | URLPatternInit, baseURL?: string): boolean; + exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; } interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; } interface URLPatternComponentResult { - input: string; - groups: Record; + input: string; + groups: Record; } interface URLPatternResult { - inputs: (string | URLPatternInit)[]; - protocol: URLPatternComponentResult; - username: URLPatternComponentResult; - password: URLPatternComponentResult; - hostname: URLPatternComponentResult; - port: URLPatternComponentResult; - pathname: URLPatternComponentResult; - search: URLPatternComponentResult; - hash: URLPatternComponentResult; + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; } interface URLPatternOptions { - ignoreCase?: boolean; + ignoreCase?: boolean; } /** * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. @@ -3104,36 +3458,36 @@ interface URLPatternOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) */ declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit); - /** - * 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; - /** - * 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; - /** - * 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) - */ - readonly wasClean: boolean; + constructor(type: string, initializer?: CloseEventInit); + /** + * 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; + /** + * 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; + /** + * 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) + */ + readonly wasClean: boolean; } interface CloseEventInit { - code?: number; - reason?: string; - wasClean?: boolean; + code?: number; + reason?: string; + wasClean?: boolean; } type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; }; /** * 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. @@ -3141,16 +3495,16 @@ type WebSocketEventMap = { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ declare var WebSocket: { - prototype: WebSocket; - new (url: string, protocols?: (string[] | string)): WebSocket; - readonly READY_STATE_CONNECTING: number; - readonly CONNECTING: number; - readonly READY_STATE_OPEN: number; - readonly OPEN: number; - readonly READY_STATE_CLOSING: number; - readonly CLOSING: number; - readonly READY_STATE_CLOSED: number; - readonly CLOSED: number; + prototype: WebSocket; + new (url: string, protocols?: string[] | string): WebSocket; + readonly READY_STATE_CONNECTING: number; + readonly CONNECTING: number; + readonly READY_STATE_OPEN: number; + readonly OPEN: number; + readonly READY_STATE_CLOSING: number; + readonly CLOSING: number; + readonly READY_STATE_CLOSED: number; + readonly CLOSED: number; }; /** * 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. @@ -3158,118 +3512,122 @@ declare var WebSocket: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(options?: WebSocketAcceptOptions): void; - /** - * 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; - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void; - serializeAttachment(attachment: any): void; - deserializeAttachment(): any | null; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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"; + accept(options?: WebSocketAcceptOptions): void; + /** + * 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; + /** + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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 (): { - 0: WebSocket; - 1: WebSocket; - }; + new (): { + 0: WebSocket; + 1: WebSocket; + }; }; interface SqlStorage { - exec>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement { -} + exec>( + query: string, + ...bindings: any[] + ): SqlStorageCursor; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement {} type SqlStorageValue = ArrayBuffer | string | number | null; declare abstract class SqlStorageCursor> { - next(): { + next(): + | { done?: false; value: T; - } | { + } + | { done: true; value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; + }; + toArray(): T[]; + one(): T; + raw(): IterableIterator; + columnNames: string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator; } interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): "on" | "off" | "starttls"; - close(): Promise; - startTls(options?: TlsOptions): Socket; + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + get upgraded(): boolean; + get secureTransport(): "on" | "off" | "starttls"; + close(): Promise; + startTls(options?: TlsOptions): Socket; } interface SocketOptions { - secureTransport?: string; - allowHalfOpen: boolean; - highWaterMark?: (number | bigint); + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: number | bigint; } interface SocketAddress { - hostname: string; - port: number; + hostname: string; + port: number; } interface TlsOptions { - expectedServerHostname?: string; + expectedServerHostname?: string; } interface SocketInfo { - remoteAddress?: string; - localAddress?: string; + remoteAddress?: string; + localAddress?: string; } /** * The **`EventSource`** interface is web content's interface to server-sent events. @@ -3277,118 +3635,120 @@ interface SocketInfo { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * The **`readyState`** read-only property of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; } interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; + withCredentials?: boolean; + fetcher?: Fetcher; } interface ExecOutput { - readonly stdout: ArrayBuffer; - readonly stderr: ArrayBuffer; - readonly exitCode: number; + 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"; + 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; + 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; - monitor(): Promise; - 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; + get running(): boolean; + start(options?: ContainerStartupOptions): void; + monitor(): Promise; + 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; + id: string; + size: number; + dir: string; + name?: string; } interface ContainerDirectorySnapshotOptions { - dir: string; - name?: string; + dir: string; + name?: string; } interface ContainerDirectorySnapshotRestoreParams { - snapshot: ContainerDirectorySnapshot; - mountPoint?: string; + snapshot: ContainerDirectorySnapshot; + mountPoint?: string; } interface ContainerSnapshot { - id: string; - size: number; - name?: string; + id: string; + size: number; + name?: string; } interface ContainerSnapshotOptions { - name?: string; + name?: string; } interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - labels?: Record; - directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; - containerSnapshot?: ContainerSnapshot; + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; + labels?: Record; + directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; + containerSnapshot?: ContainerSnapshot; } /** * 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. @@ -3396,26 +3756,26 @@ interface ContainerStartupOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ declare abstract class MessagePort extends EventTarget { - /** - * 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; - /** - * 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; - /** - * 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) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); + /** + * 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; + /** + * 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; + /** + * 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) + */ + start(): void; + 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. @@ -3423,119 +3783,142 @@ declare abstract class MessagePort extends EventTarget { * [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; + 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 LoopbackForExport 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 { -} + transfer?: any[]; +} +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; + 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; + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; } interface WorkerStub { - getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; - getDurableObjectClass(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass; + getEntrypoint( + name?: string, + options?: WorkerStubEntrypointOptions, + ): Fetcher; + getDurableObjectClass( + name?: string, + options?: WorkerStubEntrypointOptions, + ): DurableObjectClass; } interface WorkerStubEntrypointOptions { - props?: any; - limits?: workerdResourceLimits; + props?: any; + limits?: workerdResourceLimits; } interface WorkerLoader { - get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; - load(code: WorkerLoaderWorkerCode): WorkerStub; + 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; + 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[]; + 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; + cpuMs?: number; + subRequests?: number; } /** -* 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/) -*/ + * 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; + /* [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; } 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; + 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; } declare abstract class Span { - get isTraced(): boolean; - setAttribute(key: string, value?: (boolean | number | string)): void; - end(): void; + get isTraced(): boolean; + setAttribute(key: string, value?: boolean | number | string): void; + end(): void; } /** * Represents the identity of a user authenticated via Cloudflare Access. @@ -3546,41 +3929,41 @@ declare abstract class Span { * 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. */ + /** 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; - /** 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; + }>; + /** 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 @@ -3595,62 +3978,62 @@ type AgentMemoryThinkingLevel = "low" | "medium" | "high"; type AgentMemoryResponseLength = "short" | "medium" | "long"; /** A conversation message passed to ingest(). */ interface AgentMemoryMessage { - role: "system" | "user" | "assistant"; - content: string; - /** Optional message timestamp. */ - timestamp?: Date; + role: "system" | "user" | "assistant"; + content: string; + /** Optional message timestamp. */ + timestamp?: Date; } /** 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; + /** 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; - /** Memory text. */ - content: string; - /** Session that created this memory. */ - sessionId: string | null; - /** Memory creation time. */ - createdAt: Date; - /** Memory last-update time. */ - updatedAt: Date; + /** Memory ID. */ + id: string; + /** Memory type. */ + type: AgentMemoryMemoryType; + /** Text summary. */ + summary: string; + /** 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; + /** 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; } /** Options for the ingest() method. */ interface AgentMemoryIngestOptions { - /** Session identifier to associate with memories created during ingestion. */ - sessionId?: string | null | undefined; + /** Session identifier to associate with memories created during ingestion. */ + sessionId?: string | null | undefined; } /** Options for the getSummary() method. */ interface AgentMemoryGetSummaryOptions { - /** Session identifier to retrieve session summary for. */ - sessionId?: string | null | undefined; + /** Session identifier to retrieve session summary for. */ + sessionId?: string | null | undefined; } /** Response from the getSummary() method. */ interface AgentMemoryGetSummaryResponse { - /** Markdown summary. */ - summary: string; + /** Markdown summary. */ + summary: string; } /** * Options for the recall() method. @@ -3661,21 +4044,21 @@ interface AgentMemoryGetSummaryResponse { * ("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; + /** 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[]; + /** 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. @@ -3685,20 +4068,20 @@ interface AgentMemoryRecallResult { * 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; + /** 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; + memories: AgentMemoryMemoryListEntry[]; + /** Continuation cursor; absent when this page exhausted the result set. */ + cursor?: string; } /** * A single Agent Memory profile, scoped to a profile name. @@ -3706,70 +4089,70 @@ interface AgentMemoryListMemoriesResult { * 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; + /** + * 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. @@ -3789,500 +4172,505 @@ declare abstract class AgentMemoryProfile { * ``` */ 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; + /** + * 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 { -} +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; + role: "system" | "developer" | "user" | "assistant" | "tool"; + content: string | null; }; /** * 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'; - }; + 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; }; // ============ 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 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; + messages: AiSearchMessage[]; + model?: string; + stream?: boolean; + ai_search_options?: AiSearchOptions; + [key: string]: unknown; }; // ============ 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[]; + /** 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; -}; +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; +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; + 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[]; + 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 & { - ai_search_options: AiSearchMultiSearchOptions; +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[]; +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; - }; - 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; - }; - }>; + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + 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 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']; + 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; - }; + 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; + }; + }; }; // ============ 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'; + 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"; }>; - /** Sync interval in seconds. */ - sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; - metadata?: Record; - [key: string]: unknown; + } | 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; }; /** 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'; + 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 AiSearchListResponse = { - result: AiSearchInstanceInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; + result: AiSearchInstanceInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; }; // ============ 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'; + /** 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"; }>; - 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; + } | 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; }; // ============ 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; + 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 AiSearchItemContentResult = { - body: ReadableStream; - contentType: string; - filename: string; - size: number; + body: ReadableStream; + contentType: string; + filename: string; + size: number; }; type AiSearchUploadItemOptions = { - metadata?: Record; + metadata?: Record; }; 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; + 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; }; type AiSearchListItemsResponse = { - result: AiSearchItemInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; + 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; + /** 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; + 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; - }; + 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; + /** 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; - }; + 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; - }; + 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; + 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; + id: number; + message: string; + message_type: number; + created_at: number; }; type AiSearchCreateJobParams = { - description?: string; + description?: string; }; type AiSearchListJobsParams = { - page?: number; - per_page?: number; + page?: number; + per_page?: number; }; type AiSearchListJobsResponse = { - result: AiSearchJobInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; + result: AiSearchJobInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; }; type AiSearchJobLogsParams = { - page?: number; - per_page?: number; + page?: number; + per_page?: number; }; type AiSearchJobLogsResponse = { - result: AiSearchJobLog[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; + result: AiSearchJobLog[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; }; // ============ AI Search Sub-Service Classes ============ /** @@ -4290,109 +4678,117 @@ type AiSearchJobLogsResponse = { * Provides info, download, sync, logs, and chunks operations on a specific item. */ declare abstract class AiSearchItem { - /** Get metadata about this item. */ - info(): Promise; - /** - * Download the item's content. - * @returns Object with body stream, content type, filename, and size. - */ - 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; + /** Get metadata about this item. */ + info(): Promise; + /** + * Download the item's content. + * @returns Object with body stream, content type, filename, and size. + */ + 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; } /** * 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; + /** 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; } /** * 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; - /** - * Cancel a running job. - * @returns The updated job info. - * @throws AiSearchNotFoundError if the job does not exist. - */ - cancel(): Promise; + /** Get metadata about this job. */ + info(): Promise; + /** Get logs for this job. */ + logs(params?: AiSearchJobLogsParams): Promise; + /** + * Cancel a running job. + * @returns The updated job info. + * @throws AiSearchNotFoundError if the job does not exist. + */ + cancel(): Promise; } /** * 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; + /** 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; } // ============ AI Search Binding Classes ============ /** @@ -4419,43 +4815,45 @@ declare abstract class AiSearchJobs { * ``` */ 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; + /** + * 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; } /** * Namespace-level AI Search service. @@ -4490,449 +4888,476 @@ declare abstract class AiSearchInstance { * ``` */ 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; + /** + * 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 AiImageClassificationInput = { - image: number[]; + image: number[]; }; type AiImageClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; } 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[]; + 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; + description: string; }; declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; } 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[]; + 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; + description: string; }; declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiMultimodalEmbeddingsInput = { - image: string; - text: string[]; + image: string; + text: string[]; }; type AiIMultimodalEmbeddingsOutput = { - data: number[][]; - shape: number[]; + data: number[][]; + shape: number[]; }; declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiObjectDetectionInput = { - image: number[]; + image: number[]; }; type AiObjectDetectionOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; } type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; + source: string; + sentences: string[]; }; type AiSentenceSimilarityOutput = number[]; declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; } type AiAutomaticSpeechRecognitionInput = { - audio: number[]; + audio: number[]; }; type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; }; declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; } type AiSummarizationInput = { - input_text: string; - max_length?: number; + input_text: string; + max_length?: number; }; type AiSummarizationOutput = { - summary: string; + summary: string; }; declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; } type AiTextClassificationInput = { - text: string; + text: string; }; type AiTextClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; } type AiTextEmbeddingsInput = { - text: string | string[]; + text: string | string[]; }; type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; + shape: number[]; + data: number[][]; }; declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; } type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; + 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[]; + 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: "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; + name: string; + code: string; }; type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; + type: string; + json_schema?: any; }; 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[]; + 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 AiTextGenerationToolLegacyOutput = { - name: string; - arguments: unknown; + name: string; + arguments: unknown; }; type AiTextGenerationToolOutput = { - id: string; - type: "function"; - function: { - name: string; - arguments: string; - }; + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; }; type UsageTags = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; }; type AiTextGenerationOutput = { - response?: string; - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; - usage?: UsageTags; + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; }; declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; } type AiTextToSpeechInput = { - prompt: string; - lang?: string; -}; -type AiTextToSpeechOutput = Uint8Array | { - audio: string; + prompt: string; + lang?: string; }; +type AiTextToSpeechOutput = + | Uint8Array + | { + audio: string; + }; declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; + 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; + 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; + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; } type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; + text: string; + target_lang: string; + source_lang?: string; }; type AiTranslationOutput = { - translated_text?: string; + translated_text?: string; }; declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; } /** * Workers AI support for OpenAI's Chat Completions API */ type ChatCompletionContentPartText = { - type: "text"; - text: string; + type: "text"; + text: string; }; type ChatCompletionContentPartImage = { - type: "image_url"; - image_url: { - url: string; - detail?: "auto" | "low" | "high"; - }; + 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: "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: "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: "refusal"; + refusal: string; +}; +type ChatCompletionContentPart = + | ChatCompletionContentPartText + | ChatCompletionContentPartImage + | ChatCompletionContentPartInputAudio + | ChatCompletionContentPartFile; type FunctionDefinition = { - name: string; - description?: string; - parameters?: Record; - strict?: boolean | null; + name: string; + description?: string; + parameters?: Record; + strict?: boolean | null; }; type ChatCompletionFunctionTool = { - type: "function"; - function: FunctionDefinition; + type: "function"; + function: FunctionDefinition; }; type ChatCompletionCustomToolGrammarFormat = { - type: "grammar"; - grammar: { - definition: string; - syntax: "lark" | "regex"; - }; + type: "grammar"; + grammar: { + definition: string; + syntax: "lark" | "regex"; + }; }; type ChatCompletionCustomToolTextFormat = { - type: "text"; + type: "text"; }; -type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat; +type ChatCompletionCustomToolFormat = + | ChatCompletionCustomToolTextFormat + | ChatCompletionCustomToolGrammarFormat; type ChatCompletionCustomTool = { - type: "custom"; - custom: { - name: string; - description?: string; - format?: ChatCompletionCustomToolFormat; - }; + 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; - }; + id: string; + type: "function"; + function: { + name: string; + /** JSON-encoded arguments string. */ + arguments: string; + }; }; type ChatCompletionMessageCustomToolCall = { - id: string; - type: "custom"; - custom: { - name: string; - input: string; - }; + id: string; + type: "custom"; + custom: { + name: string; + input: string; + }; }; -type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall; +type ChatCompletionMessageToolCall = + | ChatCompletionMessageFunctionToolCall + | ChatCompletionMessageCustomToolCall; type ChatCompletionToolChoiceFunction = { - type: "function"; - function: { - name: string; - }; + type: "function"; + function: { + name: string; + }; }; type ChatCompletionToolChoiceCustom = { - type: "custom"; - custom: { - name: string; - }; + 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: "allowed_tools"; + allowed_tools: { + mode: "auto" | "required"; + tools: Array>; + }; +}; +type ChatCompletionToolChoiceOption = + | "none" + | "auto" + | "required" + | ChatCompletionToolChoiceFunction + | ChatCompletionToolChoiceCustom + | ChatCompletionToolChoiceAllowedTools; type DeveloperMessage = { - role: "developer"; - content: string | Array<{ + role: "developer"; + content: + | string + | Array<{ type: "text"; text: string; - }>; - name?: string; + }>; + name?: string; }; type SystemMessage = { - role: "system"; - content: string | Array<{ + role: "system"; + content: + | string + | Array<{ type: "text"; text: string; - }>; - name?: string; + }>; + name?: string; }; /** * Permissive merged content part used inside UserMessage arrays. @@ -4942,226 +5367,244 @@ type SystemMessage = { * 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: "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; + role: "user"; + content: string | Array; + name?: string; }; type AssistantMessageContentPart = { - type: "text" | "refusal"; - text?: string; - refusal?: string; + 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; - }; + 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<{ + role: "tool"; + content: + | string + | Array<{ type: "text"; text: string; - }>; - tool_call_id: string; + }>; + tool_call_id: string; }; type FunctionMessage = { - role: "function"; - content: string; - name: string; -}; -type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage; + role: "function"; + content: string; + name: string; +}; +type ChatCompletionMessageParam = + | DeveloperMessage + | SystemMessage + | UserMessage + | AssistantMessage + | ToolMessage + | FunctionMessage; type ChatCompletionsResponseFormatText = { - type: "text"; + type: "text"; }; type ChatCompletionsResponseFormatJSONObject = { - type: "json_object"; + type: "json_object"; }; type ResponseFormatJSONSchema = { - type: "json_schema"; - json_schema: { - name: string; - description?: string; - schema?: Record; - strict?: boolean | null; - }; + type: "json_schema"; + json_schema: { + name: string; + description?: string; + schema?: Record; + strict?: boolean | null; + }; }; -type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema; +type ResponseFormat = + | ChatCompletionsResponseFormatText + | ChatCompletionsResponseFormatJSONObject + | ResponseFormatJSONSchema; type ChatCompletionsStreamOptions = { - include_usage?: boolean; - include_obfuscation?: boolean; + include_usage?: boolean; + include_obfuscation?: boolean; }; type PredictionContent = { - type: "content"; - content: string | Array<{ + type: "content"; + content: + | string + | Array<{ type: "text"; text: string; - }>; + }>; }; type AudioParams = { - voice: string | { + voice: + | string + | { id: string; - }; - format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; + }; + format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; }; type WebSearchUserLocation = { - type: "approximate"; - approximate: { - city?: string; - country?: string; - region?: string; - timezone?: string; - }; + type: "approximate"; + approximate: { + city?: string; + country?: string; + region?: string; + timezone?: string; + }; }; type WebSearchOptions = { - search_context_size?: "low" | "medium" | "high"; - user_location?: WebSearchUserLocation; + 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; + /** 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" | { + 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; + }; + functions?: Array; }; type PromptTokensDetails = { - cached_tokens?: number; - audio_tokens?: number; + cached_tokens?: number; + audio_tokens?: number; }; type CompletionTokensDetails = { - reasoning_tokens?: number; - audio_tokens?: number; - accepted_prediction_tokens?: number; - rejected_prediction_tokens?: number; + 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; + 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; + token: string; + logprob: number; + bytes: Array | null; }; type ChatCompletionTokenLogprob = { - token: string; - logprob: number; - bytes: Array | null; - top_logprobs: Array; + 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; + 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: "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; + 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; + 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; + index: number; + message: ChatCompletionResponseMessage; + finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; + logprobs: ChatCompletionLogprobs | null; }; type ChatCompletionsMessagesInput = { - messages: Array; + 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; + 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 @@ -5174,444 +5617,509 @@ type ChatCompletionsOutput = { * 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; + 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; + 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"; + 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; + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; }; type ResponseIncompleteDetails = { - reason?: "max_output_tokens" | "content_filter"; + reason?: "max_output_tokens" | "content_filter"; }; type ResponsePrompt = { - id: string; - variables?: { - [key: string]: string | ResponseInputText | ResponseInputImage; - } | null; - version?: string | null; + 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; + 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"; + text: string; + type: "reasoning_text"; }; type ResponseConversationParam = { - id: string; + id: string; }; type ResponseCreatedEvent = { - response: Response; - sequence_number: number; - type: "response.created"; + response: Response; + sequence_number: number; + type: "response.created"; }; type ResponseCustomToolCallOutput = { - call_id: string; - output: string | Array; - type: "custom_tool_call_output"; - id?: string; + 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; + 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"; + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; }; type ResponseFailedEvent = { - response: Response; - sequence_number: number; - type: "response.failed"; + response: Response; + sequence_number: number; + type: "response.failed"; }; type ResponseFormatText = { - type: "text"; + type: "text"; }; type ResponseFormatJSONObject = { - type: "json_object"; + type: "json_object"; }; -type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextConfig = + | ResponseFormatText + | ResponseFormatTextJSONSchemaConfig + | ResponseFormatJSONObject; type ResponseFormatTextJSONSchemaConfig = { - name: string; - schema: { - [key: string]: unknown; - }; - type: "json_schema"; - description?: string; - strict?: boolean | null; + 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"; + 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"; + 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"; + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; }; interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { - id: string; + id: string; } type ResponseFunctionToolCallOutputItem = { - id: string; - call_id: string; - output: string | Array; - type: "function_call_output"; - status?: "in_progress" | "completed" | "incomplete"; + 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"; + response: Response; + sequence_number: number; + type: "response.incomplete"; }; type ResponseInput = Array; type ResponseInputContent = ResponseInputText | ResponseInputImage; type ResponseInputImage = { - detail: "low" | "high" | "auto"; - type: "input_image"; - /** - * Base64 encoded image - */ - image_url?: string | null; + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; }; type ResponseInputImageContent = { - type: "input_image"; - detail?: "low" | "high" | "auto" | null; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + 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; + 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"; + 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"; + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; }; type ResponseInputText = { - text: string; - type: "input_text"; + text: string; + type: "input_text"; }; type ResponseInputTextContent = { - text: string; - type: "input_text"; -}; -type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; + 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"; + 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"; + 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"; + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; }; type ResponseOutputRefusal = { - refusal: string; - type: "refusal"; + refusal: string; + type: "refusal"; }; type ResponseOutputText = { - text: string; - type: "output_text"; - logprobs?: Array; + 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"; + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; }; type ResponseReasoningSummaryItem = { - text: string; - type: "summary_text"; + text: string; + type: "summary_text"; }; type ResponseReasoningContentItem = { - text: string; - type: "reasoning_text"; + 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"; + 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"; + 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"; + 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; + 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"; + response: Response; + sequence_number: number; + type: "response.completed"; }; type ResponseTextConfig = { - format?: ResponseFormatTextConfig; - verbosity?: "low" | "medium" | "high" | null; + 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"; + 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"; + 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; + token: string; + logprob: number; + top_logprobs?: Array; }; type TopLogprob = { - token?: string; - logprob?: number; + token?: string; + logprob?: number; }; type ResponseUsage = { - input_tokens: number; - output_tokens: number; - total_tokens: number; + input_tokens: number; + output_tokens: number; + total_tokens: number; }; type Tool = ResponsesFunctionTool; type ToolChoiceFunction = { - name: string; - type: "function"; + name: string; + type: "function"; }; type ToolChoiceOptions = "none"; type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; type StreamOptions = { - include_obfuscation?: boolean; + include_obfuscation?: boolean; }; /** Marks keys from T that aren't in U as optional never */ type Without = { - [P in Exclude]?: never; + [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: { +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"; -} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; + }[]; + }; +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 { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; + /** + * The async request id that can be used to obtain the results. + */ + 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 | { + 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 { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + * The second this word begins in the recording */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Output { + start?: number; /** - * The transcription + * The ending second when the word completes */ - 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; + end?: number; + }[]; + vtt?: string; } 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 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: { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +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 */ @@ -5624,527 +6132,559 @@ type Ai_Cf_Meta_M2M100_1_2B_Input = { * 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; -} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; + }[]; + }; +type Ai_Cf_Meta_M2M100_1_2B_Output = + | { + /** + * The translated text in the target language + */ + 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; + /** + * 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: { + 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. */ 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; + }[]; + }; +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; + /** + * 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: { + 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 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"; -} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; + }[]; + }; +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"; + } + | 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; + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; } 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; -}; + 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; + 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 | { + 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 { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + * The second this word begins in the recording */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + start?: number; /** - * The transcription + * The ending second when the word completes */ - 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; + 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; + 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 | { + audio: + | string + | { body?: object; contentType?: string; - }; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: 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 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?: { /** * 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. + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. */ - initial_prompt?: string; + language_probability?: number; /** - * The prefix appended to the beginning of the output of the transcription and can guide the transcription result. + * The total duration of the original audio file, in seconds. */ - prefix?: string; + duration?: number; /** - * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed. + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. */ - beam_size?: number; + duration_after_vad?: number; + }; + /** + * The complete transcription of the audio. + */ + text: string; + /** + * The total number of words in the transcription. + */ + word_count?: number; + segments?: { /** - * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops. + * The starting time of the segment within the audio, in seconds. */ - condition_on_previous_text?: boolean; + start?: number; /** - * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped. + * The ending time of the segment within the audio, in seconds. */ - no_speech_threshold?: number; + end?: number; /** - * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text. + * The transcription of the segment. */ - compression_ratio_threshold?: number; + text?: string; /** - * Threshold for filtering out segments with low average log probability, indicating low confidence. + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. */ - log_prob_threshold?: number; + temperature?: number; /** - * Optional threshold (in seconds) to skip silent periods that may cause hallucinations. + * The average log probability of the predictions for the words in this segment, indicating overall confidence. */ - hallucination_silence_threshold?: number; -} -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; - }; + avg_logprob?: number; /** - * The complete transcription of the audio. + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. */ - text: string; + compression_ratio?: number; /** - * The total number of words in the transcription. + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. */ - 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; - }[]; + 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; + }[]; + /** + * 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)[]; -}; + 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. + */ + 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. - */ - 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? + * One of the provided context content */ - truncate_inputs?: boolean; + 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 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; + 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: { /** - * 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? + * One of the provided context content */ - truncate_inputs?: boolean; + 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[]; + 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?: { /** - * When provided with too long context should the model error out or truncate the context to fit? + * Index of the context in the request */ - 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 - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { - response?: number[][]; - shape?: number[]; + id?: number; /** - * The pooling method used in the embedding process. + * Score of the context under the index. */ - pooling?: "mean" | "cls"; + score?: number; + }[]; +} +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; } interface Ai_Cf_Baai_Bge_M3_Output_Embedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; + shape?: number[]; + /** + * 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; + /** + * 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; + 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; + /** + * 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; + /** + * 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; + 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; +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. - */ - 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; + /** + * 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. + */ + 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 Ai_Cf_Meta_Llama_3_2_11B_Vision_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 | { + /** + * 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?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - 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; - }; - }[] | { + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - 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; - }; + url?: string; + }; }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ + }[]; + image?: number[] | (string & NonNullable); + 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. */ @@ -6157,31 +6697,32 @@ interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { * 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; - }; + /** + * 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'). */ @@ -6190,188 +6731,195 @@ interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. + * A description of the expected parameter. */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; + 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; + } + )[]; + /** + * 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 + */ + response?: string; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * 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. + * The arguments passed to be passed to the tool call request */ - top_k?: number; + arguments?: object; /** - * Random seed for reproducibility of the generation. + * The name of the tool to be called */ - 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 - */ - 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; - }[]; + name?: string; + }[]; }; 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; + 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_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; +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; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - 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. - */ - 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; + /** + * 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_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. + */ + 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_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; + 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. - */ - 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; + /** + * 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?: ({ + }[]; + 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. */ @@ -6384,31 +6932,32 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * 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; - }; + /** + * 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'). */ @@ -6417,49 +6966,101 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. + * A description of the expected parameter. */ - 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; - }; - }; + description: string; + }; }; + }; }; - })[]; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + } + )[]; + 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. + */ + 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_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; /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * Prompt for the text generation model */ - raw?: boolean; + prompt?: string; /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ @@ -6476,10 +7077,6 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * 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. */ @@ -6496,69 +7093,23 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; -} -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; - }[]; + 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?: { + 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 */ @@ -6571,11 +7122,11 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { * Total number of input and output tokens */ total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** * The arguments passed to be passed to the tool call request */ @@ -6584,52 +7135,56 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { * The name of the tool to be called */ name?: string; - }[]; -} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; + }[]; + } + | 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 async request id that can be used to obtain the results. - */ - request_id?: string; + /** + * The async request id that can be used to obtain the results. + */ + 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; + 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: { /** - * 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. + * The role of the message sender must alternate between 'user' and 'assistant'. */ - max_tokens?: number; + role: "user" | "assistant"; /** - * Controls the randomness of the output; higher values produce more random results. + * The content of the message as a string. */ - temperature?: number; - /** - * Dictate the output format of the generated response. + 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. */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; + type?: string; + }; } interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: string | { + response?: + | string + | { /** * Whether the conversation is safe or not. */ @@ -6638,141 +7193,144 @@ interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. */ categories?: string[]; - }; + }; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * Usage statistics for the inference request + * Total number of tokens in input */ - 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; - }; + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + 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; + 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. + /** + * A query you wish to perform against the provided contexts. + */ + /** + * 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: { + /** + * One of the provided context content */ + text?: string; + }[]; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Output { + response?: { /** - * Number of returned results starting with the best score. + * Index of the context in the request */ - top_k?: number; + id?: number; /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + * Score of the context under the index. */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; + 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; + 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; +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; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - 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. - */ - 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; + /** + * 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_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. + */ + 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_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; + 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. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - 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; - }[]; + role: string; /** - * A list of tools available for the assistant to use. + * The content of the message as a string. */ - tools?: ({ + content: 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. */ @@ -6785,31 +7343,32 @@ interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { * 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; - }; + /** + * 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'). */ @@ -6818,228 +7377,507 @@ interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. + * A description of the expected parameter. */ - 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; - }; - }; + description: string; + }; }; + }; }; - })[]; - 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. - */ - 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; + } + )[]; + 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. + */ + 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_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 + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * 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. + * Total number of tokens in input */ - top_k?: number; + prompt_tokens?: number; /** - * Random seed for reproducibility of the generation. + * Total number of tokens in output */ - seed?: number; + completion_tokens?: number; /** - * Penalty for repeated tokens; higher values discourage repetition. + * Total number of input and output tokens */ - repetition_penalty?: number; + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * The arguments passed to be passed to the tool call request */ - frequency_penalty?: number; + arguments?: object; /** - * Increases the likelihood of the model introducing new topics. + * The name of the tool to be called */ - presence_penalty?: number; + 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; } -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; +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 fulfilled 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 Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +interface Ai_Cf_Qwen_Qwq_32B_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?: ( + | { /** - * Total number of tokens in input + * The name of the tool. More descriptive the better. */ - prompt_tokens?: number; + name: string; /** - * Total number of tokens in output + * A brief description of what the tool does. */ - completion_tokens?: number; + description: string; /** - * Total number of input and output tokens + * Schema defining the parameters accepted by the tool. */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + 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; + }; + }; + }; + } + | { /** - * The arguments passed to be passed to the tool call request + * Specifies the type of tool (e.g., 'function'). */ - arguments?: object; + type: string; /** - * The name of the tool to be called + * Details of the function tool. */ - 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; + 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; + }; + }; + }; + }; + } + )[]; + /** + * 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 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 fulfilled 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; +type Ai_Cf_Qwen_Qwq_32B_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * 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. + * Total number of tokens in input */ - top_k?: number; + prompt_tokens?: number; /** - * Random seed for reproducibility of the generation. + * Total number of tokens in output */ - seed?: number; + completion_tokens?: number; /** - * Penalty for repeated tokens; higher values discourage repetition. + * Total number of input and output tokens */ - repetition_penalty?: number; + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * The arguments passed to be passed to the tool call request */ - frequency_penalty?: number; + arguments?: object; /** - * Increases the likelihood of the model introducing new topics. + * The name of the tool to be called */ - presence_penalty?: number; + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -interface Ai_Cf_Qwen_Qwq_32B_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 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. + */ + prompt: string; + /** + * JSON schema that should be fulfilled 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; +} +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_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. 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?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - 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; - }; - }[] | { + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - 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; - }; + url?: string; + }; }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ + }[]; + 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. */ @@ -7052,6 +7890,52 @@ interface Ai_Cf_Qwen_Qwq_32B_Messages { * 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'). */ @@ -7064,19 +7948,231 @@ interface Ai_Cf_Qwen_Qwq_32B_Messages { * Definitions of each parameter. */ properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: 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 Ai_Cf_Mistralai_Mistral_Small_3_1_24B_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; + }; + /** + * 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; + }[]; +}; +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; +} +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; +} +interface Ai_Cf_Google_Gemma_3_12B_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 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?: ( + | { + /** + * 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'). */ @@ -7085,227 +8181,753 @@ interface Ai_Cf_Qwen_Qwq_32B_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. + * A description of the expected parameter. */ - 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; - }; - }; + description: 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; + } + )[]; + /** + * 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 Ai_Cf_Google_Gemma_3_12B_It_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * 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. + * Total number of tokens in input */ - top_p?: number; + prompt_tokens?: 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. + * Total number of tokens in output */ - top_k?: number; + completion_tokens?: number; /** - * Random seed for reproducibility of the generation. + * Total number of input and output tokens */ - seed?: number; + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * Penalty for repeated tokens; higher values discourage repetition. + * The arguments passed to be passed to the tool call request */ - repetition_penalty?: number; + arguments?: object; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * The name of the tool to be called */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + 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_Qwen_Qwq_32B_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +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 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_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_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?: ( + | { /** - * Total number of tokens in input + * The name of the tool. More descriptive the better. */ - prompt_tokens?: number; + name: string; /** - * Total number of tokens in output + * A brief description of what the tool does. */ - completion_tokens?: number; + description: string; /** - * Total number of input and output tokens + * Schema defining the parameters accepted by the tool. */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + 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; + }; + }; + }; + } + | { /** - * The arguments passed to be passed to the tool call request + * Specifies the type of tool (e.g., 'function'). */ - arguments?: object; + type: string; /** - * The name of the tool to be called + * Details of the function tool. */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; + 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; + /** + * 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 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. - */ - prompt: string; - /** - * JSON schema that should be fulfilled 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; +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_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_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_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { + /** + * 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?: ( + | { + /** + * 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; + }; + }; + }; + } + | { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * Specifies the type of tool (e.g., 'function'). */ - role?: string; + type: 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 + * Details of the function tool. */ - tool_call_id?: string; - content?: string | { + 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: { /** - * Type of the content provided + * The type of the parameters object (usually 'object'). */ - 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: string; + /** + * List of required parameter names. + */ + required?: string[]; /** - * Type of the content provided + * Definitions of each parameter. */ - type?: string; - text?: string; - image_url?: { + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + * A description of the expected parameter. */ - url?: string; + description: string; + }; }; + }; }; - }[]; - functions?: { - name: string; - code: string; - }[]; + } + )[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * 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 Ai_Cf_Meta_Llama_4_Scout_17B_16E_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; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The tool call id. + */ + id?: string; /** - * A list of tools available for the assistant to use. + * Specifies the type of tool (e.g., 'function'). */ - tools?: ({ + 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 { + /** + * 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_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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?: ( + | { /** * The name of the tool. More descriptive the better. */ @@ -7318,6 +8940,52 @@ interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { * 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'). */ @@ -7330,19 +8998,194 @@ interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { * Definitions of each parameter. */ properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; + [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; + /** + * 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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +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 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_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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'). */ @@ -7351,211 +9194,784 @@ interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. + * A description of the expected parameter. */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; + description: string; + }; }; + }; }; - })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; + } + )[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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_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; + }; + }[]; + }; /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * Reason why the model stopped generating */ - raw?: boolean; + finish_reason?: string; /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * Stop reason (may be null) */ - stream?: boolean; + stop_reason?: string | null; /** - * The maximum number of tokens to generate in the response. + * Log probabilities (if requested) */ - max_tokens?: number; + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * Controls the randomness of the output; higher values produce more random results. + * Total number of tokens in input */ - temperature?: number; + prompt_tokens?: 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. + * Total number of tokens in output */ - top_p?: number; + completion_tokens?: 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. + * Total number of input and output tokens */ - 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_Mistralai_Mistral_Small_3_1_24B_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; - }; - /** - * 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; - }[]; -}; -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; + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; } -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. +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 */ - stream?: boolean; + index: number; /** - * The maximum number of tokens to generate in the response. + * The generated text completion */ - max_tokens?: number; + text: string; /** - * Controls the randomness of the output; higher values produce more random results. + * Reason why the model stopped generating */ - temperature?: number; + finish_reason: string; /** - * 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. + * Stop reason (may be null) */ - top_p?: number; + stop_reason?: string | null; /** - * 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. + * Log probabilities (if requested) */ - top_k?: number; + logprobs?: {} | null; /** - * Random seed for reproducibility of the generation. + * Log probabilities for the prompt (if requested) */ - seed?: number; + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * Penalty for repeated tokens; higher values discourage repetition. + * Total number of tokens in input */ - repetition_penalty?: number; + prompt_tokens?: number; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * Total number of tokens in output */ - frequency_penalty?: number; + completion_tokens?: number; /** - * Increases the likelihood of the model introducing new topics. + * Total number of input and output tokens */ - presence_penalty?: number; + total_tokens?: number; + }; } -interface Ai_Cf_Google_Gemma_3_12B_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 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; - }; +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; }[]; + }[]; }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ + 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 = + | { + /** + * 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"; + } + | { + /** + * 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"; + }; +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?: ( + | { /** * The name of the tool. More descriptive the better. */ @@ -7568,6 +9984,52 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Messages { * 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'). */ @@ -7580,19 +10042,197 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Messages { * Definitions of each parameter. */ properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; + [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'). */ @@ -7601,2775 +10241,918 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. + * A description of the expected parameter. */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; + 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; }; - })[]; + }[]; + }; /** - * JSON schema that should be fufilled for the response. + * Reason why the model stopped generating */ - guided_json?: object; + finish_reason?: string; /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * Stop reason (may be null) */ - raw?: boolean; + stop_reason?: string | null; /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * Log probabilities (if requested) */ - stream?: boolean; + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The maximum number of tokens to generate in the response. + * Total number of tokens in input */ - max_tokens?: number; + prompt_tokens?: number; /** - * Controls the randomness of the output; higher values produce more random results. + * Total number of tokens in output */ - temperature?: number; + completion_tokens?: 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. + * Total number of input and output tokens */ - top_p?: number; + 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; /** - * 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. + * The generated text completion */ - top_k?: number; + text: string; /** - * Random seed for reproducibility of the generation. + * Reason why the model stopped generating */ - seed?: number; + finish_reason: string; /** - * Penalty for repeated tokens; higher values discourage repetition. + * Stop reason (may be null) */ - repetition_penalty?: number; + stop_reason?: string | null; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * Log probabilities (if requested) */ - frequency_penalty?: number; + logprobs?: {} | null; /** - * Increases the likelihood of the model introducing new topics. + * Log probabilities for the prompt (if requested) */ - presence_penalty?: number; -} -type Ai_Cf_Google_Gemma_3_12B_It_Output = { + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The generated text response from the model + * Total number of tokens in input */ - response: string; + prompt_tokens?: number; /** - * Usage statistics for the inference request + * Total number of tokens in output */ - 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; - }[]; -}; -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 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_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_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?: ({ - /** - * 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; - /** - * 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; -} -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 input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_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_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { - /** - * 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?: ({ - /** - * 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; - /** - * 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 Ai_Cf_Meta_Llama_4_Scout_17B_16E_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; - }; - /** - * An array of tool calls requests made during the response generation - */ - 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 { - /** - * 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_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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?: ({ - /** - * 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; - /** - * 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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -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 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_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_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_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 = { - /** - * 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"; -} | { - /** - * 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"; -}; -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?: ({ - /** - * 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_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; - }[]; + completion_tokens?: number; /** - * Usage statistics for the inference request + * Total number of input and output tokens */ - 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; - }; + 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; + /** + * 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; + 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[]; + /** + * 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 - ]; + /** + * 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; + 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; + /** + * 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; + /** + * 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; + 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; + /** + * 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; +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; + 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; - }; + multipart: { + body?: object; + contentType?: string; + }; } interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output { - /** - * Generated image as Base64 string. - */ - image?: string; + /** + * 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; + 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; - }; + multipart: { + body?: object; + contentType?: string; + }; } interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output { - /** - * Generated image as Base64 string. - */ - image?: string; + /** + * 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; + 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; - }; + multipart: { + body?: object; + contentType?: string; + }; } interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output { - /** - * Generated image as Base64 string. - */ - image?: string; + /** + * 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; + 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; + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; } declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; } declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; } declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; } declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; + 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; + "@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; + /** + * 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; + 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; - source: number; name: string; description: string; - task: { - id: string; - name: string; - description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; }; type ChatCompletionsBase = ChatCompletionsMessagesInput; type ChatCompletionsInput = ChatCompletionsMessagesInput; -interface InferenceUpstreamError extends Error { -} -interface AiInternalError extends Error { -} +interface InferenceUpstreamError extends Error {} +interface AiInternalError extends Error {} type AiModelListType = Record; type AiAsyncBatchResponse = { - request_id: string; + 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; + 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'; + 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; + 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; + 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'; + 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': { + "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; + } + | 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; + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; }; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} +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 + 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: @@ -10382,83 +11165,83 @@ declare abstract class AiGateway { */ /** 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; + /** 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; + /** 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; + /** 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; + /** 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; + /** 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; + /** Tokens in this page. */ + tokens: ArtifactsTokenInfo[]; + /** Total number of tokens for the repository. */ + total: number; } /** * Handle for a single repository. Returned by Artifacts.get(). @@ -10466,36 +11249,39 @@ interface ArtifactsTokenListResult { * 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; + /** + * 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 ────────────────────────────────────────────────────────────── /** @@ -10503,7 +11289,19 @@ interface ArtifactsRepo extends ArtifactsRepoInfo { * * 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'; +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. * @@ -10512,11 +11310,11 @@ type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' * 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; + readonly name: "ArtifactsError"; + /** String error code for programmatic matching. */ + readonly code: ArtifactsErrorCode; + /** Numeric error code matching the REST API. */ + readonly numericCode: number; } // ── Binding ────────────────────────────────────────────────────────────────── /** @@ -10525,761 +11323,793 @@ interface ArtifactsError extends Error { * 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; + /** + * 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; - 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; + 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 { -} +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 { -} +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 { -} +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 { -} +interface AutoRAGNameNotSetError extends Error {} type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; + key: string; + type: "eq" | "ne" | "gt" | "gte" | "lt" | "lte"; + value: string | number | boolean; }; type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; + 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; + 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; + 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; +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; - }[]; + 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; + }[]; + 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; + 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; + 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'; + /** + * @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 `', - ].join('\n'), - ); + it("renders safe rustdoc HTML while removing executable and style content", () => { + const html = renderMarkdown( + [ + "", + "
", + "[![crate](https://img.shields.io/crates/v/demo.svg)](https://crates.io/crates/demo)", + "
", + '', + "", + ].join("\n"), + ); - expect(html).toContain('
'); - expect(html).toContain('"); + expect(html).toContain(' { - const html = renderMarkdown('unsafe'); + it("removes unsafe URL schemes from raw rustdoc HTML", () => { + const html = renderMarkdown('unsafe'); - expect(html).toContain('unsafe'); - expect(html).not.toContain('javascript:'); - }); + expect(html).toContain("unsafe"); + expect(html).not.toContain("javascript:"); + }); - it('writes resolved app routes into intra-doc anchors', () => { - const html = renderMarkdown( - 'Use [`Item`].', - { Item: 'demo::module::Item' }, - (nodeId) => `/demo/1.0.0/${nodeId.split('::').slice(1).join('/')}`, - ); + it("writes resolved app routes into intra-doc anchors", () => { + const html = renderMarkdown( + "Use [`Item`].", + { Item: "demo::module::Item" }, + (nodeId) => `/demo/1.0.0/${nodeId.split("::").slice(1).join("/")}`, + ); - expect(html).toContain('href="/demo/1.0.0/module/Item"'); - expect(html).toContain('data-node-id="demo::module::Item"'); - }); + expect(html).toContain('href="/demo/1.0.0/module/Item"'); + expect(html).toContain('data-node-id="demo::module::Item"'); + }); - it('keeps per-render link maps isolated', () => { - const first = renderMarkdown('[`Item`]', { Item: 'first::Item' }); - const second = renderMarkdown('[`Item`]', { Item: 'second::Item' }); + it("keeps per-render link maps isolated", () => { + const first = renderMarkdown("[`Item`]", { Item: "first::Item" }); + const second = renderMarkdown("[`Item`]", { Item: "second::Item" }); - expect(first).toContain('href="#first::Item"'); - expect(first).not.toContain('second::Item'); - expect(second).toContain('href="#second::Item"'); - expect(second).not.toContain('first::Item'); - }); + expect(first).toContain('href="#first::Item"'); + expect(first).not.toContain("second::Item"); + expect(second).toContain('href="#second::Item"'); + expect(second).not.toContain("first::Item"); + }); - it('resolves rustdoc reference-style links using their visible label', () => { - const html = renderMarkdown('The complete list is [here][crate::de].', { - 'crate::de': 'serde::de', - }); + it("resolves rustdoc reference-style links using their visible label", () => { + const html = renderMarkdown("The complete list is [here][crate::de].", { + "crate::de": "serde::de", + }); - expect(html).toContain('href="#serde::de"'); - expect(html).toContain('data-node-id="serde::de"'); - expect(html).toContain('>here'); - expect(html).not.toContain('[here]'); - expect(html).not.toContain('crate::de'); - }); + expect(html).toContain('href="#serde::de"'); + expect(html).toContain('data-node-id="serde::de"'); + expect(html).toContain(">here"); + expect(html).not.toContain("[here]"); + expect(html).not.toContain("crate::de"); + }); }); diff --git a/codeview-ui/src/lib/highlight/markdown.ts b/codeview-ui/src/lib/highlight/markdown.ts index aa75a16..d964cea 100644 --- a/codeview-ui/src/lib/highlight/markdown.ts +++ b/codeview-ui/src/lib/highlight/markdown.ts @@ -1,93 +1,93 @@ -import MarkdownIt from 'markdown-it'; -import markdownItGithubAlerts from 'markdown-it-github-alerts'; -import sanitizeHtml from 'sanitize-html'; -import type StateInline from 'markdown-it/lib/rules_inline/state_inline.mjs'; +import MarkdownIt from "markdown-it"; +import markdownItGithubAlerts from "markdown-it-github-alerts"; +import sanitizeHtml from "sanitize-html"; +import type StateInline from "markdown-it/lib/rules_inline/state_inline.mjs"; // Type for resolved intra-doc links: link text -> node ID export type DocLinks = Record; export type DocLinkResolver = (nodeId: string) => string; export type MarkdownCodeBlock = { info: string; content: string }; -export const CODE_BLOCK_SENTINEL_START = '\uE000codeview-code-block:'; -export const CODE_BLOCK_SENTINEL_END = '\uE001'; +export const CODE_BLOCK_SENTINEL_START = "\uE000codeview-code-block:"; +export const CODE_BLOCK_SENTINEL_END = "\uE001"; type RenderEnvironment = { - docLinks?: DocLinks; - codeBlocks?: MarkdownCodeBlock[]; - resolveDocLink?: DocLinkResolver; + docLinks?: DocLinks; + codeBlocks?: MarkdownCodeBlock[]; + resolveDocLink?: DocLinkResolver; }; const allowedTags = Array.from( - new Set([...sanitizeHtml.defaults.allowedTags, 'details', 'img', 'kbd', 'mark', 'summary']), + new Set([...sanitizeHtml.defaults.allowedTags, "details", "img", "kbd", "mark", "summary"]), ); const sanitizeOptions: sanitizeHtml.IOptions = { - allowedTags, - exclusiveFilter: (frame) => - frame.tag === 'p' && frame.text.trim().length === 0 && frame.mediaChildren.length === 0, - allowedAttributes: { - ...sanitizeHtml.defaults.allowedAttributes, - a: [ - ...(sanitizeHtml.defaults.allowedAttributes.a ?? []), - 'aria-label', - 'class', - 'data-node-id', - 'rel', - 'target', - ], - details: ['open'], - img: [ - 'alt', - 'decoding', - 'height', - 'loading', - 'referrerpolicy', - 'src', - 'srcset', - 'title', - 'width', - ], - td: ['colspan', 'rowspan'], - th: ['colspan', 'rowspan', 'scope'], - }, - allowedClasses: { - a: ['intra-doc-link'], - }, - transformTags: { - img: (_tagName, attribs) => ({ - tagName: 'img', - attribs: { - ...attribs, - decoding: 'async', - loading: attribs.loading ?? 'lazy', - referrerpolicy: attribs.referrerpolicy ?? 'no-referrer', - }, - }), - }, + allowedTags, + exclusiveFilter: (frame) => + frame.tag === "p" && frame.text.trim().length === 0 && frame.mediaChildren.length === 0, + allowedAttributes: { + ...sanitizeHtml.defaults.allowedAttributes, + a: [ + ...(sanitizeHtml.defaults.allowedAttributes.a ?? []), + "aria-label", + "class", + "data-node-id", + "rel", + "target", + ], + details: ["open"], + img: [ + "alt", + "decoding", + "height", + "loading", + "referrerpolicy", + "src", + "srcset", + "title", + "width", + ], + td: ["colspan", "rowspan"], + th: ["colspan", "rowspan", "scope"], + }, + allowedClasses: { + a: ["intra-doc-link"], + }, + transformTags: { + img: (_tagName, attribs) => ({ + tagName: "img", + attribs: { + ...attribs, + decoding: "async", + loading: attribs.loading ?? "lazy", + referrerpolicy: attribs.referrerpolicy ?? "no-referrer", + }, + }), + }, }; // Rustdoc permits raw HTML. Parse it, then apply a strict allowlist so common // structural markup and badges render without allowing scripts, styles, event // handlers, embedded documents, or arbitrary application classes. const md = new MarkdownIt({ - html: true, - linkify: true, // Auto-convert URLs to links - typographer: true, // Smart quotes, dashes, etc. + html: true, + linkify: true, // Auto-convert URLs to links + typographer: true, // Smart quotes, dashes, etc. }).use(markdownItGithubAlerts); // GitHub-style alert blocks (> [!NOTE], etc.) // Rustdoc commonly wraps Markdown badges and prose in raw block elements. // Keep the tags as inline HTML so MarkdownIt still parses their contents. -md.block.ruler.disable(['html_block']); +md.block.ruler.disable(["html_block"]); function docLinkHref(env: RenderEnvironment | undefined, nodeId: string): string { - if (!env?.resolveDocLink) return `#${nodeId}`; - try { - return env.resolveDocLink(nodeId); - } catch { - return `#${nodeId}`; - } + if (!env?.resolveDocLink) return `#${nodeId}`; + try { + return env.resolveDocLink(nodeId); + } catch { + return `#${nodeId}`; + } } function sanitizeRenderedHtml(html: string): string { - return sanitizeHtml(html, sanitizeOptions); + return sanitizeHtml(html, sanitizeOptions); } /** @@ -100,8 +100,8 @@ function sanitizeRenderedHtml(html: string): string { * The plugin stores doc_links in md.options for access during rendering. */ function intraDocLinksPlugin(md: MarkdownIt): void { - // Add inline rule for intra-doc links BEFORE backticks are processed - md.inline.ruler.before('backticks', 'intra_doc_link', intraDocLinkRule); + // Add inline rule for intra-doc links BEFORE backticks are processed + md.inline.ruler.before("backticks", "intra_doc_link", intraDocLinkRule); } /** @@ -111,90 +111,90 @@ function intraDocLinksPlugin(md: MarkdownIt): void { * instead of emitting reference definitions in the documentation string. */ function intraDocLinkRule(state: StateInline, silent: boolean): boolean { - const start = state.pos; - const max = state.posMax; - - // Must start with [ - if (state.src.charCodeAt(start) !== 0x5b /* [ */) { - return false; - } - - // Find the closing ] - let pos = start + 1; - let depth = 1; - while (pos < max && depth > 0) { - const ch = state.src.charCodeAt(pos); - if (ch === 0x5b /* [ */) depth++; - else if (ch === 0x5d /* ] */) depth--; - pos++; - } - - if (depth !== 0) return false; - - const closeBracket = pos - 1; - const content = state.src.slice(start + 1, closeBracket); - - const docLinks = (state.env as RenderEnvironment | undefined)?.docLinks; - if (!docLinks) return false; - - let lookupContent = content; - let end = pos; - // A normal inline Markdown destination is handled by markdown-it and then - // resolved through the renderer hook below. - if (pos < max) { - const nextChar = state.src.charCodeAt(pos); - if (nextChar === 0x28 /* ( */) return false; - if (nextChar === 0x5b /* [ */) { - const referenceEnd = state.src.indexOf(']', pos + 1); - if (referenceEnd < 0) return false; - lookupContent = state.src.slice(pos + 1, referenceEnd) || content; - end = referenceEnd + 1; - } - } - - // Check for backticks: [`Foo`] -> display as code - const hasBackticks = content.startsWith('`') && content.endsWith('`'); - // Display content (without backticks) - const displayContent = hasBackticks ? content.slice(1, -1) : content; - - // Try the explicit reference target first, then shortcut-label variants. - let nodeId: string | undefined; - if (lookupContent in docLinks) { - nodeId = docLinks[lookupContent]; - } else if (content in docLinks) { - nodeId = docLinks[content]; - } else if (displayContent in docLinks) { - nodeId = docLinks[displayContent]; - } - - if (!nodeId) { - return false; - } - - if (!silent) { - // Create link_open token - let token = state.push('link_open', 'a', 1); - token.attrs = [ - ['href', docLinkHref(state.env as RenderEnvironment | undefined, nodeId)], - ['class', 'intra-doc-link'], - ['data-node-id', nodeId], - ]; - - // Create code or text token for display content - if (hasBackticks) { - token = state.push('code_inline', 'code', 0); - token.content = displayContent; - } else { - token = state.push('text', '', 0); - token.content = displayContent; - } - - // Create link_close token - state.push('link_close', 'a', -1); - } - - state.pos = end; - return true; + const start = state.pos; + const max = state.posMax; + + // Must start with [ + if (state.src.charCodeAt(start) !== 0x5b /* [ */) { + return false; + } + + // Find the closing ] + let pos = start + 1; + let depth = 1; + while (pos < max && depth > 0) { + const ch = state.src.charCodeAt(pos); + if (ch === 0x5b /* [ */) depth++; + else if (ch === 0x5d /* ] */) depth--; + pos++; + } + + if (depth !== 0) return false; + + const closeBracket = pos - 1; + const content = state.src.slice(start + 1, closeBracket); + + const docLinks = (state.env as RenderEnvironment | undefined)?.docLinks; + if (!docLinks) return false; + + let lookupContent = content; + let end = pos; + // A normal inline Markdown destination is handled by markdown-it and then + // resolved through the renderer hook below. + if (pos < max) { + const nextChar = state.src.charCodeAt(pos); + if (nextChar === 0x28 /* ( */) return false; + if (nextChar === 0x5b /* [ */) { + const referenceEnd = state.src.indexOf("]", pos + 1); + if (referenceEnd < 0) return false; + lookupContent = state.src.slice(pos + 1, referenceEnd) || content; + end = referenceEnd + 1; + } + } + + // Check for backticks: [`Foo`] -> display as code + const hasBackticks = content.startsWith("`") && content.endsWith("`"); + // Display content (without backticks) + const displayContent = hasBackticks ? content.slice(1, -1) : content; + + // Try the explicit reference target first, then shortcut-label variants. + let nodeId: string | undefined; + if (lookupContent in docLinks) { + nodeId = docLinks[lookupContent]; + } else if (content in docLinks) { + nodeId = docLinks[content]; + } else if (displayContent in docLinks) { + nodeId = docLinks[displayContent]; + } + + if (!nodeId) { + return false; + } + + if (!silent) { + // Create link_open token + let token = state.push("link_open", "a", 1); + token.attrs = [ + ["href", docLinkHref(state.env as RenderEnvironment | undefined, nodeId)], + ["class", "intra-doc-link"], + ["data-node-id", nodeId], + ]; + + // Create code or text token for display content + if (hasBackticks) { + token = state.push("code_inline", "code", 0); + token.content = displayContent; + } else { + token = state.push("text", "", 0); + token.content = displayContent; + } + + // Create link_close token + state.push("link_close", "a", -1); + } + + state.pos = end; + return true; } // Apply the intra-doc links plugin @@ -204,70 +204,70 @@ const defaultFence = md.renderer.rules.fence; const defaultCodeBlock = md.renderer.rules.code_block; function captureCodeBlock( - tokens: any[], - idx: number, - options: any, - env: RenderEnvironment, - self: any, - fallback: NonNullable, + tokens: any[], + idx: number, + options: any, + env: RenderEnvironment, + self: any, + fallback: NonNullable, ): string { - if (!env.codeBlocks) return fallback(tokens, idx, options, env, self); - - const token = tokens[idx]; - const index = - env.codeBlocks.push({ - info: token.info ?? '', - content: token.content ?? '', - }) - 1; - return `${CODE_BLOCK_SENTINEL_START}${index}${CODE_BLOCK_SENTINEL_END}\n`; + if (!env.codeBlocks) return fallback(tokens, idx, options, env, self); + + const token = tokens[idx]; + const index = + env.codeBlocks.push({ + info: token.info ?? "", + content: token.content ?? "", + }) - 1; + return `${CODE_BLOCK_SENTINEL_START}${index}${CODE_BLOCK_SENTINEL_END}\n`; } md.renderer.rules.fence = (tokens, idx, options, env, self) => - captureCodeBlock( - tokens, - idx, - options, - env as RenderEnvironment, - self, - defaultFence ?? self.renderToken.bind(self), - ); + captureCodeBlock( + tokens, + idx, + options, + env as RenderEnvironment, + self, + defaultFence ?? self.renderToken.bind(self), + ); md.renderer.rules.code_block = (tokens, idx, options, env, self) => - captureCodeBlock( - tokens, - idx, - options, - env as RenderEnvironment, - self, - defaultCodeBlock ?? self.renderToken.bind(self), - ); + captureCodeBlock( + tokens, + idx, + options, + env as RenderEnvironment, + self, + defaultCodeBlock ?? self.renderToken.bind(self), + ); // Open external links in a new tab const defaultLinkOpen = - md.renderer.rules.link_open || - ((tokens: any, idx: any, options: any, _env: any, self: any) => - self.renderToken(tokens, idx, options)); + md.renderer.rules.link_open || + ((tokens: any, idx: any, options: any, _env: any, self: any) => + self.renderToken(tokens, idx, options)); md.renderer.rules.link_open = (tokens: any, idx: any, options: any, env: any, self: any) => { - const token = tokens[idx]; - const classAttr = token.attrGet('class') ?? ''; - - if (!classAttr.includes('intra-doc-link')) { - const href = token.attrGet('href') ?? ''; - const docLinks = (env as RenderEnvironment | undefined)?.docLinks; - - // Resolve rustdoc-style path links - if (docLinks && href && href in docLinks) { - const nodeId = docLinks[href]; - token.attrSet('href', docLinkHref(env as RenderEnvironment | undefined, nodeId)); - token.attrSet('class', 'intra-doc-link'); - token.attrSet('data-node-id', nodeId); - } else { - token.attrSet('target', '_blank'); - token.attrSet('rel', 'noopener noreferrer'); - } - } - return defaultLinkOpen(tokens, idx, options, env, self); + const token = tokens[idx]; + const classAttr = token.attrGet("class") ?? ""; + + if (!classAttr.includes("intra-doc-link")) { + const href = token.attrGet("href") ?? ""; + const docLinks = (env as RenderEnvironment | undefined)?.docLinks; + + // Resolve rustdoc-style path links + if (docLinks && href && href in docLinks) { + const nodeId = docLinks[href]; + token.attrSet("href", docLinkHref(env as RenderEnvironment | undefined, nodeId)); + token.attrSet("class", "intra-doc-link"); + token.attrSet("data-node-id", nodeId); + } else { + token.attrSet("target", "_blank"); + token.attrSet("rel", "noopener noreferrer"); + } + } + return defaultLinkOpen(tokens, idx, options, env, self); }; /** @@ -278,23 +278,23 @@ md.renderer.rules.link_open = (tokens: any, idx: any, options: any, env: any, se * @param docLinks Optional map of intra-doc link text to node IDs */ export function renderMarkdown( - text: string, - docLinks?: DocLinks, - resolveDocLink?: DocLinkResolver, + text: string, + docLinks?: DocLinks, + resolveDocLink?: DocLinkResolver, ): string { - return sanitizeRenderedHtml( - md.render(text, { docLinks, resolveDocLink } satisfies RenderEnvironment), - ); + return sanitizeRenderedHtml( + md.render(text, { docLinks, resolveDocLink } satisfies RenderEnvironment), + ); } export function renderMarkdownDocument( - text: string, - docLinks?: DocLinks, - resolveDocLink?: DocLinkResolver, + text: string, + docLinks?: DocLinks, + resolveDocLink?: DocLinkResolver, ): { html: string; codeBlocks: MarkdownCodeBlock[] } { - const codeBlocks: MarkdownCodeBlock[] = []; - const html = sanitizeRenderedHtml( - md.render(text, { docLinks, codeBlocks, resolveDocLink } satisfies RenderEnvironment), - ); - return { html, codeBlocks }; + const codeBlocks: MarkdownCodeBlock[] = []; + const html = sanitizeRenderedHtml( + md.render(text, { docLinks, codeBlocks, resolveDocLink } satisfies RenderEnvironment), + ); + return { html, codeBlocks }; } diff --git a/codeview-ui/src/lib/highlight/shiki-modules.d.ts b/codeview-ui/src/lib/highlight/shiki-modules.d.ts new file mode 100644 index 0000000..614c131 --- /dev/null +++ b/codeview-ui/src/lib/highlight/shiki-modules.d.ts @@ -0,0 +1,14 @@ +declare module "@shikijs/langs/*" { + const lang: any; + export default lang; +} + +declare module "@shikijs/themes/*" { + const theme: { + colors?: Record; + tokenColors?: Array<{ + settings: { foreground?: string }; + }>; + }; + export default theme; +} diff --git a/codeview-ui/src/lib/highlight/shiki.test.ts b/codeview-ui/src/lib/highlight/shiki.test.ts index 62694a4..b1801dd 100644 --- a/codeview-ui/src/lib/highlight/shiki.test.ts +++ b/codeview-ui/src/lib/highlight/shiki.test.ts @@ -1,61 +1,61 @@ -import { describe, expect, it } from 'vitest'; -import { highlightCode } from './shiki'; +import { describe, expect, it } from "vite-plus/test"; +import { highlightCode } from "./shiki"; function relativeLuminance(hex: string): number { - const channels = hex - .slice(1) - .match(/.{2}/g) - ?.map((channel) => Number.parseInt(channel, 16) / 255); - if (!channels || channels.length !== 3) throw new Error(`Invalid color: ${hex}`); + const channels = hex + .slice(1) + .match(/.{2}/g) + ?.map((channel) => Number.parseInt(channel, 16) / 255); + if (!channels || channels.length !== 3) throw new Error(`Invalid color: ${hex}`); - const [red, green, blue] = channels.map((channel) => - channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4, - ); - return 0.2126 * red + 0.7152 * green + 0.0722 * blue; + const [red, green, blue] = channels.map((channel) => + channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4, + ); + return 0.2126 * red + 0.7152 * green + 0.0722 * blue; } function contrastRatio(foreground: string, background: string): number { - const foregroundLuminance = relativeLuminance(foreground); - const backgroundLuminance = relativeLuminance(background); - return ( - (Math.max(foregroundLuminance, backgroundLuminance) + 0.05) / - (Math.min(foregroundLuminance, backgroundLuminance) + 0.05) - ); + const foregroundLuminance = relativeLuminance(foreground); + const backgroundLuminance = relativeLuminance(background); + return ( + (Math.max(foregroundLuminance, backgroundLuminance) + 0.05) / + (Math.min(foregroundLuminance, backgroundLuminance) + 0.05) + ); } -describe('code highlighting themes', () => { - it('keeps every emitted theme token readable', async () => { - const html = await highlightCode( - 'let result: Result = Err(Error);\nlet text = "value"; // note', - 'rust', - 'dark', - ); - const themeCases = [ - { name: 'solarized-light', background: '#f2ebd7' }, - { name: 'solarized-dark', background: '#001f27' }, - { name: 'catppuccin-latte', background: '#eff1f5' }, - { name: 'catppuccin-mocha', background: '#1e1e2e' }, - { name: 'one-light', background: '#fafafa' }, - { name: 'one-dark', background: '#282c34' }, - { name: 'github-light', background: '#ffffff' }, - { name: 'github-dark', background: '#0d1117' }, - ] as const; +describe("code highlighting themes", () => { + it("keeps every emitted theme token readable", async () => { + const html = await highlightCode( + 'let result: Result = Err(Error);\nlet text = "value"; // note', + "rust", + "dark", + ); + const themeCases = [ + { name: "solarized-light", background: "#f2ebd7" }, + { name: "solarized-dark", background: "#001f27" }, + { name: "catppuccin-latte", background: "#eff1f5" }, + { name: "catppuccin-mocha", background: "#1e1e2e" }, + { name: "one-light", background: "#fafafa" }, + { name: "one-dark", background: "#282c34" }, + { name: "github-light", background: "#ffffff" }, + { name: "github-dark", background: "#0d1117" }, + ] as const; - expect(html).toContain('--shiki-solarized-light-bg:#f2ebd7'); - expect(html).toContain('--shiki-solarized-dark-bg:#001f27'); - for (const theme of themeCases) { - const colors = new Set( - [...html.matchAll(new RegExp(`--shiki-${theme.name}:(#[\\da-f]{6})`, 'gi'))].map((match) => - match[1].toLowerCase(), - ), - ); - expect(colors.size).toBeGreaterThan(3); - for (const color of colors) { - expect( - contrastRatio(color, theme.background), - `${theme.name} ${color}`, - ).toBeGreaterThanOrEqual(4.5); - } - } - }); + expect(html).toContain("--shiki-solarized-light-bg:#f2ebd7"); + expect(html).toContain("--shiki-solarized-dark-bg:#001f27"); + for (const theme of themeCases) { + const colors = new Set( + [...html.matchAll(new RegExp(`--shiki-${theme.name}:(#[\\da-f]{6})`, "gi"))].map((match) => + match[1].toLowerCase(), + ), + ); + expect(colors.size).toBeGreaterThan(3); + for (const color of colors) { + expect( + contrastRatio(color, theme.background), + `${theme.name} ${color}`, + ).toBeGreaterThanOrEqual(4.5); + } + } + }); }); diff --git a/codeview-ui/src/lib/highlight/shiki.ts b/codeview-ui/src/lib/highlight/shiki.ts index c574bd6..455d114 100644 --- a/codeview-ui/src/lib/highlight/shiki.ts +++ b/codeview-ui/src/lib/highlight/shiki.ts @@ -1,97 +1,97 @@ -import { createHighlighterCore, type HighlighterCore } from 'shiki/core'; -import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'; -import rust from '@shikijs/langs/rust'; -import typescript from '@shikijs/langs/typescript'; -import javascript from '@shikijs/langs/javascript'; -import json from '@shikijs/langs/json'; -import toml from '@shikijs/langs/toml'; -import bash from '@shikijs/langs/bash'; -import sql from '@shikijs/langs/sql'; -import type { SupportedLanguage } from './languages'; -export { getDefaultLanguage, normalizeLanguage } from './languages'; -export type { ProjectType, SupportedLanguage } from './languages'; +import { createHighlighterCore, type HighlighterCore } from "shiki/core"; +import { createJavaScriptRegexEngine } from "shiki/engine/javascript"; +import rust from "@shikijs/langs/rust"; +import typescript from "@shikijs/langs/typescript"; +import javascript from "@shikijs/langs/javascript"; +import json from "@shikijs/langs/json"; +import toml from "@shikijs/langs/toml"; +import bash from "@shikijs/langs/bash"; +import sql from "@shikijs/langs/sql"; +import type { SupportedLanguage } from "./languages"; +export { getDefaultLanguage, normalizeLanguage } from "./languages"; +export type { ProjectType, SupportedLanguage } from "./languages"; // Eager imports force Vite/rolldown to bundle each theme — `themes: ['name']` // alone leaves them dynamic and they fall out of the build. We re-alias // `one-dark-pro` (the only "One Dark" shiki ships) as `one-dark` so the // Tweaks-panel-facing key matches. -import solarizedLight from '@shikijs/themes/solarized-light'; -import solarizedDark from '@shikijs/themes/solarized-dark'; -import catppuccinLatte from '@shikijs/themes/catppuccin-latte'; -import catppuccinMocha from '@shikijs/themes/catppuccin-mocha'; -import oneLight from '@shikijs/themes/one-light'; -import oneDarkPro from '@shikijs/themes/one-dark-pro'; -import githubLight from '@shikijs/themes/github-light'; -import githubDark from '@shikijs/themes/github-dark'; +import solarizedLight from "@shikijs/themes/solarized-light"; +import solarizedDark from "@shikijs/themes/solarized-dark"; +import catppuccinLatte from "@shikijs/themes/catppuccin-latte"; +import catppuccinMocha from "@shikijs/themes/catppuccin-mocha"; +import oneLight from "@shikijs/themes/one-light"; +import oneDarkPro from "@shikijs/themes/one-dark-pro"; +import githubLight from "@shikijs/themes/github-light"; +import githubDark from "@shikijs/themes/github-dark"; const solarizedLightContrastMap: Record = { - '#268bd2': '#1f6fa5', - '#2aa198': '#176d68', - '#657b83': '#4f656d', - '#6c71c4': '#5359a8', - '#859900': '#596800', - '#93a1a1': '#556a72', - '#b58900': '#856500', - '#cb4b16': '#a93b0c', - '#d33682': '#9f2861', - '#dc322f': '#ad2422', + "#268bd2": "#1f6fa5", + "#2aa198": "#176d68", + "#657b83": "#4f656d", + "#6c71c4": "#5359a8", + "#859900": "#596800", + "#93a1a1": "#556a72", + "#b58900": "#856500", + "#cb4b16": "#a93b0c", + "#d33682": "#9f2861", + "#dc322f": "#ad2422", }; const solarizedDarkContrastMap: Record = { - '#268bd2': '#5fb3eb', - '#2aa198': '#55bfb5', - '#586e75': '#7f9296', - '#6c71c4': '#a294de', - '#859900': '#a3b900', - '#b58900': '#d8ad32', - '#cb4b16': '#ff9d66', - '#d33682': '#e66aa6', - '#dc322f': '#ff7b72', + "#268bd2": "#5fb3eb", + "#2aa198": "#55bfb5", + "#586e75": "#7f9296", + "#6c71c4": "#a294de", + "#859900": "#a3b900", + "#b58900": "#d8ad32", + "#cb4b16": "#ff9d66", + "#d33682": "#e66aa6", + "#dc322f": "#ff7b72", }; // Solarized targets equal perceived lightness, but several accents fall below // 4.5:1 against their editor background. Preserve the hue relationships while // moving only the low-contrast token colors. const readableSolarizedLight = { - ...solarizedLight, - colors: { - ...solarizedLight.colors, - 'editor.background': '#f2ebd7', - }, - tokenColors: solarizedLight.tokenColors?.map((token) => { - const foreground = token.settings.foreground?.toLowerCase(); - return { - ...token, - settings: { - ...token.settings, - foreground: foreground - ? (solarizedLightContrastMap[foreground] ?? token.settings.foreground) - : undefined, - }, - }; - }), + ...solarizedLight, + colors: { + ...solarizedLight.colors, + "editor.background": "#f2ebd7", + }, + tokenColors: solarizedLight.tokenColors?.map((token) => { + const foreground = token.settings.foreground?.toLowerCase(); + return { + ...token, + settings: { + ...token.settings, + foreground: foreground + ? (solarizedLightContrastMap[foreground] ?? token.settings.foreground) + : undefined, + }, + }; + }), }; const readableSolarizedDark = { - ...solarizedDark, - colors: { - ...solarizedDark.colors, - 'editor.background': '#001f27', - }, - tokenColors: solarizedDark.tokenColors?.map((token) => { - const foreground = token.settings.foreground?.toLowerCase(); - return { - ...token, - settings: { - ...token.settings, - foreground: foreground - ? (solarizedDarkContrastMap[foreground] ?? token.settings.foreground) - : undefined, - }, - }; - }), + ...solarizedDark, + colors: { + ...solarizedDark.colors, + "editor.background": "#001f27", + }, + tokenColors: solarizedDark.tokenColors?.map((token) => { + const foreground = token.settings.foreground?.toLowerCase(); + return { + ...token, + settings: { + ...token.settings, + foreground: foreground + ? (solarizedDarkContrastMap[foreground] ?? token.settings.foreground) + : undefined, + }, + }; + }), }; -const oneDark = { ...oneDarkPro, name: 'one-dark' }; +const oneDark = { ...oneDarkPro, name: "one-dark" }; /** * All shiki themes the Tweaks panel can pick. Output is generated with @@ -99,25 +99,25 @@ const oneDark = { ...oneDarkPro, name: 'one-dark' }; * via `[data-code-theme="..."]` in app.css — no re-render needed. */ const CODE_THEMES = [ - 'solarized-light', - 'solarized-dark', - 'catppuccin-latte', - 'catppuccin-mocha', - 'one-light', - 'one-dark', - 'github-light', - 'github-dark', + "solarized-light", + "solarized-dark", + "catppuccin-latte", + "catppuccin-mocha", + "one-light", + "one-dark", + "github-light", + "github-dark", ] as const; const CODE_THEME_BACKGROUNDS: Record<(typeof CODE_THEMES)[number], string> = { - 'solarized-light': '#f2ebd7', - 'solarized-dark': '#001f27', - 'catppuccin-latte': '#eff1f5', - 'catppuccin-mocha': '#1e1e2e', - 'one-light': '#fafafa', - 'one-dark': '#282c34', - 'github-light': '#ffffff', - 'github-dark': '#0d1117', + "solarized-light": "#f2ebd7", + "solarized-dark": "#001f27", + "catppuccin-latte": "#eff1f5", + "catppuccin-mocha": "#1e1e2e", + "one-light": "#fafafa", + "one-dark": "#282c34", + "github-light": "#ffffff", + "github-dark": "#0d1117", }; const MINIMUM_CODE_CONTRAST = 4.5; @@ -127,189 +127,189 @@ let highlighterPromise: Promise | null = null; // Keep the browser bundle limited to the languages Codeview actually renders. // Importing Shiki's umbrella entry emits every bundled grammar as an asset. async function getHighlighter(): Promise { - if (!highlighterPromise) { - highlighterPromise = createHighlighterCore({ - themes: [ - readableSolarizedLight, - readableSolarizedDark, - catppuccinLatte, - catppuccinMocha, - oneLight, - oneDark, - githubLight, - githubDark, - ], - langs: [rust, typescript, javascript, json, toml, bash, sql], - engine: createJavaScriptRegexEngine(), - }); - } - return highlighterPromise; + if (!highlighterPromise) { + highlighterPromise = createHighlighterCore({ + themes: [ + readableSolarizedLight, + readableSolarizedDark, + catppuccinLatte, + catppuccinMocha, + oneLight, + oneDark, + githubLight, + githubDark, + ], + langs: [rust, typescript, javascript, json, toml, bash, sql], + engine: createJavaScriptRegexEngine(), + }); + } + return highlighterPromise; } // Highlight code with the given language. The `theme` argument is kept // for backwards-compatibility but is ignored — all 8 themes are emitted // as CSS variables and the active one is picked by `[data-code-theme]`. export async function highlightCode( - code: string, - lang: SupportedLanguage = 'rust', - _theme: 'dark' | 'light' = 'dark', - options?: { - startLine?: number; - highlightLines?: number[]; - showLineNumbers?: boolean; - }, + code: string, + lang: SupportedLanguage = "rust", + _theme: "dark" | "light" = "dark", + options?: { + startLine?: number; + highlightLines?: number[]; + showLineNumbers?: boolean; + }, ): Promise { - const highlighter = await getHighlighter(); + const highlighter = await getHighlighter(); - const { startLine = 1, highlightLines, showLineNumbers } = options ?? {}; - const needsTransformer = showLineNumbers || highlightLines?.length; + const { startLine = 1, highlightLines, showLineNumbers } = options ?? {}; + const needsTransformer = showLineNumbers || highlightLines?.length; - // For unsupported or 'text' language, return plain text with optional line info - if (lang === 'text') { - return buildPlainHtml(escapeHtml(code), startLine, highlightLines, showLineNumbers); - } + // For unsupported or 'text' language, return plain text with optional line info + if (lang === "text") { + return buildPlainHtml(escapeHtml(code), startLine, highlightLines, showLineNumbers); + } - const themesMap: Record = {}; - for (const t of CODE_THEMES) themesMap[t] = t; + const themesMap: Record = {}; + for (const t of CODE_THEMES) themesMap[t] = t; - try { - const html = highlighter.codeToHtml(code, { - lang, - themes: themesMap, - // defaultColor: false → no top-level color attr; everything goes - // through --shiki-{theme} CSS vars + the [data-code-theme] selectors - // in app.css. - defaultColor: false, - cssVariablePrefix: '--shiki-', - transformers: needsTransformer - ? [ - { - line(node: any, line: number) { - const lineNum = line + startLine - 1; - const classes: string[] = ['line']; - if (showLineNumbers) { - node.properties['data-line'] = lineNum; - classes.push('has-line-number'); - } - if (highlightLines?.includes(lineNum)) { - classes.push('highlighted'); - } - node.properties['class'] = classes.join(' '); - }, - }, - ] - : undefined, - }); - return enforceThemeContrast(html); - } catch { - return buildPlainHtml(escapeHtml(code), startLine, highlightLines, showLineNumbers); - } + try { + const html = highlighter.codeToHtml(code, { + lang, + themes: themesMap, + // defaultColor: false → no top-level color attr; everything goes + // through --shiki-{theme} CSS vars + the [data-code-theme] selectors + // in app.css. + defaultColor: false, + cssVariablePrefix: "--shiki-", + transformers: needsTransformer + ? [ + { + line(node: any, line: number) { + const lineNum = line + startLine - 1; + const classes: string[] = ["line"]; + if (showLineNumbers) { + node.properties["data-line"] = lineNum; + classes.push("has-line-number"); + } + if (highlightLines?.includes(lineNum)) { + classes.push("highlighted"); + } + node.properties["class"] = classes.join(" "); + }, + }, + ] + : undefined, + }); + return enforceThemeContrast(html); + } catch { + return buildPlainHtml(escapeHtml(code), startLine, highlightLines, showLineNumbers); + } } function enforceThemeContrast(html: string): string { - let readableHtml = html; - for (const theme of CODE_THEMES) { - const token = theme.replaceAll('-', '\\-'); - const pattern = new RegExp(`(--shiki-${token}:)(#[\\da-f]{6})`, 'gi'); - const background = CODE_THEME_BACKGROUNDS[theme]; - readableHtml = readableHtml.replace(pattern, (_match, prefix: string, color: string) => { - return `${prefix}${ensureContrast(color, background)}`; - }); - } - return readableHtml; + let readableHtml = html; + for (const theme of CODE_THEMES) { + const token = theme.replaceAll("-", "\\-"); + const pattern = new RegExp(`(--shiki-${token}:)(#[\\da-f]{6})`, "gi"); + const background = CODE_THEME_BACKGROUNDS[theme]; + readableHtml = readableHtml.replace(pattern, (_match, prefix: string, color: string) => { + return `${prefix}${ensureContrast(color, background)}`; + }); + } + return readableHtml; } function ensureContrast(foreground: string, background: string): string { - if (contrastRatio(foreground, background) >= MINIMUM_CODE_CONTRAST) { - return foreground.toLowerCase(); - } + if (contrastRatio(foreground, background) >= MINIMUM_CODE_CONTRAST) { + return foreground.toLowerCase(); + } - const black = '#000000'; - const white = '#ffffff'; - const target = - contrastRatio(black, background) > contrastRatio(white, background) ? black : white; - let low = 0; - let high = 1; - for (let iteration = 0; iteration < 20; iteration += 1) { - const midpoint = (low + high) / 2; - const candidate = mixHex(foreground, target, midpoint); - if (contrastRatio(candidate, background) >= MINIMUM_CODE_CONTRAST) high = midpoint; - else low = midpoint; - } + const black = "#000000"; + const white = "#ffffff"; + const target = + contrastRatio(black, background) > contrastRatio(white, background) ? black : white; + let low = 0; + let high = 1; + for (let iteration = 0; iteration < 20; iteration += 1) { + const midpoint = (low + high) / 2; + const candidate = mixHex(foreground, target, midpoint); + if (contrastRatio(candidate, background) >= MINIMUM_CODE_CONTRAST) high = midpoint; + else low = midpoint; + } - const adjusted = mixHex(foreground, target, high); - return contrastRatio(adjusted, background) >= MINIMUM_CODE_CONTRAST ? adjusted : target; + const adjusted = mixHex(foreground, target, high); + return contrastRatio(adjusted, background) >= MINIMUM_CODE_CONTRAST ? adjusted : target; } function mixHex(from: string, to: string, amount: number): string { - const fromChannels = hexChannels(from); - const toChannels = hexChannels(to); - return `#${fromChannels - .map((channel, index) => - Math.round(channel + (toChannels[index] - channel) * amount) - .toString(16) - .padStart(2, '0'), - ) - .join('')}`; + const fromChannels = hexChannels(from); + const toChannels = hexChannels(to); + return `#${fromChannels + .map((channel, index) => + Math.round(channel + (toChannels[index] - channel) * amount) + .toString(16) + .padStart(2, "0"), + ) + .join("")}`; } function contrastRatio(foreground: string, background: string): number { - const foregroundLuminance = relativeLuminance(foreground); - const backgroundLuminance = relativeLuminance(background); - return ( - (Math.max(foregroundLuminance, backgroundLuminance) + 0.05) / - (Math.min(foregroundLuminance, backgroundLuminance) + 0.05) - ); + const foregroundLuminance = relativeLuminance(foreground); + const backgroundLuminance = relativeLuminance(background); + return ( + (Math.max(foregroundLuminance, backgroundLuminance) + 0.05) / + (Math.min(foregroundLuminance, backgroundLuminance) + 0.05) + ); } function relativeLuminance(hex: string): number { - const channels = hexChannels(hex).map((channel) => { - const normalized = channel / 255; - return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4; - }); - return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]; + const channels = hexChannels(hex).map((channel) => { + const normalized = channel / 255; + return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]; } function hexChannels(hex: string): [number, number, number] { - return [ - Number.parseInt(hex.slice(1, 3), 16), - Number.parseInt(hex.slice(3, 5), 16), - Number.parseInt(hex.slice(5, 7), 16), - ]; + return [ + Number.parseInt(hex.slice(1, 3), 16), + Number.parseInt(hex.slice(3, 5), 16), + Number.parseInt(hex.slice(5, 7), 16), + ]; } function buildPlainHtml( - escapedCode: string, - startLine: number, - highlightLines?: number[], - showLineNumbers?: boolean, + escapedCode: string, + startLine: number, + highlightLines?: number[], + showLineNumbers?: boolean, ): string { - if (!showLineNumbers && !highlightLines?.length) { - return `
${escapedCode}
`; - } - const lines = escapedCode.split('\n'); - const html = lines - .map((line, i) => { - const lineNum = startLine + i; - const classes = [ - 'line', - showLineNumbers ? 'has-line-number' : '', - highlightLines?.includes(lineNum) ? 'highlighted' : '', - ] - .filter(Boolean) - .join(' '); - const dataAttr = showLineNumbers ? ` data-line="${lineNum}"` : ''; - return `${line}`; - }) - .join('\n'); - return `
${html}
`; + if (!showLineNumbers && !highlightLines?.length) { + return `
${escapedCode}
`; + } + const lines = escapedCode.split("\n"); + const html = lines + .map((line, i) => { + const lineNum = startLine + i; + const classes = [ + "line", + showLineNumbers ? "has-line-number" : "", + highlightLines?.includes(lineNum) ? "highlighted" : "", + ] + .filter(Boolean) + .join(" "); + const dataAttr = showLineNumbers ? ` data-line="${lineNum}"` : ""; + return `${line}`; + }) + .join("\n"); + return `
${html}
`; } function escapeHtml(text: string): string { - return text - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); + return text + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); } diff --git a/codeview-ui/src/lib/highlight/theme-contrast.test.ts b/codeview-ui/src/lib/highlight/theme-contrast.test.ts index cc9c1f8..8e2c19e 100644 --- a/codeview-ui/src/lib/highlight/theme-contrast.test.ts +++ b/codeview-ui/src/lib/highlight/theme-contrast.test.ts @@ -1,55 +1,55 @@ -import { readFileSync } from 'node:fs'; -import { describe, expect, it } from 'vitest'; +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vite-plus/test"; -const appCss = readFileSync(new URL('../../app.css', import.meta.url), 'utf8'); +const appCss = readFileSync(new URL("../../app.css", import.meta.url), "utf8"); const themes = [ - 'solarized-light', - 'solarized-dark', - 'catppuccin-latte', - 'catppuccin-mocha', - 'one-light', - 'one-dark', - 'github-light', - 'github-dark', + "solarized-light", + "solarized-dark", + "catppuccin-latte", + "catppuccin-mocha", + "one-light", + "one-dark", + "github-light", + "github-dark", ] as const; function relativeLuminance(hex: string): number { - const channels = [1, 3, 5].map((index) => Number.parseInt(hex.slice(index, index + 2), 16) / 255); - const linear = channels.map((channel) => - channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4, - ); - return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]; + const channels = [1, 3, 5].map((index) => Number.parseInt(hex.slice(index, index + 2), 16) / 255); + const linear = channels.map((channel) => + channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4, + ); + return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]; } function contrastRatio(foreground: string, background: string): number { - const foregroundLuminance = relativeLuminance(foreground); - const backgroundLuminance = relativeLuminance(background); - return ( - (Math.max(foregroundLuminance, backgroundLuminance) + 0.05) / - (Math.min(foregroundLuminance, backgroundLuminance) + 0.05) - ); + const foregroundLuminance = relativeLuminance(foreground); + const backgroundLuminance = relativeLuminance(background); + return ( + (Math.max(foregroundLuminance, backgroundLuminance) + 0.05) / + (Math.min(foregroundLuminance, backgroundLuminance) + 0.05) + ); } -describe('static code theme tokens', () => { - it.each(themes)('%s keeps every text token at WCAG AA contrast', (theme) => { - const block = appCss.match( - new RegExp(`\\[data-code-theme='${theme}'\\] \\{([\\s\\S]*?)\\n\\t\\}`), - )?.[1]; - expect(block, `${theme} CSS block`).toBeDefined(); - const variables = Object.fromEntries( - [...(block ?? '').matchAll(/--([\w-]+):\s*(#[\da-f]{6})/gi)].map((match) => [ - match[1], - match[2].toLowerCase(), - ]), - ); - const background = variables['code-bg']; - expect(background, `${theme} background`).toBeDefined(); +describe("static code theme tokens", () => { + it.each(themes)("%s keeps every text token at WCAG AA contrast", (theme) => { + const block = appCss.match( + new RegExp(`\\[data-code-theme='${theme}'\\] \\{([\\s\\S]*?)\\n\\t\\}`), + )?.[1]; + expect(block, `${theme} CSS block`).toBeDefined(); + const variables = Object.fromEntries( + [...(block ?? "").matchAll(/--([\w-]+):\s*(#[\da-f]{6})/gi)].map((match) => [ + match[1], + match[2].toLowerCase(), + ]), + ); + const background = variables["code-bg"]; + expect(background, `${theme} background`).toBeDefined(); - for (const [name, color] of Object.entries(variables)) { - if (name !== 'code-ink' && !name.startsWith('syntax-')) continue; - expect(contrastRatio(color, background), `${theme} ${name} ${color}`).toBeGreaterThanOrEqual( - 4.5, - ); - } - }); + for (const [name, color] of Object.entries(variables)) { + if (name !== "code-ink" && !name.startsWith("syntax-")) continue; + expect(contrastRatio(color, background), `${theme} ${name} ${color}`).toBeGreaterThanOrEqual( + 4.5, + ); + } + }); }); diff --git a/codeview-ui/src/lib/hosted-contract.test.ts b/codeview-ui/src/lib/hosted-contract.test.ts index 40ea170..ce0f59b 100644 --- a/codeview-ui/src/lib/hosted-contract.test.ts +++ b/codeview-ui/src/lib/hosted-contract.test.ts @@ -1,40 +1,40 @@ -import { describe, expect, test } from 'vitest'; +import { describe, expect, test } from "vite-plus/test"; import { - HOSTED_ARTIFACT_CACHE_NAMESPACE, - isCurrentHostedArtifactMetadata, -} from './hosted-contract'; + HOSTED_ARTIFACT_CACHE_NAMESPACE, + isCurrentHostedArtifactMetadata, +} from "./hosted-contract"; function metadata(schemaVersion = 2) { - return { - schema_version: schemaVersion, - name: 'serde', - version: '1.0.228', - index: {}, - artifacts: { - kindIndex: true, - nodeViewBucketCount: 128, - treeChildrenBucketCount: 128, - aliasBucketCount: 128, - searchPrefixLength: 2, - }, - }; + return { + schema_version: schemaVersion, + name: "serde", + version: "1.0.228", + index: {}, + artifacts: { + kindIndex: true, + nodeViewBucketCount: 128, + treeChildrenBucketCount: 128, + aliasBucketCount: 128, + searchPrefixLength: 2, + }, + }; } -describe('hosted artifact contract', () => { - test('ties worker cache identity to the artifact schema', () => { - expect(HOSTED_ARTIFACT_CACHE_NAMESPACE).toBe('hosted-artifact-v2'); - }); +describe("hosted artifact contract", () => { + test("ties worker cache identity to the artifact schema", () => { + expect(HOSTED_ARTIFACT_CACHE_NAMESPACE).toBe("hosted-artifact-v2"); + }); - test('accepts current metadata for the expected crate', () => { - expect(isCurrentHostedArtifactMetadata(metadata(), { name: 'serde', version: '1.0.228' })).toBe( - true, - ); - }); + test("accepts current metadata for the expected crate", () => { + expect(isCurrentHostedArtifactMetadata(metadata(), { name: "serde", version: "1.0.228" })).toBe( + true, + ); + }); - test('rejects stale and mismatched metadata', () => { - expect(isCurrentHostedArtifactMetadata(metadata(1))).toBe(false); - expect(isCurrentHostedArtifactMetadata(metadata(), { name: 'serde', version: '1.0.227' })).toBe( - false, - ); - }); + test("rejects stale and mismatched metadata", () => { + expect(isCurrentHostedArtifactMetadata(metadata(1))).toBe(false); + expect(isCurrentHostedArtifactMetadata(metadata(), { name: "serde", version: "1.0.227" })).toBe( + false, + ); + }); }); diff --git a/codeview-ui/src/lib/hosted-contract.ts b/codeview-ui/src/lib/hosted-contract.ts index 1f45152..083e7e8 100644 --- a/codeview-ui/src/lib/hosted-contract.ts +++ b/codeview-ui/src/lib/hosted-contract.ts @@ -1,36 +1,36 @@ -import { STATIC_ARTIFACT_SCHEMA_VERSION } from '#lib/schema'; +import { STATIC_ARTIFACT_SCHEMA_VERSION } from "#lib/schema"; export const HOSTED_ARTIFACT_CACHE_NAMESPACE = `hosted-artifact-v${STATIC_ARTIFACT_SCHEMA_VERSION}`; type HostedArtifactExpectation = { - name: string; - version: string; + name: string; + version: string; }; export function isCurrentHostedArtifactMetadata( - value: unknown, - expected?: HostedArtifactExpectation, + value: unknown, + expected?: HostedArtifactExpectation, ): boolean { - if (typeof value !== 'object' || value === null) return false; - const metadata = value as Record; - if (metadata.schema_version !== STATIC_ARTIFACT_SCHEMA_VERSION) return false; - if (typeof metadata.name !== 'string' || typeof metadata.version !== 'string') return false; - if (expected && (metadata.name !== expected.name || metadata.version !== expected.version)) { - return false; - } - if (typeof metadata.index !== 'object' || metadata.index === null) return false; - if (typeof metadata.artifacts !== 'object' || metadata.artifacts === null) return false; + if (typeof value !== "object" || value === null) return false; + const metadata = value as Record; + if (metadata.schema_version !== STATIC_ARTIFACT_SCHEMA_VERSION) return false; + if (typeof metadata.name !== "string" || typeof metadata.version !== "string") return false; + if (expected && (metadata.name !== expected.name || metadata.version !== expected.version)) { + return false; + } + if (typeof metadata.index !== "object" || metadata.index === null) return false; + if (typeof metadata.artifacts !== "object" || metadata.artifacts === null) return false; - const artifacts = metadata.artifacts as Record; - return ( - artifacts.kindIndex === true && - isPositiveInteger(artifacts.nodeViewBucketCount) && - isPositiveInteger(artifacts.treeChildrenBucketCount) && - isPositiveInteger(artifacts.aliasBucketCount) && - artifacts.searchPrefixLength === 2 - ); + const artifacts = metadata.artifacts as Record; + return ( + artifacts.kindIndex === true && + isPositiveInteger(artifacts.nodeViewBucketCount) && + isPositiveInteger(artifacts.treeChildrenBucketCount) && + isPositiveInteger(artifacts.aliasBucketCount) && + artifacts.searchPrefixLength === 2 + ); } function isPositiveInteger(value: unknown): value is number { - return Number.isInteger(value) && Number(value) > 0; + return Number.isInteger(value) && Number(value) > 0; } diff --git a/codeview-ui/src/lib/index.ts b/codeview-ui/src/lib/index.ts index ee51248..0464856 100644 --- a/codeview-ui/src/lib/index.ts +++ b/codeview-ui/src/lib/index.ts @@ -1,7 +1,7 @@ -export { cn, refAttachment } from './utils.js'; +export { cn, refAttachment } from "./utils.js"; export type { - WithoutChild, - WithoutChildren, - WithoutChildrenOrChild, - WithElementRef, -} from './utils.js'; + WithoutChild, + WithoutChildren, + WithoutChildrenOrChild, + WithElementRef, +} from "./utils.js"; diff --git a/codeview-ui/src/lib/load-precedence.test.ts b/codeview-ui/src/lib/load-precedence.test.ts index 88fb585..c700176 100644 --- a/codeview-ui/src/lib/load-precedence.test.ts +++ b/codeview-ui/src/lib/load-precedence.test.ts @@ -1,21 +1,21 @@ -import { describe, expect, it } from 'vitest'; -import { hasNonEmptyArray, preferNonEmptyArray } from './load-precedence'; +import { describe, expect, it } from "vite-plus/test"; +import { hasNonEmptyArray, preferNonEmptyArray } from "./load-precedence"; -describe('load precedence', () => { - it('keeps fresh load data when client cache is empty', () => { - const loadData = [{ id: 'gpui' }]; +describe("load precedence", () => { + it("keeps fresh load data when client cache is empty", () => { + const loadData = [{ id: "gpui" }]; - expect(preferNonEmptyArray(loadData, [])).toBe(loadData); - }); + expect(preferNonEmptyArray(loadData, [])).toBe(loadData); + }); - it('uses client data when load data timed out or is missing', () => { - const clientData = [{ id: 'gpui' }]; + it("uses client data when load data timed out or is missing", () => { + const clientData = [{ id: "gpui" }]; - expect(preferNonEmptyArray(null, clientData)).toBe(clientData); - }); + expect(preferNonEmptyArray(null, clientData)).toBe(clientData); + }); - it('does not treat empty arrays as available data', () => { - expect(hasNonEmptyArray([])).toBe(false); - expect(hasNonEmptyArray([{ id: 'gpui' }])).toBe(true); - }); + it("does not treat empty arrays as available data", () => { + expect(hasNonEmptyArray([])).toBe(false); + expect(hasNonEmptyArray([{ id: "gpui" }])).toBe(true); + }); }); diff --git a/codeview-ui/src/lib/load-precedence.ts b/codeview-ui/src/lib/load-precedence.ts index 1d42486..f1cbfae 100644 --- a/codeview-ui/src/lib/load-precedence.ts +++ b/codeview-ui/src/lib/load-precedence.ts @@ -1,12 +1,12 @@ export function hasNonEmptyArray(value: T[] | null | undefined): value is T[] { - return Array.isArray(value) && value.length > 0; + return Array.isArray(value) && value.length > 0; } export function preferNonEmptyArray( - primary: T[] | null | undefined, - secondary: T[] | null | undefined, + primary: T[] | null | undefined, + secondary: T[] | null | undefined, ): T[] | null { - if (hasNonEmptyArray(primary)) return primary; - if (hasNonEmptyArray(secondary)) return secondary; - return primary ?? secondary ?? null; + if (hasNonEmptyArray(primary)) return primary; + if (hasNonEmptyArray(secondary)) return secondary; + return primary ?? secondary ?? null; } diff --git a/codeview-ui/src/lib/log.server.ts b/codeview-ui/src/lib/log.server.ts index 68159d7..7909dec 100644 --- a/codeview-ui/src/lib/log.server.ts +++ b/codeview-ui/src/lib/log.server.ts @@ -1,41 +1,41 @@ -import { Result } from 'better-result'; -import { getStreamSink, type Sink } from '@logtape/logtape'; -import { setupLogging as setupBaseLogging } from './log'; +import { Result } from "better-result"; +import { getStreamSink, type Sink } from "@logtape/logtape"; +import { setupLogging as setupBaseLogging } from "./log"; async function createFileSink(): Promise { - if (typeof globalThis.caches !== 'undefined') return null; - const logFile = process.env.LOG_FILE; - if (!logFile) return null; + if (typeof globalThis.caches !== "undefined") return null; + const logFile = process.env.LOG_FILE; + if (!logFile) return null; - const { createWriteStream } = await import('node:fs'); - const stream = createWriteStream(logFile, { flags: 'a' }); - const webStream = new WritableStream({ - write(chunk) { - stream.write(chunk); - }, - close() { - stream.end(); - }, - }); + const { createWriteStream } = await import("node:fs"); + const stream = createWriteStream(logFile, { flags: "a" }); + const webStream = new WritableStream({ + write(chunk) { + stream.write(chunk); + }, + close() { + stream.end(); + }, + }); - return getStreamSink(webStream, { - formatter: (record) => { - const timestamp = new Date(record.timestamp).toISOString(); - const level = record.level.toUpperCase(); - const category = record.category.slice(1).join(':'); - const message = record.message - .map((part) => (typeof part === 'function' ? part() : part)) - .join(''); - const properties = - record.properties && Object.keys(record.properties).length > 0 - ? ` ${Result.try(() => JSON.stringify(record.properties)).unwrapOr('[unserializable]')}` - : ''; - return `${timestamp} ${level} [${category}] ${message}${properties}\n`; - }, - }); + return getStreamSink(webStream, { + formatter: (record) => { + const timestamp = new Date(record.timestamp).toISOString(); + const level = record.level.toUpperCase(); + const category = record.category.slice(1).join(":"); + const message = record.message + .map((part) => (typeof part === "function" ? part() : part)) + .join(""); + const properties = + record.properties && Object.keys(record.properties).length > 0 + ? ` ${Result.try(() => JSON.stringify(record.properties)).unwrapOr("[unserializable]")}` + : ""; + return `${timestamp} ${level} [${category}] ${message}${properties}\n`; + }, + }); } export async function setupLogging(): Promise { - const fileSink = await createFileSink().catch(() => null); - await setupBaseLogging(fileSink ? { file: fileSink } : {}); + const fileSink = await createFileSink().catch(() => null); + await setupBaseLogging(fileSink ? { file: fileSink } : {}); } diff --git a/codeview-ui/src/lib/log.ts b/codeview-ui/src/lib/log.ts index cc56a76..49acbb6 100644 --- a/codeview-ui/src/lib/log.ts +++ b/codeview-ui/src/lib/log.ts @@ -1,113 +1,113 @@ -import { Result } from 'better-result'; +import { Result } from "better-result"; import { - configure, - getConsoleSink, - getLogger as _getLogger, - type LogLevel, - type Sink, - isLogLevel, -} from '@logtape/logtape'; + configure, + getConsoleSink, + getLogger as _getLogger, + type LogLevel, + type Sink, + isLogLevel, +} from "@logtape/logtape"; let configured = false; -const isBrowser = typeof globalThis.document !== 'undefined'; -const isCloudflare = typeof globalThis.caches !== 'undefined' && !isBrowser; +const isBrowser = typeof globalThis.document !== "undefined"; +const isCloudflare = typeof globalThis.caches !== "undefined" && !isBrowser; function isPerfEnabled(): boolean { - if (!isBrowser) return false; - try { - if (new URL(window.location.href).searchParams.has('perf')) return true; - } catch {} - try { - if (localStorage.getItem('codeview-perf') === '1') return true; - } catch {} - return false; + if (!isBrowser) return false; + try { + if (new URL(window.location.href).searchParams.has("perf")) return true; + } catch {} + try { + if (localStorage.getItem("codeview-perf") === "1") return true; + } catch {} + return false; } function resolveLogLevel(): LogLevel { - if (isBrowser) { - try { - const param = new URL(window.location.href).searchParams.get('log'); - if (param && isLogLevel(param)) return param; - } catch {} - try { - const stored = localStorage.getItem('codeview-log-level'); - if (stored && isLogLevel(stored)) return stored as LogLevel; - } catch {} - } else if (!isCloudflare) { - // Node / Bun server - try { - const envLevel = process.env.LOG_LEVEL; - if (envLevel && isLogLevel(envLevel)) return envLevel as LogLevel; - } catch {} - } - // Default: debug in dev-like, info otherwise - if (isBrowser) { - try { - if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') - return 'debug'; - } catch {} - } else if (!isCloudflare) { - try { - if (process.env.NODE_ENV !== 'production') return 'debug'; - } catch {} - } - return 'info'; + if (isBrowser) { + try { + const param = new URL(window.location.href).searchParams.get("log"); + if (param && isLogLevel(param)) return param; + } catch {} + try { + const stored = localStorage.getItem("codeview-log-level"); + if (stored && isLogLevel(stored)) return stored as LogLevel; + } catch {} + } else if (!isCloudflare) { + // Node / Bun server + try { + const envLevel = process.env.LOG_LEVEL; + if (envLevel && isLogLevel(envLevel)) return envLevel as LogLevel; + } catch {} + } + // Default: debug in dev-like, info otherwise + if (isBrowser) { + try { + if (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") + return "debug"; + } catch {} + } else if (!isCloudflare) { + try { + if (process.env.NODE_ENV !== "production") return "debug"; + } catch {} + } + return "info"; } export async function setupLogging(extraSinks: Record = {}): Promise { - if (configured) return; - configured = true; + if (configured) return; + configured = true; - const perfEnabled = isPerfEnabled(); - const logLevel = resolveLogLevel(); - const allSinks = ['console', ...Object.keys(extraSinks)]; + const perfEnabled = isPerfEnabled(); + const logLevel = resolveLogLevel(); + const allSinks = ["console", ...Object.keys(extraSinks)]; - await configure({ - sinks: { - console: getConsoleSink({ - formatter: (record) => { - const cat = record.category.slice(1).join(':'); - const prefix = `[${cat}]`; - const msg = record.message.map((p) => (typeof p === 'function' ? p() : p)).join(''); - const props = - record.properties && Object.keys(record.properties).length > 0 - ? ' ' + - Result.try(() => JSON.stringify(record.properties)).unwrapOr('[unserializable]') - : ''; - return [`${prefix} ${msg}${props}`]; - }, - }), - ...extraSinks, - }, - loggers: [ - { - category: ['logtape', 'meta'], - sinks: [], - }, - { - category: ['codeview', 'perf'], - sinks: perfEnabled ? allSinks : [], - parentSinks: 'override', - lowestLevel: 'debug', - }, - { - category: ['codeview'], - sinks: allSinks, - lowestLevel: logLevel, - }, - ], - }); + await configure({ + sinks: { + console: getConsoleSink({ + formatter: (record) => { + const cat = record.category.slice(1).join(":"); + const prefix = `[${cat}]`; + const msg = record.message.map((p) => (typeof p === "function" ? p() : p)).join(""); + const props = + record.properties && Object.keys(record.properties).length > 0 + ? " " + + Result.try(() => JSON.stringify(record.properties)).unwrapOr("[unserializable]") + : ""; + return [`${prefix} ${msg}${props}`]; + }, + }), + ...extraSinks, + }, + loggers: [ + { + category: ["logtape", "meta"], + sinks: [], + }, + { + category: ["codeview", "perf"], + sinks: perfEnabled ? allSinks : [], + parentSinks: "override", + lowestLevel: "debug", + }, + { + category: ["codeview"], + sinks: allSinks, + lowestLevel: logLevel, + }, + ], + }); } export function getLogger(...category: string[]) { - return _getLogger(['codeview', ...category]); + return _getLogger(["codeview", ...category]); } export function getPerfLogger(category: string) { - return _getLogger(['codeview', 'perf', category]); + return _getLogger(["codeview", "perf", category]); } export function getLoggerWith(category: string, context: Record) { - return _getLogger(['codeview', category]).with(context); + return _getLogger(["codeview", category]).with(context); } diff --git a/codeview-ui/src/lib/node-order.ts b/codeview-ui/src/lib/node-order.ts index 18567ed..a3dd8db 100644 --- a/codeview-ui/src/lib/node-order.ts +++ b/codeview-ui/src/lib/node-order.ts @@ -1,40 +1,40 @@ -import type { NodeKind } from '#lib/graph'; +import type { NodeKind } from "#lib/graph"; export const kindOrder: Record = { - Crate: 0, - Module: 1, - TypeAlias: 2, - Struct: 3, - StructField: 4, - Enum: 5, - Variant: 6, - Union: 7, - Function: 8, - AssocType: 9, - Constant: 10, - AssocConst: 11, - Static: 12, - Macro: 13, - ProcMacro: 14, - Primitive: 15, - ExternCrate: 16, - Import: 17, - Impl: 18, - Trait: 19, - TraitAlias: 20, + Crate: 0, + Module: 1, + TypeAlias: 2, + Struct: 3, + StructField: 4, + Enum: 5, + Variant: 6, + Union: 7, + Function: 8, + AssocType: 9, + Constant: 10, + AssocConst: 11, + Static: 12, + Macro: 13, + ProcMacro: 14, + Primitive: 15, + ExternCrate: 16, + Import: 17, + Impl: 18, + Trait: 19, + TraitAlias: 20, }; export type OrderedNodeLike = { - id?: string; - name: string; - kind: NodeKind; + id?: string; + name: string; + kind: NodeKind; }; export function compareNodeLike(a: OrderedNodeLike, b: OrderedNodeLike): number { - const kindDiff = (kindOrder[a.kind] ?? 99) - (kindOrder[b.kind] ?? 99); - if (kindDiff !== 0) return kindDiff; - if (a.name !== b.name) return a.name < b.name ? -1 : 1; - const aId = a.id ?? ''; - const bId = b.id ?? ''; - return aId < bId ? -1 : aId > bId ? 1 : 0; + const kindDiff = (kindOrder[a.kind] ?? 99) - (kindOrder[b.kind] ?? 99); + if (kindDiff !== 0) return kindDiff; + if (a.name !== b.name) return a.name < b.name ? -1 : 1; + const aId = a.id ?? ""; + const bId = b.id ?? ""; + return aId < bId ? -1 : aId > bId ? 1 : 0; } diff --git a/codeview-ui/src/lib/node-summary.test.ts b/codeview-ui/src/lib/node-summary.test.ts index a20e908..c5708fd 100644 --- a/codeview-ui/src/lib/node-summary.test.ts +++ b/codeview-ui/src/lib/node-summary.test.ts @@ -1,54 +1,50 @@ -import { describe, expect, it } from 'vitest'; -import type { CrateGraph, Node } from '#lib/schema'; -import { buildCrateTree } from './node-summary'; +import { describe, expect, it } from "vite-plus/test"; +import type { CrateGraph, Node } from "#lib/schema"; +import { buildCrateTree } from "./node-summary"; -const publicVisibility = { kind: 'Public' } as const; +const publicVisibility = { kind: "Public" } as const; -function node(id: string, name: string, kind: Node['kind'], isExternal = false): Node { - return { - id, - name, - kind, - visibility: publicVisibility, - attrs: [], - ...(isExternal ? { is_external: true } : {}), - }; +function node(id: string, name: string, kind: Node["kind"], isExternal = false): Node { + return { + id, + name, + kind, + visibility: publicVisibility, + attrs: [], + ...(isExternal ? { is_external: true } : {}), + }; } -describe('buildCrateTree', () => { - it('keeps internal nodes and structural edges only', () => { - const graph: CrateGraph = { - id: 'demo', - name: 'demo', - version: '1.0.0', - nodes: [ - node('demo', 'demo', 'Crate'), - node('demo::map', 'map', 'Module'), - node('demo::map::Drain', 'Drain', 'Struct'), - node('alloc::Allocator', 'Allocator', 'Trait', true), - ], - edges: [ - { from: 'demo', to: 'demo::map', kind: 'Contains', confidence: 'Static' }, - { from: 'demo::map', to: 'demo::map::Drain', kind: 'Defines', confidence: 'Static' }, - { - from: 'demo::map::Drain', - to: 'alloc::Allocator', - kind: 'UsesType', - confidence: 'Static', - }, - ], - }; +describe("buildCrateTree", () => { + it("keeps internal nodes and structural edges only", () => { + const graph: CrateGraph = { + id: "demo", + name: "demo", + version: "1.0.0", + nodes: [ + node("demo", "demo", "Crate"), + node("demo::map", "map", "Module"), + node("demo::map::Drain", "Drain", "Struct"), + node("alloc::Allocator", "Allocator", "Trait", true), + ], + edges: [ + { from: "demo", to: "demo::map", kind: "Contains", confidence: "Static" }, + { from: "demo::map", to: "demo::map::Drain", kind: "Defines", confidence: "Static" }, + { + from: "demo::map::Drain", + to: "alloc::Allocator", + kind: "UsesType", + confidence: "Static", + }, + ], + }; - const tree = buildCrateTree(graph); + const tree = buildCrateTree(graph); - expect(tree.nodes.map((entry) => entry.id)).toEqual([ - 'demo', - 'demo::map', - 'demo::map::Drain', - ]); - expect(tree.edges.map((entry) => [entry.from, entry.to, entry.kind])).toEqual([ - ['demo', 'demo::map', 'Contains'], - ['demo::map', 'demo::map::Drain', 'Defines'], - ]); - }); + expect(tree.nodes.map((entry) => entry.id)).toEqual(["demo", "demo::map", "demo::map::Drain"]); + expect(tree.edges.map((entry) => [entry.from, entry.to, entry.kind])).toEqual([ + ["demo", "demo::map", "Contains"], + ["demo::map", "demo::map::Drain", "Defines"], + ]); + }); }); diff --git a/codeview-ui/src/lib/node-summary.ts b/codeview-ui/src/lib/node-summary.ts index 3ac0e9f..4417731 100644 --- a/codeview-ui/src/lib/node-summary.ts +++ b/codeview-ui/src/lib/node-summary.ts @@ -1,34 +1,34 @@ -import type { CrateGraph, CrateTree, Edge, Node, NodeSummary } from '#lib/schema'; +import type { CrateGraph, CrateTree, Edge, Node, NodeSummary } from "#lib/schema"; export function summarizeNode(node: Node): NodeSummary { - return { - id: node.id, - name: node.name, - kind: node.kind, - visibility: node.visibility, - is_external: node.is_external, - is_deprecated: node.is_deprecated, - ...(node.kind === 'Impl' - ? { - impl_trait: node.impl_trait, - impl_category: node.impl_category, - generics: node.generics, - } - : {}), - }; + return { + id: node.id, + name: node.name, + kind: node.kind, + visibility: node.visibility, + is_external: node.is_external, + is_deprecated: node.is_deprecated, + ...(node.kind === "Impl" + ? { + impl_trait: node.impl_trait, + impl_category: node.impl_category, + generics: node.generics, + } + : {}), + }; } -export function buildCrateTree(graph: Pick): CrateTree { - const internalNodes = graph.nodes.filter((node) => !node.is_external); - const internalIds = new Set(internalNodes.map((node) => node.id)); - const structuralEdges = graph.edges.filter( - (edge): edge is Edge => - (edge.kind === 'Contains' || edge.kind === 'Defines') && - internalIds.has(edge.from) && - internalIds.has(edge.to), - ); - return { - nodes: internalNodes.map(summarizeNode), - edges: structuralEdges, - }; +export function buildCrateTree(graph: Pick): CrateTree { + const internalNodes = graph.nodes.filter((node) => !node.is_external); + const internalIds = new Set(internalNodes.map((node) => node.id)); + const structuralEdges = graph.edges.filter( + (edge): edge is Edge => + (edge.kind === "Contains" || edge.kind === "Defines") && + internalIds.has(edge.from) && + internalIds.has(edge.to), + ); + return { + nodes: internalNodes.map(summarizeNode), + edges: structuralEdges, + }; } diff --git a/codeview-ui/src/lib/pagination.test.ts b/codeview-ui/src/lib/pagination.test.ts index e926f50..8e4fd2f 100644 --- a/codeview-ui/src/lib/pagination.test.ts +++ b/codeview-ui/src/lib/pagination.test.ts @@ -1,19 +1,19 @@ -import { describe, expect, it } from 'vitest'; -import { paginationHref, readPageParam } from './pagination'; +import { describe, expect, it } from "vite-plus/test"; +import { paginationHref, readPageParam } from "./pagination"; -describe('pagination URL state', () => { - it('clamps invalid pages to the available range', () => { - expect( - readPageParam(new URL('https://codeview.test/queue?recentPage=99'), 'recentPage', 4), - ).toBe(4); - expect( - readPageParam(new URL('https://codeview.test/queue?recentPage=-2'), 'recentPage', 4), - ).toBe(1); - }); +describe("pagination URL state", () => { + it("clamps invalid pages to the available range", () => { + expect( + readPageParam(new URL("https://codeview.test/queue?recentPage=99"), "recentPage", 4), + ).toBe(4); + expect( + readPageParam(new URL("https://codeview.test/queue?recentPage=-2"), "recentPage", 4), + ).toBe(1); + }); - it('preserves unrelated query state', () => { - expect( - paginationHref(new URL('https://codeview.test/queue?activePage=2'), 'recentPage', 3), - ).toBe('/queue?activePage=2&recentPage=3'); - }); + it("preserves unrelated query state", () => { + expect( + paginationHref(new URL("https://codeview.test/queue?activePage=2"), "recentPage", 3), + ).toBe("/queue?activePage=2&recentPage=3"); + }); }); diff --git a/codeview-ui/src/lib/pagination.ts b/codeview-ui/src/lib/pagination.ts index 09ab874..c25fb9a 100644 --- a/codeview-ui/src/lib/pagination.ts +++ b/codeview-ui/src/lib/pagination.ts @@ -1,12 +1,17 @@ -export function readPageParam(url: URL, name: string, pageCount: number): number { - const raw = Number.parseInt(url.searchParams.get(name) ?? '1', 10); - if (!Number.isFinite(raw)) return 1; - return Math.min(Math.max(raw, 1), Math.max(pageCount, 1)); +type SearchParamsReader = { + href: string; + searchParams: { get(name: string): string | null }; +}; + +export function readPageParam(url: SearchParamsReader, name: string, pageCount: number): number { + const raw = Number.parseInt(url.searchParams.get(name) ?? "1", 10); + if (!Number.isFinite(raw)) return 1; + return Math.min(Math.max(raw, 1), Math.max(pageCount, 1)); } -export function paginationHref(url: URL, name: string, page: number): string { - const next = new URL(url); - if (page <= 1) next.searchParams.delete(name); - else next.searchParams.set(name, String(page)); - return `${next.pathname}${next.search}${next.hash}`; +export function paginationHref(url: SearchParamsReader, name: string, page: number): string { + const next = new URL(url.href); + if (page <= 1) next.searchParams.delete(name); + else next.searchParams.set(name, String(page)); + return `${next.pathname}${next.search}${next.hash}`; } diff --git a/codeview-ui/src/lib/perf.svelte.ts b/codeview-ui/src/lib/perf.svelte.ts index bc54bec..d7f9db1 100644 --- a/codeview-ui/src/lib/perf.svelte.ts +++ b/codeview-ui/src/lib/perf.svelte.ts @@ -1,15 +1,15 @@ -import { tick } from 'svelte'; -import { getPerfLogger } from './log'; +import { tick } from "svelte"; +import { getPerfLogger } from "./log"; /** * Measures time from call until Svelte's `tick()` resolves (render commit). */ export function perfTick(cat: string, label: string): void { - const t0 = performance.now(); - tick().then(() => { - const dt = performance.now() - t0; - getPerfLogger(cat).debug(`${label} ${dt.toFixed(0)}ms`); - }); + const t0 = performance.now(); + tick().then(() => { + const dt = performance.now() - t0; + getPerfLogger(cat).debug(`${label} ${dt.toFixed(0)}ms`); + }); } /** @@ -17,13 +17,13 @@ export function perfTick(cat: string, label: string): void { * Only measures a new tick when `key` changes. */ export function createTickTracker(cat: string, label: string) { - let lastKey: unknown = undefined; - return { - track(key: unknown) { - if (key !== lastKey) { - lastKey = key; - perfTick(cat, label); - } - }, - }; + let lastKey: unknown = undefined; + return { + track(key: unknown) { + if (key !== lastKey) { + lastKey = key; + perfTick(cat, label); + } + }, + }; } diff --git a/codeview-ui/src/lib/perf.ts b/codeview-ui/src/lib/perf.ts index 0344a46..703c8d1 100644 --- a/codeview-ui/src/lib/perf.ts +++ b/codeview-ui/src/lib/perf.ts @@ -1,112 +1,112 @@ -import { getPerfLogger } from './log'; +import { getPerfLogger } from "./log"; type DetailFn = string | ((result: T) => string); const perfNow = () => (globalThis.performance?.now ? globalThis.performance.now() : Date.now()); const raf = - typeof requestAnimationFrame === 'function' - ? requestAnimationFrame - : (cb: (time: number) => void) => setTimeout(() => cb(perfNow()), 16); + typeof requestAnimationFrame === "function" + ? requestAnimationFrame + : (cb: (time: number) => void) => setTimeout(() => cb(perfNow()), 16); function resolveDetail(detail: DetailFn | undefined, result: T): string { - if (!detail) return ''; - if (typeof detail === 'string') return detail; - return detail(result); + if (!detail) return ""; + if (typeof detail === "string") return detail; + return detail(result); } function formatMsg(label: string, dt: number, detail?: string): string { - const suffix = detail ? ` (${detail})` : ''; - return `${label} ${dt.toFixed(1)}ms${suffix}`; + const suffix = detail ? ` (${detail})` : ""; + return `${label} ${dt.toFixed(1)}ms${suffix}`; } export const perf = { - time( - cat: string, - label: string, - fn: () => T, - opts?: { threshold?: number; detail?: DetailFn }, - ): T { - const t0 = perfNow(); - const result = fn(); - const dt = perfNow() - t0; - const threshold = opts?.threshold ?? 2; - if (dt > threshold) { - getPerfLogger(cat).debug(formatMsg(label, dt, resolveDetail(opts?.detail, result))); - } - return result; - }, + time( + cat: string, + label: string, + fn: () => T, + opts?: { threshold?: number; detail?: DetailFn }, + ): T { + const t0 = perfNow(); + const result = fn(); + const dt = perfNow() - t0; + const threshold = opts?.threshold ?? 2; + if (dt > threshold) { + getPerfLogger(cat).debug(formatMsg(label, dt, resolveDetail(opts?.detail, result))); + } + return result; + }, - async timeAsync( - cat: string, - label: string, - fn: () => Promise, - opts?: { threshold?: number; detail?: DetailFn }, - ): Promise { - const t0 = perfNow(); - const result = await fn(); - const dt = perfNow() - t0; - const threshold = opts?.threshold ?? 2; - if (dt > threshold) { - getPerfLogger(cat).debug(formatMsg(label, dt, resolveDetail(opts?.detail, result))); - } - return result; - }, + async timeAsync( + cat: string, + label: string, + fn: () => Promise, + opts?: { threshold?: number; detail?: DetailFn }, + ): Promise { + const t0 = perfNow(); + const result = await fn(); + const dt = perfNow() - t0; + const threshold = opts?.threshold ?? 2; + if (dt > threshold) { + getPerfLogger(cat).debug(formatMsg(label, dt, resolveDetail(opts?.detail, result))); + } + return result; + }, - timeAlways(cat: string, label: string, fn: () => T, opts?: { detail?: DetailFn }): T { - const t0 = perfNow(); - const result = fn(); - const dt = perfNow() - t0; - getPerfLogger(cat).debug(formatMsg(label, dt, resolveDetail(opts?.detail, result))); - return result; - }, + timeAlways(cat: string, label: string, fn: () => T, opts?: { detail?: DetailFn }): T { + const t0 = perfNow(); + const result = fn(); + const dt = perfNow() - t0; + getPerfLogger(cat).debug(formatMsg(label, dt, resolveDetail(opts?.detail, result))); + return result; + }, - begin(cat: string, label: string): { end: () => void } { - const t0 = perfNow(); - const logger = getPerfLogger(cat); - logger.debug(`${label} start`); - return { - end() { - const dt = perfNow() - t0; - logger.debug(`${label} ${dt.toFixed(0)}ms`); - }, - }; - }, + begin(cat: string, label: string): { end: () => void } { + const t0 = perfNow(); + const logger = getPerfLogger(cat); + logger.debug(`${label} start`); + return { + end() { + const dt = perfNow() - t0; + logger.debug(`${label} ${dt.toFixed(0)}ms`); + }, + }; + }, - /** Log a one-shot event (no timing, just a message). */ - event(cat: string, label: string, detail?: string): void { - const suffix = detail ? ` (${detail})` : ''; - getPerfLogger(cat).debug(`${label}${suffix}`); - }, + /** Log a one-shot event (no timing, just a message). */ + event(cat: string, label: string, detail?: string): void { + const suffix = detail ? ` (${detail})` : ""; + getPerfLogger(cat).debug(`${label}${suffix}`); + }, - frame(cat: string, label: string, fn: () => T): T { - const t0 = perfNow(); - const result = fn(); - const dt = perfNow() - t0; + frame(cat: string, label: string, fn: () => T): T { + const t0 = perfNow(); + const result = fn(); + const dt = perfNow() - t0; - // Accumulate into per-label frame counter - let entry = _frameCounters.get(label); - if (!entry) { - entry = { count: 0, totalMs: 0, scheduled: false }; - _frameCounters.set(label, entry); - } - entry.count++; - entry.totalMs += dt; + // Accumulate into per-label frame counter + let entry = _frameCounters.get(label); + if (!entry) { + entry = { count: 0, totalMs: 0, scheduled: false }; + _frameCounters.set(label, entry); + } + entry.count++; + entry.totalMs += dt; - if (!entry.scheduled) { - entry.scheduled = true; - raf(() => { - const logger = getPerfLogger(cat); - logger.debug( - `${label} recomputed ${entry!.count}x this frame (${entry!.totalMs.toFixed(1)}ms total)`, - ); - entry!.count = 0; - entry!.totalMs = 0; - entry!.scheduled = false; - }); - } + if (!entry.scheduled) { + entry.scheduled = true; + raf(() => { + const logger = getPerfLogger(cat); + logger.debug( + `${label} recomputed ${entry!.count}x this frame (${entry!.totalMs.toFixed(1)}ms total)`, + ); + entry!.count = 0; + entry!.totalMs = 0; + entry!.scheduled = false; + }); + } - return result; - }, + return result; + }, }; const _frameCounters = new Map(); diff --git a/codeview-ui/src/lib/platform.ts b/codeview-ui/src/lib/platform.ts index 05058ec..5baee5f 100644 --- a/codeview-ui/src/lib/platform.ts +++ b/codeview-ui/src/lib/platform.ts @@ -1,7 +1,7 @@ -import { PUBLIC_CODEVIEW_PLATFORM } from '$env/static/public'; +import { PUBLIC_CODEVIEW_PLATFORM } from "$app/env/public"; /** Build-time platform identifier — 'cloudflare' | 'local' etc. */ export const platform = PUBLIC_CODEVIEW_PLATFORM; /** True when built for a hosted platform (Cloudflare, Vercel, etc.) */ -export const isHosted = platform === 'cloudflare'; +export const isHosted = platform === "cloudflare"; diff --git a/codeview-ui/src/lib/preferences.ts b/codeview-ui/src/lib/preferences.ts index edac9cb..7329bc0 100644 --- a/codeview-ui/src/lib/preferences.ts +++ b/codeview-ui/src/lib/preferences.ts @@ -1,154 +1,154 @@ import type { - AccentMode, - CodeTheme, - DensityMode, - DocLayoutMode, - ExternalLinkMode, - SourceProviderMode, - Theme, - TextSizeMode, - VcsMode, - VoiceMode, -} from './context'; + AccentMode, + CodeTheme, + DensityMode, + DocLayoutMode, + ExternalLinkMode, + SourceProviderMode, + Theme, + TextSizeMode, + VcsMode, + VoiceMode, +} from "./context"; export const PREF_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365; -export const THEME_KEY = 'codeview-theme'; -export const ACCENT_KEY = 'codeview-accent'; -export const DENSITY_KEY = 'codeview-density'; -export const TEXT_SIZE_KEY = 'codeview-text-size'; -export const VOICE_KEY = 'codeview-voice'; -export const DOC_LAYOUT_KEY = 'codeview-doc-layout'; -export const CODE_LIGHT_KEY = 'codeview-code-light'; -export const CODE_DARK_KEY = 'codeview-code-dark'; -export const EXT_LINK_KEY = 'codeview-ext-link-mode'; -export const SOURCE_PROVIDER_KEY = 'codeview-source-provider-mode'; -export const VCS_KEY = 'codeview-vcs'; -export const EDITOR_KEY = 'codeview-editor'; -export const CUSTOM_EDITOR_KEY = 'codeview-editor-custom'; -export const SOURCE_ROOT_KEY = 'codeview-source-root'; +export const THEME_KEY = "codeview-theme"; +export const ACCENT_KEY = "codeview-accent"; +export const DENSITY_KEY = "codeview-density"; +export const TEXT_SIZE_KEY = "codeview-text-size"; +export const VOICE_KEY = "codeview-voice"; +export const DOC_LAYOUT_KEY = "codeview-doc-layout"; +export const CODE_LIGHT_KEY = "codeview-code-light"; +export const CODE_DARK_KEY = "codeview-code-dark"; +export const EXT_LINK_KEY = "codeview-ext-link-mode"; +export const SOURCE_PROVIDER_KEY = "codeview-source-provider-mode"; +export const VCS_KEY = "codeview-vcs"; +export const EDITOR_KEY = "codeview-editor"; +export const CUSTOM_EDITOR_KEY = "codeview-editor-custom"; +export const SOURCE_ROOT_KEY = "codeview-source-root"; -export const THEME_VALUES = ['light', 'dark', 'system'] as const satisfies readonly Theme[]; +export const THEME_VALUES = ["light", "dark", "system"] as const satisfies readonly Theme[]; export const ACCENT_VALUES = [ - 'orange', - 'cobalt', - 'forest', - 'plum', - 'char', + "orange", + "cobalt", + "forest", + "plum", + "char", ] as const satisfies readonly AccentMode[]; export const DENSITY_VALUES = [ - 'compact', - 'comfortable', - 'spacious', + "compact", + "comfortable", + "spacious", ] as const satisfies readonly DensityMode[]; export const TEXT_SIZE_VALUES = [ - 'standard', - 'large', - 'extra-large', + "standard", + "large", + "extra-large", ] as const satisfies readonly TextSizeMode[]; export const VOICE_VALUES = [ - 'editorial', - 'technical', - 'geometric', + "editorial", + "technical", + "geometric", ] as const satisfies readonly VoiceMode[]; export const DOC_LAYOUT_VALUES = [ - 'classic', - 'reading', - 'split', + "classic", + "reading", + "split", ] as const satisfies readonly DocLayoutMode[]; export const CODE_LIGHT_VALUES = [ - 'solarized-light', - 'catppuccin-latte', - 'one-light', - 'github-light', + "solarized-light", + "catppuccin-latte", + "one-light", + "github-light", ] as const satisfies readonly CodeTheme[]; export const CODE_DARK_VALUES = [ - 'solarized-dark', - 'catppuccin-mocha', - 'one-dark', - 'github-dark', + "solarized-dark", + "catppuccin-mocha", + "one-dark", + "github-dark", ] as const satisfies readonly CodeTheme[]; -export const EXT_LINK_VALUES = ['codeview', 'docs'] as const satisfies readonly ExternalLinkMode[]; +export const EXT_LINK_VALUES = ["codeview", "docs"] as const satisfies readonly ExternalLinkMode[]; export const SOURCE_PROVIDER_VALUES = [ - 'auto', - 'crates-io', - 'github', + "auto", + "crates-io", + "github", ] as const satisfies readonly SourceProviderMode[]; -export const VCS_VALUES = ['git', 'jj'] as const satisfies readonly VcsMode[]; -export const EDITOR_VALUES = ['vscode', 'cursor', 'zed', 'neovim', 'custom'] as const; +export const VCS_VALUES = ["git", "jj"] as const satisfies readonly VcsMode[]; +export const EDITOR_VALUES = ["vscode", "cursor", "zed", "neovim", "custom"] as const; export type EditorId = (typeof EDITOR_VALUES)[number]; export function readAllowedPreference( - value: string | null | undefined, - allowed: readonly T[], - fallback: T, + value: string | null | undefined, + allowed: readonly T[], + fallback: T, ): T { - return value && (allowed as readonly string[]).includes(value) ? (value as T) : fallback; + return value && (allowed as readonly string[]).includes(value) ? (value as T) : fallback; } export function readClientPref(key: string, fallback: string): string { - const cookieValue = readClientCookie(key); - if (cookieValue !== null) return cookieValue; + const cookieValue = readClientCookie(key); + if (cookieValue !== null) return cookieValue; - try { - if (typeof localStorage === 'undefined') return fallback; - return localStorage.getItem(key) ?? fallback; - } catch { - return fallback; - } + try { + if (typeof localStorage === "undefined") return fallback; + return localStorage.getItem(key) ?? fallback; + } catch { + return fallback; + } } export function readStoredPref( - key: string, - allowed: readonly T[], - fallback: T, + key: string, + allowed: readonly T[], + fallback: T, ): T { - return readAllowedPreference(readClientPref(key, fallback), allowed, fallback); + return readAllowedPreference(readClientPref(key, fallback), allowed, fallback); } export function writePref(key: string, value: string): void { - try { - if (typeof localStorage !== 'undefined') { - localStorage.setItem(key, value); - } - } catch { - // A blocked localStorage write should not prevent the SSR cookie mirror. - } + try { + if (typeof localStorage !== "undefined") { + localStorage.setItem(key, value); + } + } catch { + // A blocked localStorage write should not prevent the SSR cookie mirror. + } - if (typeof document !== 'undefined') { - document.cookie = `${key}=${encodeURIComponent( - value, - )}; path=/; max-age=${PREF_COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`; - } + if (typeof document !== "undefined") { + document.cookie = `${key}=${encodeURIComponent( + value, + )}; path=/; max-age=${PREF_COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`; + } } export function writeClientPref(key: string, value: string): void { - try { - if (typeof localStorage === 'undefined') return; - const next = value.trim(); - if (next) localStorage.setItem(key, next); - else localStorage.removeItem(key); - } catch { - // Local integration preferences are best-effort browser state. - } + try { + if (typeof localStorage === "undefined") return; + const next = value.trim(); + if (next) localStorage.setItem(key, next); + else localStorage.removeItem(key); + } catch { + // Local integration preferences are best-effort browser state. + } } function readClientCookie(key: string): string | null { - if (typeof document === 'undefined' || !document.cookie) return null; + if (typeof document === "undefined" || !document.cookie) return null; - const prefix = `${key}=`; - for (const rawPart of document.cookie.split(';')) { - const part = rawPart.trim(); - if (!part.startsWith(prefix)) continue; + const prefix = `${key}=`; + for (const rawPart of document.cookie.split(";")) { + const part = rawPart.trim(); + if (!part.startsWith(prefix)) continue; - const rawValue = part.slice(prefix.length); - try { - return decodeURIComponent(rawValue); - } catch { - return rawValue; - } - } + const rawValue = part.slice(prefix.length); + try { + return decodeURIComponent(rawValue); + } catch { + return rawValue; + } + } - return null; + return null; } diff --git a/codeview-ui/src/lib/realtime/constants.ts b/codeview-ui/src/lib/realtime/constants.ts index 773e9b2..82dd5d0 100644 --- a/codeview-ui/src/lib/realtime/constants.ts +++ b/codeview-ui/src/lib/realtime/constants.ts @@ -1,44 +1,44 @@ export const STEP_ORDER = [ - 'queued', - 'waiting-capacity', - 'waiting-github-capacity', - 'waiting-rate-limit', - 'workflow-started', - 'github-running', - 'resolving', - 'fetching', - 'parsing', - 'finalizing', - 'storing', - 'indexing', + "queued", + "waiting-capacity", + "waiting-github-capacity", + "waiting-rate-limit", + "workflow-started", + "github-running", + "resolving", + "fetching", + "parsing", + "finalizing", + "storing", + "indexing", ]; export const stepLabels: Record = { - queued: 'Queued...', - 'waiting-capacity': 'Waiting for parser capacity...', - 'waiting-github-capacity': 'Waiting for parser capacity...', - 'waiting-rate-limit': 'Waiting for parser capacity...', - 'workflow-started': 'Starting parser workflow...', - 'github-running': 'Running parser job...', - resolving: 'Resolving metadata...', - fetching: 'Downloading rustdoc...', - parsing: 'Extracting graph...', - finalizing: 'Resolving edges...', - storing: 'Uploading graph...', - indexing: 'Indexing dependencies...', + queued: "Queued...", + "waiting-capacity": "Waiting for parser capacity...", + "waiting-github-capacity": "Waiting for parser capacity...", + "waiting-rate-limit": "Waiting for parser capacity...", + "workflow-started": "Starting parser workflow...", + "github-running": "Running parser job...", + resolving: "Resolving metadata...", + fetching: "Downloading rustdoc...", + parsing: "Extracting graph...", + finalizing: "Resolving edges...", + storing: "Uploading graph...", + indexing: "Indexing dependencies...", }; export const stepPercents: Record = { - queued: 2, - 'waiting-capacity': 3, - 'waiting-github-capacity': 3, - 'waiting-rate-limit': 3, - 'workflow-started': 5, - 'github-running': 8, - resolving: 5, - fetching: 10, - parsing: 15, - finalizing: 60, - storing: 85, - indexing: 92, + queued: 2, + "waiting-capacity": 3, + "waiting-github-capacity": 3, + "waiting-rate-limit": 3, + "workflow-started": 5, + "github-running": 8, + resolving: 5, + fetching: 10, + parsing: 15, + finalizing: 60, + storing: 85, + indexing: 92, }; diff --git a/codeview-ui/src/lib/realtime/index.ts b/codeview-ui/src/lib/realtime/index.ts index 1cbdcf6..cd274b4 100644 --- a/codeview-ui/src/lib/realtime/index.ts +++ b/codeview-ui/src/lib/realtime/index.ts @@ -1,7 +1,7 @@ -export { STEP_ORDER, stepLabels, stepPercents } from './constants'; -export { CrateStatusConnection } from './status.svelte'; -export { ParseProgressConnection } from './progress.svelte'; -export { ProcessingStatusConnection } from './processing.svelte'; -export { QueueStatusConnection } from './queue.svelte'; -export { CrossEdgeUpdatesConnection } from './updates.svelte'; -export type { RealtimeCallback, RealtimeClient } from './types'; +export { STEP_ORDER, stepLabels, stepPercents } from "./constants"; +export { CrateStatusConnection } from "./status.svelte"; +export { ParseProgressConnection } from "./progress.svelte"; +export { ProcessingStatusConnection } from "./processing.svelte"; +export { QueueStatusConnection } from "./queue.svelte"; +export { CrossEdgeUpdatesConnection } from "./updates.svelte"; +export type { RealtimeCallback, RealtimeClient } from "./types"; diff --git a/codeview-ui/src/lib/realtime/processing.svelte.ts b/codeview-ui/src/lib/realtime/processing.svelte.ts index 0f59903..dec58f5 100644 --- a/codeview-ui/src/lib/realtime/processing.svelte.ts +++ b/codeview-ui/src/lib/realtime/processing.svelte.ts @@ -1,75 +1,75 @@ -import { getLogger } from '#lib/log'; -import { connect } from '$realtime'; -import type { CrateSummaryResult } from '#lib/server/provider'; -import type { RealtimeClient } from './types'; +import { getLogger } from "#lib/log"; +import { connect } from "$realtime"; +import type { CrateSummaryResult } from "#lib/server/provider"; +import type { RealtimeClient } from "./types"; interface ProcessingMessage { - type?: string; - count?: number; - crates?: unknown; + type?: string; + count?: number; + crates?: unknown; } export class ProcessingStatusConnection implements Disposable { - count = $state(0); - crates = $state.raw([]); + count = $state(0); + crates = $state.raw([]); - #client: RealtimeClient = connect(); - #log = getLogger('processing'); - #ecosystem = 'rust'; - #currentTag: string | null = null; - #callback = (data: unknown) => this.#onData(data as ProcessingMessage); + #client: RealtimeClient = connect(); + #log = getLogger("processing"); + #ecosystem = "rust"; + #currentTag: string | null = null; + #callback = (data: unknown) => this.#onData(data as ProcessingMessage); - get tag() { - return `processing:${this.#ecosystem}`; - } + get tag() { + return `processing:${this.#ecosystem}`; + } - connect(ecosystem = 'rust') { - if (this.#ecosystem === ecosystem && this.#currentTag) return; - this.disconnect(); + connect(ecosystem = "rust") { + if (this.#ecosystem === ecosystem && this.#currentTag) return; + this.disconnect(); - this.#ecosystem = ecosystem; - const tag = `processing:${ecosystem}`; - this.#currentTag = tag; + this.#ecosystem = ecosystem; + const tag = `processing:${ecosystem}`; + this.#currentTag = tag; - this.#log.debug`connect ${this.tag}`; + this.#log.debug`connect ${this.tag}`; - this.#client.subscribe(tag, this.#callback); - } + this.#client.subscribe(tag, this.#callback); + } - disconnect() { - if (this.#currentTag) { - this.#client.unsubscribe(this.#currentTag, this.#callback); - this.#currentTag = null; - } - } + disconnect() { + if (this.#currentTag) { + this.#client.unsubscribe(this.#currentTag, this.#callback); + this.#currentTag = null; + } + } - #onData(msg: ProcessingMessage) { - if (msg.type && msg.type !== 'processing') return; - if (typeof msg.count === 'number') { - this.#log.debug`msg ${this.tag} count=${String(msg.count)}`; - this.count = msg.count; - } - if (Array.isArray(msg.crates)) { - this.crates = msg.crates.filter(isCrateSummary); - } - } + #onData(msg: ProcessingMessage) { + if (msg.type && msg.type !== "processing") return; + if (typeof msg.count === "number") { + this.#log.debug`msg ${this.tag} count=${String(msg.count)}`; + this.count = msg.count; + } + if (Array.isArray(msg.crates)) { + this.crates = msg.crates.filter(isCrateSummary); + } + } - destroy() { - this.disconnect(); - } + destroy() { + this.disconnect(); + } - [Symbol.dispose]() { - this.destroy(); - } + [Symbol.dispose]() { + this.destroy(); + } } function isCrateSummary(value: unknown): value is CrateSummaryResult { - if (!value || typeof value !== 'object') return false; - const crate = value as Partial; - return ( - typeof crate.name === 'string' && - typeof crate.version === 'string' && - (crate.id === undefined || typeof crate.id === 'string') && - (crate.description === undefined || typeof crate.description === 'string') - ); + if (!value || typeof value !== "object") return false; + const crate = value as Partial; + return ( + typeof crate.name === "string" && + typeof crate.version === "string" && + (crate.id === undefined || typeof crate.id === "string") && + (crate.description === undefined || typeof crate.description === "string") + ); } diff --git a/codeview-ui/src/lib/realtime/progress.svelte.ts b/codeview-ui/src/lib/realtime/progress.svelte.ts index f737b6a..3cb2d20 100644 --- a/codeview-ui/src/lib/realtime/progress.svelte.ts +++ b/codeview-ui/src/lib/realtime/progress.svelte.ts @@ -1,86 +1,86 @@ -import { getLogger } from '#lib/log'; -import { connect } from '$realtime'; -import type { RealtimeClient } from './types'; +import { getLogger } from "#lib/log"; +import { connect } from "$realtime"; +import type { RealtimeClient } from "./types"; interface ProgressEvent { - type: 'meta' | 'delta' | 'complete'; - nodeCount?: number; - edgeCount?: number; - totalItems?: number; + type: "meta" | "delta" | "complete"; + nodeCount?: number; + edgeCount?: number; + totalItems?: number; } export class ParseProgressConnection implements Disposable { - nodeCount = $state(0); - edgeCount = $state(0); - totalItems = $state(null); - complete: boolean = $state(false); - - #client: RealtimeClient = connect(); - #log = getLogger('progress'); - #name = ''; - #version = ''; - #currentTag: string | null = null; - #callback = (data: unknown) => this.#onProgressData(data as ProgressEvent); - - get tag() { - return `${this.#name}@${this.#version}`; - } - - connect(name: string, version: string) { - this.reset(); - this.#name = name; - this.#version = version; - const tag = `progress:rust:${name}:${version}`; - this.#currentTag = tag; - - this.#log.debug`connect ${this.tag}`; - - this.#client.subscribe(tag, this.#callback); - } - - disconnect() { - if (this.#currentTag) { - this.#client.unsubscribe(this.#currentTag, this.#callback); - this.#currentTag = null; - } - } - - destroy() { - this.disconnect(); - this.#resetCounters(); - } - - [Symbol.dispose]() { - this.destroy(); - } - - reset() { - this.disconnect(); - this.#resetCounters(); - } - - #resetCounters() { - this.nodeCount = 0; - this.edgeCount = 0; - this.totalItems = null; - this.complete = false; - } - - #onProgressData(msg: ProgressEvent) { - this.#log - .debug`msg ${this.tag} type=${msg.type} nodes=${msg.nodeCount ?? 0} edges=${msg.edgeCount ?? 0} total=${msg.totalItems ?? '-'}`; - - if (typeof msg.nodeCount === 'number') this.nodeCount = msg.nodeCount; - if (typeof msg.edgeCount === 'number') this.edgeCount = msg.edgeCount; - - if ((msg.type === 'meta' || msg.type === 'complete') && typeof msg.totalItems === 'number') { - this.totalItems = msg.totalItems; - } - - if (msg.type === 'complete') { - this.complete = true; - this.#log.debug`complete ${this.tag}`; - this.disconnect(); - } - } + nodeCount = $state(0); + edgeCount = $state(0); + totalItems = $state(null); + complete: boolean = $state(false); + + #client: RealtimeClient = connect(); + #log = getLogger("progress"); + #name = ""; + #version = ""; + #currentTag: string | null = null; + #callback = (data: unknown) => this.#onProgressData(data as ProgressEvent); + + get tag() { + return `${this.#name}@${this.#version}`; + } + + connect(name: string, version: string) { + this.reset(); + this.#name = name; + this.#version = version; + const tag = `progress:rust:${name}:${version}`; + this.#currentTag = tag; + + this.#log.debug`connect ${this.tag}`; + + this.#client.subscribe(tag, this.#callback); + } + + disconnect() { + if (this.#currentTag) { + this.#client.unsubscribe(this.#currentTag, this.#callback); + this.#currentTag = null; + } + } + + destroy() { + this.disconnect(); + this.#resetCounters(); + } + + [Symbol.dispose]() { + this.destroy(); + } + + reset() { + this.disconnect(); + this.#resetCounters(); + } + + #resetCounters() { + this.nodeCount = 0; + this.edgeCount = 0; + this.totalItems = null; + this.complete = false; + } + + #onProgressData(msg: ProgressEvent) { + this.#log + .debug`msg ${this.tag} type=${msg.type} nodes=${msg.nodeCount ?? 0} edges=${msg.edgeCount ?? 0} total=${msg.totalItems ?? "-"}`; + + if (typeof msg.nodeCount === "number") this.nodeCount = msg.nodeCount; + if (typeof msg.edgeCount === "number") this.edgeCount = msg.edgeCount; + + if ((msg.type === "meta" || msg.type === "complete") && typeof msg.totalItems === "number") { + this.totalItems = msg.totalItems; + } + + if (msg.type === "complete") { + this.complete = true; + this.#log.debug`complete ${this.tag}`; + this.disconnect(); + } + } } diff --git a/codeview-ui/src/lib/realtime/queue.svelte.ts b/codeview-ui/src/lib/realtime/queue.svelte.ts index d4f5eeb..50f5a4f 100644 --- a/codeview-ui/src/lib/realtime/queue.svelte.ts +++ b/codeview-ui/src/lib/realtime/queue.svelte.ts @@ -1,91 +1,91 @@ -import { getLogger } from '#lib/log'; -import { connect } from '$realtime'; -import type { ParseQueueEntry } from '#lib/server/provider'; -import type { StoredParseStatus } from '#lib/server/cloudflare/parse-contract'; -import type { RealtimeClient } from './types'; +import { getLogger } from "#lib/log"; +import { connect } from "$realtime"; +import type { ParseQueueEntry } from "#lib/server/provider"; +import type { StoredParseStatus } from "#lib/server/cloudflare/parse-contract"; +import type { RealtimeClient } from "./types"; interface QueueMessage { - type?: string; - active?: unknown; - recent?: unknown; + type?: string; + active?: unknown; + recent?: unknown; } export class QueueStatusConnection implements Disposable { - active = $state.raw([]); - recent = $state.raw([]); - received = $state(false); + active = $state.raw([]); + recent = $state.raw([]); + received = $state(false); - #client: RealtimeClient = connect(); - #log = getLogger('queue-status'); - #tag: string | null = null; - #callback = (data: unknown) => this.#onData(data as QueueMessage); + #client: RealtimeClient = connect(); + #log = getLogger("queue-status"); + #tag: string | null = null; + #callback = (data: unknown) => this.#onData(data as QueueMessage); - connect(ecosystem = 'rust') { - const tag = `queue:${ecosystem}`; - if (this.#tag === tag) return; - this.disconnect(); - this.#tag = tag; - this.#client.subscribe(tag, this.#callback); - } + connect(ecosystem = "rust") { + const tag = `queue:${ecosystem}`; + if (this.#tag === tag) return; + this.disconnect(); + this.#tag = tag; + this.#client.subscribe(tag, this.#callback); + } - disconnect() { - if (!this.#tag) return; - this.#client.unsubscribe(this.#tag, this.#callback); - this.#tag = null; - } + disconnect() { + if (!this.#tag) return; + this.#client.unsubscribe(this.#tag, this.#callback); + this.#tag = null; + } - #onData(message: QueueMessage) { - if (message.type && message.type !== 'queue') return; - if (!Array.isArray(message.active) || !Array.isArray(message.recent)) return; + #onData(message: QueueMessage) { + if (message.type && message.type !== "queue") return; + if (!Array.isArray(message.active) || !Array.isArray(message.recent)) return; - const active = message.active.filter(isStoredParseStatus); - const recent = message.recent.filter(isStoredParseStatus); - this.active = active.map((entry, index) => toQueueEntry(entry, index + 1)); - this.recent = recent.map((entry) => toQueueEntry(entry)); - this.received = true; - this.#log.debug`queue snapshot active=${String(active.length)} recent=${String(recent.length)}`; - } + const active = message.active.filter(isStoredParseStatus); + const recent = message.recent.filter(isStoredParseStatus); + this.active = active.map((entry, index) => toQueueEntry(entry, index + 1)); + this.recent = recent.map((entry) => toQueueEntry(entry)); + this.received = true; + this.#log.debug`queue snapshot active=${String(active.length)} recent=${String(recent.length)}`; + } - destroy() { - this.disconnect(); - } + destroy() { + this.disconnect(); + } - [Symbol.dispose]() { - this.destroy(); - } + [Symbol.dispose]() { + this.destroy(); + } } function isStoredParseStatus(value: unknown): value is StoredParseStatus { - if (!value || typeof value !== 'object') return false; - const status = value as Partial; - return ( - (status.kind === 'crate' || status.kind === 'sysroot') && - typeof status.name === 'string' && - typeof status.version === 'string' && - (status.status === 'unknown' || - status.status === 'processing' || - status.status === 'ready' || - status.status === 'failed') && - typeof status.createdAt === 'string' && - typeof status.updatedAt === 'string' - ); + if (!value || typeof value !== "object") return false; + const status = value as Partial; + return ( + (status.kind === "crate" || status.kind === "sysroot") && + typeof status.name === "string" && + typeof status.version === "string" && + (status.status === "unknown" || + status.status === "processing" || + status.status === "ready" || + status.status === "failed") && + typeof status.createdAt === "string" && + typeof status.updatedAt === "string" + ); } function toQueueEntry(status: StoredParseStatus, position?: number): ParseQueueEntry { - return { - kind: status.kind, - name: status.name, - version: status.version, - status: status.status, - step: status.step, - error: status.error, - requestId: status.requestId, - workflowId: status.workflowId, - githubRunId: status.githubRunId, - githubRunUrl: status.githubRunUrl, - requestedBy: status.requestedBy, - requestedAt: status.createdAt, - updatedAt: status.updatedAt, - position, - }; + return { + kind: status.kind, + name: status.name, + version: status.version, + status: status.status, + step: status.step, + error: status.error, + requestId: status.requestId, + workflowId: status.workflowId, + githubRunId: status.githubRunId, + githubRunUrl: status.githubRunUrl, + requestedBy: status.requestedBy, + requestedAt: status.createdAt, + updatedAt: status.updatedAt, + position, + }; } diff --git a/codeview-ui/src/lib/realtime/status.svelte.ts b/codeview-ui/src/lib/realtime/status.svelte.ts index 150bf89..6b79040 100644 --- a/codeview-ui/src/lib/realtime/status.svelte.ts +++ b/codeview-ui/src/lib/realtime/status.svelte.ts @@ -1,114 +1,114 @@ -import type { CrateStatus } from '#lib/schema'; -import { triggerCrateParse } from '#lib/rpc/crate.remote'; -import { getLogger } from '#lib/log'; -import { connect } from '$realtime'; -import { STEP_ORDER, stepLabels, stepPercents } from './constants'; -import type { RealtimeClient } from './types'; +import type { CrateStatus } from "#lib/schema"; +import { triggerCrateParse } from "#lib/rpc/crate.remote"; +import { getLogger } from "#lib/log"; +import { connect } from "$realtime"; +import { STEP_ORDER, stepLabels, stepPercents } from "./constants"; +import type { RealtimeClient } from "./types"; -type CrateStatusValue = CrateStatus['status']; +type CrateStatusValue = CrateStatus["status"]; export { STEP_ORDER, stepLabels, stepPercents }; export class CrateStatusConnection implements Disposable { - status = $state('unknown'); - error = $state(null); - step = $state(null); - action = $state<'install_std_docs' | 'docs_unavailable' | undefined>(undefined); - installedVersion = $state(undefined); - - #client: RealtimeClient = connect(); - #log = getLogger('status'); - #name = ''; - #version = ''; - #currentTag: string | null = null; - // Stable callback reference — same identity across subscribe/unsubscribe calls. - // Using a per-call closure caused a race: the #unsubscribe closure was set after - // an await, creating a microtask window where disconnect() couldn't clean up. - #callback = (data: unknown) => this.#onStatusData(data as CrateStatus); - - get tag() { - return `${this.#name}@${this.#version}`; - } - - connect(name: string, version: string) { - this.disconnect(); - - this.#name = name; - this.#version = version; - const tag = `rust:${name}:${version}`; - this.#currentTag = tag; - - this.#log.debug`connect ${this.tag}`; - - // Don't reset to 'unknown' if already seeded to 'ready' from SSR - if (this.status !== 'ready') { - this.status = 'unknown'; - this.error = null; - this.step = null; - this.action = undefined; - this.installedVersion = undefined; - } - - this.#client.subscribe(tag, this.#callback); - } - - disconnect() { - if (this.#currentTag) { - this.#client.unsubscribe(this.#currentTag, this.#callback); - this.#currentTag = null; - } - } - - destroy() { - this.disconnect(); - } - - [Symbol.dispose]() { - this.destroy(); - } - - #onStatusData(msg: CrateStatus) { - this.#log - .debug`msg ${this.tag} status=${msg.status} step=${msg.step ?? '-'}${msg.error ? ` error=${msg.error}` : ''}`; - - this.status = msg.status; - this.error = msg.error ?? null; - this.action = msg.action; - this.installedVersion = msg.installedVersion; - - const incoming = msg.step ?? null; - if (incoming !== null) { - const curIdx = this.step ? STEP_ORDER.indexOf(this.step) : -1; - const newIdx = STEP_ORDER.indexOf(incoming); - if (newIdx >= curIdx) this.step = incoming; - } - - if (msg.status === 'ready' || msg.status === 'failed') { - this.#log.debug`terminal ${this.tag} status=${msg.status}`; - this.disconnect(); - } - } - - async triggerParse(name: string, version: string) { - this.#log.info`triggerParse ${name}@${version}`; - this.status = 'processing'; - this.error = null; - this.step = null; - - this.connect(name, version); - - try { - await triggerCrateParse({ name, version }); - } catch (err) { - this.#log.error`triggerParse failed ${name}@${version}: ${String(err)}`; - this.status = 'failed'; - this.error = err instanceof Error ? err.message : String(err); - } - } - - async retry(name: string, version: string) { - this.#log.info`retry ${name}@${version}`; - this.error = null; - await this.triggerParse(name, version); - } + status = $state("unknown"); + error = $state(null); + step = $state(null); + action = $state<"install_std_docs" | "docs_unavailable" | undefined>(undefined); + installedVersion = $state(undefined); + + #client: RealtimeClient = connect(); + #log = getLogger("status"); + #name = ""; + #version = ""; + #currentTag: string | null = null; + // Stable callback reference — same identity across subscribe/unsubscribe calls. + // Using a per-call closure caused a race: the #unsubscribe closure was set after + // an await, creating a microtask window where disconnect() couldn't clean up. + #callback = (data: unknown) => this.#onStatusData(data as CrateStatus); + + get tag() { + return `${this.#name}@${this.#version}`; + } + + connect(name: string, version: string) { + this.disconnect(); + + this.#name = name; + this.#version = version; + const tag = `rust:${name}:${version}`; + this.#currentTag = tag; + + this.#log.debug`connect ${this.tag}`; + + // Don't reset to 'unknown' if already seeded to 'ready' from SSR + if (this.status !== "ready") { + this.status = "unknown"; + this.error = null; + this.step = null; + this.action = undefined; + this.installedVersion = undefined; + } + + this.#client.subscribe(tag, this.#callback); + } + + disconnect() { + if (this.#currentTag) { + this.#client.unsubscribe(this.#currentTag, this.#callback); + this.#currentTag = null; + } + } + + destroy() { + this.disconnect(); + } + + [Symbol.dispose]() { + this.destroy(); + } + + #onStatusData(msg: CrateStatus) { + this.#log + .debug`msg ${this.tag} status=${msg.status} step=${msg.step ?? "-"}${msg.error ? ` error=${msg.error}` : ""}`; + + this.status = msg.status; + this.error = msg.error ?? null; + this.action = msg.action; + this.installedVersion = msg.installedVersion; + + const incoming = msg.step ?? null; + if (incoming !== null) { + const curIdx = this.step ? STEP_ORDER.indexOf(this.step) : -1; + const newIdx = STEP_ORDER.indexOf(incoming); + if (newIdx >= curIdx) this.step = incoming; + } + + if (msg.status === "ready" || msg.status === "failed") { + this.#log.debug`terminal ${this.tag} status=${msg.status}`; + this.disconnect(); + } + } + + async triggerParse(name: string, version: string) { + this.#log.info`triggerParse ${name}@${version}`; + this.status = "processing"; + this.error = null; + this.step = null; + + this.connect(name, version); + + try { + await triggerCrateParse({ name, version }); + } catch (err) { + this.#log.error`triggerParse failed ${name}@${version}: ${String(err)}`; + this.status = "failed"; + this.error = err instanceof Error ? err.message : String(err); + } + } + + async retry(name: string, version: string) { + this.#log.info`retry ${name}@${version}`; + this.error = null; + await this.triggerParse(name, version); + } } diff --git a/codeview-ui/src/lib/realtime/types.ts b/codeview-ui/src/lib/realtime/types.ts index 5f6d73c..b67ccb4 100644 --- a/codeview-ui/src/lib/realtime/types.ts +++ b/codeview-ui/src/lib/realtime/types.ts @@ -1,7 +1,7 @@ export type RealtimeCallback = (data: T) => void; export interface RealtimeClient { - subscribe(tag: string, callback: RealtimeCallback): void | Promise; - unsubscribe(tag: string, callback: RealtimeCallback): void | Promise; - isSubscribed(tag: string): boolean; + subscribe(tag: string, callback: RealtimeCallback): void | Promise; + unsubscribe(tag: string, callback: RealtimeCallback): void | Promise; + isSubscribed(tag: string): boolean; } diff --git a/codeview-ui/src/lib/realtime/updates.svelte.ts b/codeview-ui/src/lib/realtime/updates.svelte.ts index 1146650..ffbc590 100644 --- a/codeview-ui/src/lib/realtime/updates.svelte.ts +++ b/codeview-ui/src/lib/realtime/updates.svelte.ts @@ -1,80 +1,80 @@ -import { getLogger } from '#lib/log'; -import { connect } from '$realtime'; -import type { RealtimeClient } from './types'; +import { getLogger } from "#lib/log"; +import { connect } from "$realtime"; +import type { RealtimeClient } from "./types"; const CONNECT_DELAY_MS = 1_500; interface EdgeUpdateMessage { - type?: string; - nodeId?: string; + type?: string; + nodeId?: string; } export class CrossEdgeUpdatesConnection implements Disposable { - updateTick = $state(0); + updateTick = $state(0); - #client: RealtimeClient = connect(); - #log = getLogger('graph-updates'); - #nodeId = ''; - #currentTag: string | null = null; - #unsubscribe: (() => void) | null = null; - #connectTimer: ReturnType | null = null; + #client: RealtimeClient = connect(); + #log = getLogger("graph-updates"); + #nodeId = ""; + #currentTag: string | null = null; + #unsubscribe: (() => void) | null = null; + #connectTimer: ReturnType | null = null; - get tag() { - return `edge:${this.#nodeId}`; - } + get tag() { + return `edge:${this.#nodeId}`; + } - connect(nodeId: string) { - if (this.#nodeId === nodeId && this.#currentTag) return; - this.#cancelPending(); - this.disconnect(); + connect(nodeId: string) { + if (this.#nodeId === nodeId && this.#currentTag) return; + this.#cancelPending(); + this.disconnect(); - this.#nodeId = nodeId; - const tag = `edge:${nodeId}`; - this.#currentTag = tag; + this.#nodeId = nodeId; + const tag = `edge:${nodeId}`; + this.#currentTag = tag; - this.#log.debug`connect ${this.tag}`; + this.#log.debug`connect ${this.tag}`; - this.#connectTimer = setTimeout(() => { - this.#connectTimer = null; - void this.#doSubscribe(tag); - }, CONNECT_DELAY_MS); - } + this.#connectTimer = setTimeout(() => { + this.#connectTimer = null; + void this.#doSubscribe(tag); + }, CONNECT_DELAY_MS); + } - async #doSubscribe(tag: string) { - const callback = (data: unknown) => this.#onData(data as EdgeUpdateMessage); - await this.#client.subscribe(tag, callback); - this.#unsubscribe = () => { - void this.#client.unsubscribe(tag, callback); - }; - } + async #doSubscribe(tag: string) { + const callback = (data: unknown) => this.#onData(data as EdgeUpdateMessage); + await this.#client.subscribe(tag, callback); + this.#unsubscribe = () => { + void this.#client.unsubscribe(tag, callback); + }; + } - #cancelPending() { - if (this.#connectTimer !== null) { - clearTimeout(this.#connectTimer); - this.#connectTimer = null; - } - } + #cancelPending() { + if (this.#connectTimer !== null) { + clearTimeout(this.#connectTimer); + this.#connectTimer = null; + } + } - disconnect() { - this.#cancelPending(); - if (this.#unsubscribe) { - this.#unsubscribe(); - this.#unsubscribe = null; - } - this.#currentTag = null; - } + disconnect() { + this.#cancelPending(); + if (this.#unsubscribe) { + this.#unsubscribe(); + this.#unsubscribe = null; + } + this.#currentTag = null; + } - #onData(msg: EdgeUpdateMessage) { - if (msg.type && msg.type !== 'cross-edges') return; - this.updateTick += 1; - this.#log.debug`update ${this.tag} tick=${String(this.updateTick)}`; - } + #onData(msg: EdgeUpdateMessage) { + if (msg.type && msg.type !== "cross-edges") return; + this.updateTick += 1; + this.#log.debug`update ${this.tag} tick=${String(this.updateTick)}`; + } - destroy() { - this.disconnect(); - } + destroy() { + this.disconnect(); + } - [Symbol.dispose]() { - this.destroy(); - } + [Symbol.dispose]() { + this.destroy(); + } } diff --git a/codeview-ui/src/lib/renderers/graph.test.ts b/codeview-ui/src/lib/renderers/graph.test.ts index c413bf6..ca46368 100644 --- a/codeview-ui/src/lib/renderers/graph.test.ts +++ b/codeview-ui/src/lib/renderers/graph.test.ts @@ -1,494 +1,494 @@ -import { describe, it, expect } from 'vite-plus/test'; +import { describe, it, expect } from "vite-plus/test"; import { - buildScene, - buildBaseScene, - buildNodeMap, - computeSceneLabels, - computeEdgeSimilarityGroups, - filterEdges, - structuralEdgeKinds, - semanticEdgeKinds, -} from './graph'; -import type { Graph, Node, Edge } from '#lib/graph'; -import { isSyntheticProjectionNodeId, projectGraphForRendering } from '#lib/graph/projection'; + buildScene, + buildBaseScene, + buildNodeMap, + computeSceneLabels, + computeEdgeSimilarityGroups, + filterEdges, + structuralEdgeKinds, + semanticEdgeKinds, +} from "./graph"; +import type { Graph, Node, Edge } from "#lib/graph"; +import { isSyntheticProjectionNodeId, projectGraphForRendering } from "#lib/graph/projection"; // --------------------------------------------------------------------------- // Test fixtures // --------------------------------------------------------------------------- -function makeNode(id: string, name: string, kind: Node['kind'] = 'Function'): Node { - return { - id, - name, - kind, - visibility: { kind: 'Public' }, - } as Node; +function makeNode(id: string, name: string, kind: Node["kind"] = "Function"): Node { + return { + id, + name, + kind, + visibility: { kind: "Public" }, + } as Node; } -function makeEdge(from: string, to: string, kind: Edge['kind'] = 'UsesType'): Edge { - return { from, to, kind, confidence: 'Static' }; +function makeEdge(from: string, to: string, kind: Edge["kind"] = "UsesType"): Edge { + return { from, to, kind, confidence: "Static" }; } function makeGraph(nodes: Node[], edges: Edge[]): Graph { - return { nodes, edges }; + return { nodes, edges }; } // --------------------------------------------------------------------------- // Exported constants // --------------------------------------------------------------------------- -describe('edge kind constants', () => { - it('structuralEdgeKinds contains Contains and Defines', () => { - expect(structuralEdgeKinds).toContain('Contains'); - expect(structuralEdgeKinds).toContain('Defines'); - }); - - it('semanticEdgeKinds contains semantic edge kinds', () => { - expect(semanticEdgeKinds).toContain('UsesType'); - expect(semanticEdgeKinds).toContain('Implements'); - expect(semanticEdgeKinds).toContain('CallsStatic'); - expect(semanticEdgeKinds).toContain('CallsRuntime'); - expect(semanticEdgeKinds).toContain('Derives'); - expect(semanticEdgeKinds).toContain('ReExports'); - }); - - it('constants are readonly (no overlap)', () => { - for (const kind of structuralEdgeKinds) { - expect(semanticEdgeKinds).not.toContain(kind); - } - }); +describe("edge kind constants", () => { + it("structuralEdgeKinds contains Contains and Defines", () => { + expect(structuralEdgeKinds).toContain("Contains"); + expect(structuralEdgeKinds).toContain("Defines"); + }); + + it("semanticEdgeKinds contains semantic edge kinds", () => { + expect(semanticEdgeKinds).toContain("UsesType"); + expect(semanticEdgeKinds).toContain("Implements"); + expect(semanticEdgeKinds).toContain("CallsStatic"); + expect(semanticEdgeKinds).toContain("CallsRuntime"); + expect(semanticEdgeKinds).toContain("Derives"); + expect(semanticEdgeKinds).toContain("ReExports"); + }); + + it("constants are readonly (no overlap)", () => { + for (const kind of structuralEdgeKinds) { + expect(semanticEdgeKinds).not.toContain(kind); + } + }); }); // --------------------------------------------------------------------------- // filterEdges // --------------------------------------------------------------------------- -describe('filterEdges', () => { - const edges: Edge[] = [ - makeEdge('a', 'b', 'UsesType'), - makeEdge('a', 'c', 'Contains'), - makeEdge('a', 'd', 'Defines'), - makeEdge('a', 'e', 'Implements'), - ]; - - it('keeps all edges when both flags are true', () => { - const result = filterEdges(edges, { showStructural: true, showSemantic: true }); - expect(result).toHaveLength(4); - }); - - it('filters out structural edges', () => { - const result = filterEdges(edges, { showStructural: false, showSemantic: true }); - const kinds = result.map((e) => e.kind); - expect(kinds).not.toContain('Contains'); - expect(kinds).not.toContain('Defines'); - expect(kinds).toContain('UsesType'); - expect(kinds).toContain('Implements'); - }); - - it('filters out semantic edges', () => { - const result = filterEdges(edges, { showStructural: true, showSemantic: false }); - const kinds = result.map((e) => e.kind); - expect(kinds).toContain('Contains'); - expect(kinds).toContain('Defines'); - expect(kinds).not.toContain('UsesType'); - expect(kinds).not.toContain('Implements'); - }); - - it('filters out both', () => { - const result = filterEdges(edges, { showStructural: false, showSemantic: false }); - expect(result).toHaveLength(0); - }); +describe("filterEdges", () => { + const edges: Edge[] = [ + makeEdge("a", "b", "UsesType"), + makeEdge("a", "c", "Contains"), + makeEdge("a", "d", "Defines"), + makeEdge("a", "e", "Implements"), + ]; + + it("keeps all edges when both flags are true", () => { + const result = filterEdges(edges, { showStructural: true, showSemantic: true }); + expect(result).toHaveLength(4); + }); + + it("filters out structural edges", () => { + const result = filterEdges(edges, { showStructural: false, showSemantic: true }); + const kinds = result.map((e) => e.kind); + expect(kinds).not.toContain("Contains"); + expect(kinds).not.toContain("Defines"); + expect(kinds).toContain("UsesType"); + expect(kinds).toContain("Implements"); + }); + + it("filters out semantic edges", () => { + const result = filterEdges(edges, { showStructural: true, showSemantic: false }); + const kinds = result.map((e) => e.kind); + expect(kinds).toContain("Contains"); + expect(kinds).toContain("Defines"); + expect(kinds).not.toContain("UsesType"); + expect(kinds).not.toContain("Implements"); + }); + + it("filters out both", () => { + const result = filterEdges(edges, { showStructural: false, showSemantic: false }); + expect(result).toHaveLength(0); + }); }); // --------------------------------------------------------------------------- // buildNodeMap // --------------------------------------------------------------------------- -describe('buildNodeMap', () => { - it('builds a map from node id to VisNode', () => { - const center = makeNode('a', 'A'); - const graph = makeGraph([center, makeNode('b', 'B')], [makeEdge('a', 'b')]); - const base = buildBaseScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - const map = buildNodeMap(base.nodes); - expect(map.size).toBe(base.nodes.length); - for (const node of base.nodes) { - expect(map.get(node.node.id)).toBe(node); - } - }); +describe("buildNodeMap", () => { + it("builds a map from node id to VisNode", () => { + const center = makeNode("a", "A"); + const graph = makeGraph([center, makeNode("b", "B")], [makeEdge("a", "b")]); + const base = buildBaseScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + const map = buildNodeMap(base.nodes); + expect(map.size).toBe(base.nodes.length); + for (const node of base.nodes) { + expect(map.get(node.node.id)).toBe(node); + } + }); }); // --------------------------------------------------------------------------- // computeEdgeSimilarityGroups // --------------------------------------------------------------------------- -describe('computeEdgeSimilarityGroups', () => { - it('returns empty map for no edges', () => { - const result = computeEdgeSimilarityGroups([], new Map()); - expect(result.size).toBe(0); - }); - - it('assigns every edge to a group', () => { - const center = makeNode('a', 'A'); - const graph = makeGraph( - [center, makeNode('b', 'B'), makeNode('c', 'C')], - [makeEdge('a', 'b'), makeEdge('a', 'c')], - ); - const base = buildBaseScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - const nodeMap = buildNodeMap(base.nodes); - const groups = computeEdgeSimilarityGroups(base.edges, nodeMap); - for (let i = 0; i < base.edges.length; i++) { - expect(groups.has(i)).toBe(true); - const info = groups.get(i)!; - expect(info.group).toContain(i); - expect(typeof info.indexOf).toBe('number'); - } - }); +describe("computeEdgeSimilarityGroups", () => { + it("returns empty map for no edges", () => { + const result = computeEdgeSimilarityGroups([], new Map()); + expect(result.size).toBe(0); + }); + + it("assigns every edge to a group", () => { + const center = makeNode("a", "A"); + const graph = makeGraph( + [center, makeNode("b", "B"), makeNode("c", "C")], + [makeEdge("a", "b"), makeEdge("a", "c")], + ); + const base = buildBaseScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + const nodeMap = buildNodeMap(base.nodes); + const groups = computeEdgeSimilarityGroups(base.edges, nodeMap); + for (let i = 0; i < base.edges.length; i++) { + expect(groups.has(i)).toBe(true); + const info = groups.get(i)!; + expect(info.group).toContain(i); + expect(typeof info.indexOf).toBe("number"); + } + }); }); // --------------------------------------------------------------------------- // buildBaseScene (Stage 1) // --------------------------------------------------------------------------- -describe('buildBaseScene', () => { - const center = makeNode('my_crate::Foo', 'Foo', 'Struct'); - const dep = makeNode('my_crate::Bar', 'Bar', 'Function'); - - it('returns nodes, edges, groups, similarityGroups, and mode', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - const base = buildBaseScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - - expect(base.mode).toBe('ego'); - expect(base.nodes.length).toBeGreaterThanOrEqual(1); - expect(base.edges.length).toBeGreaterThanOrEqual(0); - expect(base.groups.length).toBeGreaterThan(0); - expect(base.similarityGroups).toBeInstanceOf(Map); - }); - - it('does not include labels', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - const base = buildBaseScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - expect(base).not.toHaveProperty('labels'); - }); - - it('filters edges according to opts', () => { - const child = makeNode('my_crate::Baz', 'Baz', 'Enum'); - const graph = makeGraph( - [center, dep, child], - [ - makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType'), - makeEdge('my_crate::Foo', 'my_crate::Baz', 'Contains'), - ], - ); - const base = buildBaseScene(graph, center, 'ego', { - showStructural: false, - showSemantic: true, - }); - const edgeKinds = base.edges.map((e) => e.kind); - expect(edgeKinds).not.toContain('Contains'); - }); +describe("buildBaseScene", () => { + const center = makeNode("my_crate::Foo", "Foo", "Struct"); + const dep = makeNode("my_crate::Bar", "Bar", "Function"); + + it("returns nodes, edges, groups, similarityGroups, and mode", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + const base = buildBaseScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + + expect(base.mode).toBe("ego"); + expect(base.nodes.length).toBeGreaterThanOrEqual(1); + expect(base.edges.length).toBeGreaterThanOrEqual(0); + expect(base.groups.length).toBeGreaterThan(0); + expect(base.similarityGroups).toBeInstanceOf(Map); + }); + + it("does not include labels", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + const base = buildBaseScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + expect(base).not.toHaveProperty("labels"); + }); + + it("filters edges according to opts", () => { + const child = makeNode("my_crate::Baz", "Baz", "Enum"); + const graph = makeGraph( + [center, dep, child], + [ + makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType"), + makeEdge("my_crate::Foo", "my_crate::Baz", "Contains"), + ], + ); + const base = buildBaseScene(graph, center, "ego", { + showStructural: false, + showSemantic: true, + }); + const edgeKinds = base.edges.map((e) => e.kind); + expect(edgeKinds).not.toContain("Contains"); + }); }); // --------------------------------------------------------------------------- // computeSceneLabels (Stage 2) // --------------------------------------------------------------------------- -describe('computeSceneLabels', () => { - const center = makeNode('my_crate::Foo', 'Foo', 'Struct'); - const dep = makeNode('my_crate::Bar', 'Bar', 'Function'); - - it('returns one label per edge', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - const base = buildBaseScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - const nodeMap = buildNodeMap(base.nodes); - const labels = computeSceneLabels(base, nodeMap); - - expect(labels).toHaveLength(base.edges.length); - for (const label of labels) { - expect(label).toHaveProperty('x'); - expect(label).toHaveProperty('y'); - expect(label).toHaveProperty('anchor'); - } - }); - - it('returns empty array for no edges', () => { - const graph = makeGraph([center], []); - const base = buildBaseScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - const nodeMap = buildNodeMap(base.nodes); - const labels = computeSceneLabels(base, nodeMap); - expect(labels).toHaveLength(0); - }); - - it('accepts custom getMetrics', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - const base = buildBaseScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - const nodeMap = buildNodeMap(base.nodes); - const labels = computeSceneLabels(base, nodeMap, () => ({ width: 100 })); - expect(labels).toHaveLength(base.edges.length); - }); - - it('calls SceneHook.adjustLabels when provided', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - const base = buildBaseScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - const nodeMap = buildNodeMap(base.nodes); - let hookCalled = false; - const labels = computeSceneLabels(base, nodeMap, undefined, { - adjustLabels(positions, ctx) { - hookCalled = true; - expect(ctx.baseScene).toBe(base); - expect(ctx.positionedNodeMap).toBe(nodeMap); - // Shift all labels by 10px - for (const pos of positions) { - pos.x += 10; - } - }, - }); - expect(hookCalled).toBe(true); - expect(labels).toHaveLength(base.edges.length); - }); +describe("computeSceneLabels", () => { + const center = makeNode("my_crate::Foo", "Foo", "Struct"); + const dep = makeNode("my_crate::Bar", "Bar", "Function"); + + it("returns one label per edge", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + const base = buildBaseScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + const nodeMap = buildNodeMap(base.nodes); + const labels = computeSceneLabels(base, nodeMap); + + expect(labels).toHaveLength(base.edges.length); + for (const label of labels) { + expect(label).toHaveProperty("x"); + expect(label).toHaveProperty("y"); + expect(label).toHaveProperty("anchor"); + } + }); + + it("returns empty array for no edges", () => { + const graph = makeGraph([center], []); + const base = buildBaseScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + const nodeMap = buildNodeMap(base.nodes); + const labels = computeSceneLabels(base, nodeMap); + expect(labels).toHaveLength(0); + }); + + it("accepts custom getMetrics", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + const base = buildBaseScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + const nodeMap = buildNodeMap(base.nodes); + const labels = computeSceneLabels(base, nodeMap, () => ({ width: 100 })); + expect(labels).toHaveLength(base.edges.length); + }); + + it("calls SceneHook.adjustLabels when provided", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + const base = buildBaseScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + const nodeMap = buildNodeMap(base.nodes); + let hookCalled = false; + const labels = computeSceneLabels(base, nodeMap, undefined, { + adjustLabels(positions, ctx) { + hookCalled = true; + expect(ctx.baseScene).toBe(base); + expect(ctx.positionedNodeMap).toBe(nodeMap); + // Shift all labels by 10px + for (const pos of positions) { + pos.x += 10; + } + }, + }); + expect(hookCalled).toBe(true); + expect(labels).toHaveLength(base.edges.length); + }); }); // --------------------------------------------------------------------------- // buildScene (composed) // --------------------------------------------------------------------------- -describe('buildScene', () => { - const center = makeNode('my_crate::Foo', 'Foo', 'Struct'); - const dep = makeNode('my_crate::Bar', 'Bar', 'Function'); - const child = makeNode('my_crate::Baz', 'Baz', 'Enum'); - - it('returns a scene with nodes, edges, labels, groups, and mode', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - - const scene = buildScene(graph, center, 'ego', { - showStructural: true, - showSemantic: true, - }); - - expect(scene.mode).toBe('ego'); - expect(scene.nodes.length).toBeGreaterThanOrEqual(1); - expect(scene.edges).toHaveLength(scene.labels.length); - expect(scene.groups.length).toBeGreaterThan(0); - }); - - it('filters out structural edges when showStructural is false', () => { - const graph = makeGraph( - [center, dep, child], - [ - makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType'), - makeEdge('my_crate::Foo', 'my_crate::Baz', 'Contains'), - ], - ); - - const scene = buildScene(graph, center, 'ego', { - showStructural: false, - showSemantic: true, - }); - - const edgeKinds = scene.edges.map((e) => e.kind); - expect(edgeKinds).not.toContain('Contains'); - }); - - it('filters out semantic edges when showSemantic is false', () => { - const graph = makeGraph( - [center, dep, child], - [ - makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType'), - makeEdge('my_crate::Foo', 'my_crate::Baz', 'Contains'), - ], - ); - - const scene = buildScene(graph, center, 'ego', { - showStructural: true, - showSemantic: false, - }); - - const edgeKinds = scene.edges.map((e) => e.kind); - expect(edgeKinds).not.toContain('UsesType'); - }); - - it('produces a label for each edge', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - - const scene = buildScene(graph, center, 'ego', { - showStructural: true, - showSemantic: true, - }); - - expect(scene.labels).toHaveLength(scene.edges.length); - for (const label of scene.labels) { - expect(label).toHaveProperty('x'); - expect(label).toHaveProperty('y'); - expect(label).toHaveProperty('anchor'); - } - }); - - it('works with an empty graph (center only, no edges)', () => { - const graph = makeGraph([center], []); - const scene = buildScene(graph, center, 'ego', { - showStructural: true, - showSemantic: true, - }); - - expect(scene.nodes).toHaveLength(1); - expect(scene.edges).toHaveLength(0); - expect(scene.labels).toHaveLength(0); - }); - - it('works with different layout modes', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - - for (const mode of ['ego', 'force', 'hierarchical', 'radial'] as const) { - const scene = buildScene(graph, center, mode, { - showStructural: true, - showSemantic: true, - }); - expect(scene.mode).toBe(mode); - expect(scene.nodes.length).toBeGreaterThanOrEqual(1); - } - }); - - it('supports projected graphs with trait filtering metadata policy', () => { - const trait = makeNode('my_crate::Display', 'Display', 'Trait'); - const graph = makeGraph( - [center, dep, trait], - [ - makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType'), - makeEdge('my_crate::Foo', 'my_crate::Display', 'Implements'), - ], - ); - - const projected = projectGraphForRendering(graph, center, { - showStructural: true, - showSemantic: true, - layoutMode: 'ego', - }); - - expect(projected.graph.nodes.some((n) => n.kind === 'Trait')).toBe(false); - - const scene = buildScene(projected.graph, center, 'ego', { - showStructural: true, - showSemantic: true, - }); - - expect(scene.nodes.some((n) => n.node.kind === 'Trait')).toBe(false); - expect(scene.edges.length).toBe(scene.labels.length); - }); - - it('supports projected overflow summary nodes', () => { - const denseNeighbors = Array.from({ length: 220 }, (_, i) => - makeNode(`my_crate::Dep${i}`, `Dep${i}`, 'Function'), - ); - const graph = makeGraph( - [center, ...denseNeighbors], - denseNeighbors.map((node) => makeEdge(center.id, node.id, 'UsesType')), - ); - - const projected = projectGraphForRendering(graph, center, { - showStructural: true, - showSemantic: true, - layoutMode: 'ego', - maxNodes: 24, - maxEdges: 48, - }); - - expect(projected.graph.nodes.some((n) => isSyntheticProjectionNodeId(n.id))).toBe(true); - - const scene = buildScene(projected.graph, center, 'ego', { - showStructural: true, - showSemantic: true, - }); - - expect(scene.nodes.length).toBeLessThanOrEqual(24); - expect(scene.edges.length).toBe(scene.labels.length); - }); - - describe('groups', () => { - it('creates one node group per node', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - - const scene = buildScene(graph, center, 'ego', { - showStructural: true, - showSemantic: true, - }); - - const nodeGroups = scene.groups.filter((g) => g.type === 'node'); - expect(nodeGroups).toHaveLength(scene.nodes.length); - for (const g of nodeGroups) { - if (g.type !== 'node') continue; - expect(typeof g.nodeIndex).toBe('number'); - expect(g.id).toMatch(/^node:/); - } - }); - - it('creates one edge group per edge with matching label index', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - - const scene = buildScene(graph, center, 'ego', { - showStructural: true, - showSemantic: true, - }); - - const edgeGroups = scene.groups.filter((g) => g.type === 'edge'); - expect(edgeGroups).toHaveLength(scene.edges.length); - for (const g of edgeGroups) { - if (g.type !== 'edge') continue; - expect(typeof g.edgeIndex).toBe('number'); - expect(g.labelIndex).toBeDefined(); - expect(g.id).toMatch(/^edge:/); - } - }); - - it('produces no edge groups when there are no edges', () => { - const graph = makeGraph([center], []); - const scene = buildScene(graph, center, 'ego', { - showStructural: true, - showSemantic: true, - }); - - const edgeGroups = scene.groups.filter((g) => g.type === 'edge'); - expect(edgeGroups).toHaveLength(0); - }); - - it('group IDs are stable for the same input', () => { - const graph = makeGraph( - [center, dep], - [makeEdge('my_crate::Foo', 'my_crate::Bar', 'UsesType')], - ); - - const a = buildScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - const b = buildScene(graph, center, 'ego', { showStructural: true, showSemantic: true }); - - expect(a.groups.map((g) => g.id)).toEqual(b.groups.map((g) => g.id)); - }); - }); +describe("buildScene", () => { + const center = makeNode("my_crate::Foo", "Foo", "Struct"); + const dep = makeNode("my_crate::Bar", "Bar", "Function"); + const child = makeNode("my_crate::Baz", "Baz", "Enum"); + + it("returns a scene with nodes, edges, labels, groups, and mode", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + + const scene = buildScene(graph, center, "ego", { + showStructural: true, + showSemantic: true, + }); + + expect(scene.mode).toBe("ego"); + expect(scene.nodes.length).toBeGreaterThanOrEqual(1); + expect(scene.edges).toHaveLength(scene.labels.length); + expect(scene.groups.length).toBeGreaterThan(0); + }); + + it("filters out structural edges when showStructural is false", () => { + const graph = makeGraph( + [center, dep, child], + [ + makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType"), + makeEdge("my_crate::Foo", "my_crate::Baz", "Contains"), + ], + ); + + const scene = buildScene(graph, center, "ego", { + showStructural: false, + showSemantic: true, + }); + + const edgeKinds = scene.edges.map((e) => e.kind); + expect(edgeKinds).not.toContain("Contains"); + }); + + it("filters out semantic edges when showSemantic is false", () => { + const graph = makeGraph( + [center, dep, child], + [ + makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType"), + makeEdge("my_crate::Foo", "my_crate::Baz", "Contains"), + ], + ); + + const scene = buildScene(graph, center, "ego", { + showStructural: true, + showSemantic: false, + }); + + const edgeKinds = scene.edges.map((e) => e.kind); + expect(edgeKinds).not.toContain("UsesType"); + }); + + it("produces a label for each edge", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + + const scene = buildScene(graph, center, "ego", { + showStructural: true, + showSemantic: true, + }); + + expect(scene.labels).toHaveLength(scene.edges.length); + for (const label of scene.labels) { + expect(label).toHaveProperty("x"); + expect(label).toHaveProperty("y"); + expect(label).toHaveProperty("anchor"); + } + }); + + it("works with an empty graph (center only, no edges)", () => { + const graph = makeGraph([center], []); + const scene = buildScene(graph, center, "ego", { + showStructural: true, + showSemantic: true, + }); + + expect(scene.nodes).toHaveLength(1); + expect(scene.edges).toHaveLength(0); + expect(scene.labels).toHaveLength(0); + }); + + it("works with different layout modes", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + + for (const mode of ["ego", "force", "hierarchical", "radial"] as const) { + const scene = buildScene(graph, center, mode, { + showStructural: true, + showSemantic: true, + }); + expect(scene.mode).toBe(mode); + expect(scene.nodes.length).toBeGreaterThanOrEqual(1); + } + }); + + it("supports projected graphs with trait filtering metadata policy", () => { + const trait = makeNode("my_crate::Display", "Display", "Trait"); + const graph = makeGraph( + [center, dep, trait], + [ + makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType"), + makeEdge("my_crate::Foo", "my_crate::Display", "Implements"), + ], + ); + + const projected = projectGraphForRendering(graph, center, { + showStructural: true, + showSemantic: true, + layoutMode: "ego", + }); + + expect(projected.graph.nodes.some((n) => n.kind === "Trait")).toBe(false); + + const scene = buildScene(projected.graph, center, "ego", { + showStructural: true, + showSemantic: true, + }); + + expect(scene.nodes.some((n) => n.node.kind === "Trait")).toBe(false); + expect(scene.edges.length).toBe(scene.labels.length); + }); + + it("supports projected overflow summary nodes", () => { + const denseNeighbors = Array.from({ length: 220 }, (_, i) => + makeNode(`my_crate::Dep${i}`, `Dep${i}`, "Function"), + ); + const graph = makeGraph( + [center, ...denseNeighbors], + denseNeighbors.map((node) => makeEdge(center.id, node.id, "UsesType")), + ); + + const projected = projectGraphForRendering(graph, center, { + showStructural: true, + showSemantic: true, + layoutMode: "ego", + maxNodes: 24, + maxEdges: 48, + }); + + expect(projected.graph.nodes.some((n) => isSyntheticProjectionNodeId(n.id))).toBe(true); + + const scene = buildScene(projected.graph, center, "ego", { + showStructural: true, + showSemantic: true, + }); + + expect(scene.nodes.length).toBeLessThanOrEqual(24); + expect(scene.edges.length).toBe(scene.labels.length); + }); + + describe("groups", () => { + it("creates one node group per node", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + + const scene = buildScene(graph, center, "ego", { + showStructural: true, + showSemantic: true, + }); + + const nodeGroups = scene.groups.filter((g) => g.type === "node"); + expect(nodeGroups).toHaveLength(scene.nodes.length); + for (const g of nodeGroups) { + if (g.type !== "node") continue; + expect(typeof g.nodeIndex).toBe("number"); + expect(g.id).toMatch(/^node:/); + } + }); + + it("creates one edge group per edge with matching label index", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + + const scene = buildScene(graph, center, "ego", { + showStructural: true, + showSemantic: true, + }); + + const edgeGroups = scene.groups.filter((g) => g.type === "edge"); + expect(edgeGroups).toHaveLength(scene.edges.length); + for (const g of edgeGroups) { + if (g.type !== "edge") continue; + expect(typeof g.edgeIndex).toBe("number"); + expect(g.labelIndex).toBeDefined(); + expect(g.id).toMatch(/^edge:/); + } + }); + + it("produces no edge groups when there are no edges", () => { + const graph = makeGraph([center], []); + const scene = buildScene(graph, center, "ego", { + showStructural: true, + showSemantic: true, + }); + + const edgeGroups = scene.groups.filter((g) => g.type === "edge"); + expect(edgeGroups).toHaveLength(0); + }); + + it("group IDs are stable for the same input", () => { + const graph = makeGraph( + [center, dep], + [makeEdge("my_crate::Foo", "my_crate::Bar", "UsesType")], + ); + + const a = buildScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + const b = buildScene(graph, center, "ego", { showStructural: true, showSemantic: true }); + + expect(a.groups.map((g) => g.id)).toEqual(b.groups.map((g) => g.id)); + }); + }); }); diff --git a/codeview-ui/src/lib/renderers/graph.ts b/codeview-ui/src/lib/renderers/graph.ts index e386e00..c36ed84 100644 --- a/codeview-ui/src/lib/renderers/graph.ts +++ b/codeview-ui/src/lib/renderers/graph.ts @@ -1,8 +1,8 @@ -import type { Edge, EdgeKind, Graph, Node } from '#lib/graph'; -import type { LayoutMode, VisEdge, VisNode } from '#lib/graph/layout'; -import type { LabelPosition, SimilarityInfo } from '#lib/graph/labels'; -import { computeLayout } from '#lib/graph/layout'; -import { getLabelProvider, computeAllLabelPositions } from '#lib/graph/labels'; +import type { Edge, EdgeKind, Graph, Node } from "#lib/graph"; +import type { LayoutMode, VisEdge, VisNode } from "#lib/graph/layout"; +import type { LabelPosition, SimilarityInfo } from "#lib/graph/labels"; +import { computeLayout } from "#lib/graph/layout"; +import { getLabelProvider, computeAllLabelPositions } from "#lib/graph/labels"; /** * A logical group of scene elements that belong together. @@ -10,51 +10,51 @@ import { getLabelProvider, computeAllLabelPositions } from '#lib/graph/labels'; * SVG data-group attributes) so that grouped elements move/select as one unit. */ export type SceneGroup = - | { - /** Stable identifier derived from the node identity. */ - id: string; - type: 'node'; - /** Index into `scene.nodes`. */ - nodeIndex: number; - } - | { - /** Stable identifier derived from the edge identity. */ - id: string; - type: 'edge'; - /** Index into `scene.edges`. */ - edgeIndex: number; - /** Index into `scene.labels` (always matches edgeIndex when label exists). */ - labelIndex: number | undefined; - }; + | { + /** Stable identifier derived from the node identity. */ + id: string; + type: "node"; + /** Index into `scene.nodes`. */ + nodeIndex: number; + } + | { + /** Stable identifier derived from the edge identity. */ + id: string; + type: "edge"; + /** Index into `scene.edges`. */ + edgeIndex: number; + /** Index into `scene.labels` (always matches edgeIndex when label exists). */ + labelIndex: number | undefined; + }; /** The positioned, ready-to-render scene produced by computeLayout + label positioning. */ export type GraphScene = { - nodes: VisNode[]; - edges: VisEdge[]; - labels: LabelPosition[]; - groups: SceneGroup[]; - mode: LayoutMode; + nodes: VisNode[]; + edges: VisEdge[]; + labels: LabelPosition[]; + groups: SceneGroup[]; + mode: LayoutMode; }; /** What a renderer can do with a scene. */ export interface GraphRenderer { - readonly id: string; - readonly label: string; - render(scene: GraphScene): T; + readonly id: string; + readonly label: string; + render(scene: GraphScene): T; } // --------------------------------------------------------------------------- // Edge kind constants (single source of truth) // --------------------------------------------------------------------------- -export const structuralEdgeKinds: readonly EdgeKind[] = ['Contains', 'Defines']; +export const structuralEdgeKinds: readonly EdgeKind[] = ["Contains", "Defines"]; export const semanticEdgeKinds: readonly EdgeKind[] = [ - 'UsesType', - 'Implements', - 'CallsStatic', - 'CallsRuntime', - 'Derives', - 'ReExports', + "UsesType", + "Implements", + "CallsStatic", + "CallsRuntime", + "Derives", + "ReExports", ]; // --------------------------------------------------------------------------- @@ -63,66 +63,66 @@ export const semanticEdgeKinds: readonly EdgeKind[] = [ /** Filter edges by structural/semantic toggles. */ export function filterEdges( - edges: Edge[], - opts: { showStructural: boolean; showSemantic: boolean }, + edges: Edge[], + opts: { showStructural: boolean; showSemantic: boolean }, ): Edge[] { - return edges.filter((edge: Edge) => { - if ((structuralEdgeKinds as readonly string[]).includes(edge.kind)) return opts.showStructural; - if ((semanticEdgeKinds as readonly string[]).includes(edge.kind)) return opts.showSemantic; - return true; - }); + return edges.filter((edge: Edge) => { + if ((structuralEdgeKinds as readonly string[]).includes(edge.kind)) return opts.showStructural; + if ((semanticEdgeKinds as readonly string[]).includes(edge.kind)) return opts.showSemantic; + return true; + }); } /** Build a lookup map from node id → VisNode. */ export function buildNodeMap(nodes: VisNode[]): Map { - const map = new Map(); - for (const node of nodes) { - map.set(node.node.id, node); - } - return map; + const map = new Map(); + for (const node of nodes) { + map.set(node.node.id, node); + } + return map; } /** Compute edge angle similarity groups for label layout. */ export function computeEdgeSimilarityGroups( - edges: VisEdge[], - nodeMap: Map, + edges: VisEdge[], + nodeMap: Map, ): Map { - if (edges.length === 0) return new Map(); + if (edges.length === 0) return new Map(); - type EdgeAngle = { index: number; angle: number; direction: string }; - const edgeAngles: EdgeAngle[] = edges.map((edge, i) => { - const fromNode = nodeMap.get(edge.from.node.id) ?? edge.from; - const toNode = nodeMap.get(edge.to.node.id) ?? edge.to; - const dx = toNode.x - fromNode.x; - const dy = toNode.y - fromNode.y; - return { index: i, angle: Math.atan2(dy, dx), direction: edge.direction }; - }); + type EdgeAngle = { index: number; angle: number; direction: string }; + const edgeAngles: EdgeAngle[] = edges.map((edge, i) => { + const fromNode = nodeMap.get(edge.from.node.id) ?? edge.from; + const toNode = nodeMap.get(edge.to.node.id) ?? edge.to; + const dx = toNode.x - fromNode.x; + const dy = toNode.y - fromNode.y; + return { index: i, angle: Math.atan2(dy, dx), direction: edge.direction }; + }); - const sorted = [...edgeAngles].sort((a, b) => { - if (a.direction !== b.direction) return a.direction < b.direction ? -1 : 1; - return a.angle - b.angle; - }); + const sorted = [...edgeAngles].sort((a, b) => { + if (a.direction !== b.direction) return a.direction < b.direction ? -1 : 1; + return a.angle - b.angle; + }); - const result = new Map(); - let groupStart = 0; - while (groupStart < sorted.length) { - const group: number[] = [sorted[groupStart].index]; - let groupEnd = groupStart + 1; - while ( - groupEnd < sorted.length && - sorted[groupEnd].direction === sorted[groupStart].direction && - Math.abs(sorted[groupEnd].angle - sorted[groupStart].angle) < 0.35 - ) { - group.push(sorted[groupEnd].index); - groupEnd++; - } - for (let k = 0; k < group.length; k++) { - result.set(group[k], { group, indexOf: k }); - } - groupStart = groupEnd; - } + const result = new Map(); + let groupStart = 0; + while (groupStart < sorted.length) { + const group: number[] = [sorted[groupStart].index]; + let groupEnd = groupStart + 1; + while ( + groupEnd < sorted.length && + sorted[groupEnd].direction === sorted[groupStart].direction && + Math.abs(sorted[groupEnd].angle - sorted[groupStart].angle) < 0.35 + ) { + group.push(sorted[groupEnd].index); + groupEnd++; + } + for (let k = 0; k < group.length; k++) { + result.set(group[k], { group, indexOf: k }); + } + groupStart = groupEnd; + } - return result; + return result; } // --------------------------------------------------------------------------- @@ -131,11 +131,11 @@ export function computeEdgeSimilarityGroups( /** The layout-computed scene before label positioning. Immune to drag offsets. */ export type BaseScene = { - nodes: VisNode[]; - edges: VisEdge[]; - groups: SceneGroup[]; - similarityGroups: Map; - mode: LayoutMode; + nodes: VisNode[]; + edges: VisEdge[]; + groups: SceneGroup[]; + similarityGroups: Map; + mode: LayoutMode; }; /** @@ -144,48 +144,48 @@ export type BaseScene = { * (graph, selected.id, layoutMode, showStructural, showSemantic). */ export function buildBaseScene( - graph: Graph, - selected: Node, - layoutMode: LayoutMode, - opts: { showStructural: boolean; showSemantic: boolean }, + graph: Graph, + selected: Node, + layoutMode: LayoutMode, + opts: { showStructural: boolean; showSemantic: boolean }, ): BaseScene { - const filteredEdges = filterEdges(graph.edges, opts); - const filteredGraph: Graph = { nodes: graph.nodes, edges: filteredEdges }; + const filteredEdges = filterEdges(graph.edges, opts); + const filteredGraph: Graph = { nodes: graph.nodes, edges: filteredEdges }; - const visData = computeLayout(filteredGraph, selected, layoutMode); + const visData = computeLayout(filteredGraph, selected, layoutMode); - const nodeMap = buildNodeMap(visData.nodes); - const similarityGroups = computeEdgeSimilarityGroups(visData.edges, nodeMap); + const nodeMap = buildNodeMap(visData.nodes); + const similarityGroups = computeEdgeSimilarityGroups(visData.edges, nodeMap); - // Build groups — one per node, one per edge - const groups: SceneGroup[] = []; + // Build groups — one per node, one per edge + const groups: SceneGroup[] = []; - for (let i = 0; i < visData.nodes.length; i++) { - groups.push({ - id: `node:${visData.nodes[i].node.id}`, - type: 'node', - nodeIndex: i, - }); - } + for (let i = 0; i < visData.nodes.length; i++) { + groups.push({ + id: `node:${visData.nodes[i].node.id}`, + type: "node", + nodeIndex: i, + }); + } - for (let i = 0; i < visData.edges.length; i++) { - const edge = visData.edges[i]; - groups.push({ - id: `edge:${edge.from.node.id}:${edge.to.node.id}:${edge.kind}:${edge.confidence}${edge.is_glob ? ':glob' : ''}`, - type: 'edge', - edgeIndex: i, - // labelIndex will be filled in by buildScene; for BaseScene it's provisional - labelIndex: i, - }); - } + for (let i = 0; i < visData.edges.length; i++) { + const edge = visData.edges[i]; + groups.push({ + id: `edge:${edge.from.node.id}:${edge.to.node.id}:${edge.kind}:${edge.confidence}${edge.is_glob ? ":glob" : ""}`, + type: "edge", + edgeIndex: i, + // labelIndex will be filled in by buildScene; for BaseScene it's provisional + labelIndex: i, + }); + } - return { - nodes: visData.nodes, - edges: visData.edges, - groups, - similarityGroups, - mode: layoutMode, - }; + return { + nodes: visData.nodes, + edges: visData.edges, + groups, + similarityGroups, + mode: layoutMode, + }; } // --------------------------------------------------------------------------- @@ -194,14 +194,14 @@ export function buildBaseScene( /** Hook interface for renderer-specific adjustments. */ export interface SceneHook { - adjustLabels?( - positions: LabelPosition[], - ctx: { - baseScene: BaseScene; - positionedNodeMap: Map; - }, - ): void; - expandNeighbors?(hoveredNodeId: string, ctx: { baseScene: BaseScene }): Set; + adjustLabels?( + positions: LabelPosition[], + ctx: { + baseScene: BaseScene; + positionedNodeMap: Map; + }, + ): void; + expandNeighbors?(hoveredNodeId: string, ctx: { baseScene: BaseScene }): Set; } /** @@ -209,30 +209,30 @@ export interface SceneHook { * This is cheap and recomputes each drag frame. */ export function computeSceneLabels( - baseScene: BaseScene, - positionedNodeMap: Map, - getMetrics?: (kind: string) => { width: number }, - hook?: SceneHook, + baseScene: BaseScene, + positionedNodeMap: Map, + getMetrics?: (kind: string) => { width: number }, + hook?: SceneHook, ): LabelPosition[] { - const defaultGetMetrics = (kind: string) => { - const fontSize = 9; - const paddingX = 6; - const textWidth = kind.length * fontSize * 0.6; - return { width: Math.max(28, textWidth + paddingX * 2) }; - }; + const defaultGetMetrics = (kind: string) => { + const fontSize = 9; + const paddingX = 6; + const textWidth = kind.length * fontSize * 0.6; + return { width: Math.max(28, textWidth + paddingX * 2) }; + }; - const provider = getLabelProvider(baseScene.mode); - const labels = computeAllLabelPositions( - provider, - baseScene.edges, - positionedNodeMap, - baseScene.similarityGroups, - getMetrics ?? defaultGetMetrics, - ); + const provider = getLabelProvider(baseScene.mode); + const labels = computeAllLabelPositions( + provider, + baseScene.edges, + positionedNodeMap, + baseScene.similarityGroups, + getMetrics ?? defaultGetMetrics, + ); - hook?.adjustLabels?.(labels, { baseScene, positionedNodeMap }); + hook?.adjustLabels?.(labels, { baseScene, positionedNodeMap }); - return labels; + return labels; } // --------------------------------------------------------------------------- @@ -245,20 +245,20 @@ export function computeSceneLabels( * Exporters call this; the SVG component calls the stages separately for granular caching. */ export function buildScene( - graph: Graph, - selected: Node, - layoutMode: LayoutMode, - opts: { showStructural: boolean; showSemantic: boolean }, + graph: Graph, + selected: Node, + layoutMode: LayoutMode, + opts: { showStructural: boolean; showSemantic: boolean }, ): GraphScene { - const base = buildBaseScene(graph, selected, layoutMode, opts); - const nodeMap = buildNodeMap(base.nodes); - const labels = computeSceneLabels(base, nodeMap); + const base = buildBaseScene(graph, selected, layoutMode, opts); + const nodeMap = buildNodeMap(base.nodes); + const labels = computeSceneLabels(base, nodeMap); - return { - nodes: base.nodes, - edges: base.edges, - labels, - groups: base.groups, - mode: base.mode, - }; + return { + nodes: base.nodes, + edges: base.edges, + labels, + groups: base.groups, + mode: base.mode, + }; } diff --git a/codeview-ui/src/lib/rpc/ancestors.remote.ts b/codeview-ui/src/lib/rpc/ancestors.remote.ts index 24b5658..ba625db 100644 --- a/codeview-ui/src/lib/rpc/ancestors.remote.ts +++ b/codeview-ui/src/lib/rpc/ancestors.remote.ts @@ -1,69 +1,69 @@ -import { prerender, query } from '$app/server'; -import { getLogger } from '#lib/log'; -import { perf } from '#lib/perf'; -import { isHosted } from '#lib/platform'; -import type { NodeSummary } from '#lib/schema'; -import { summarizeNode } from '#lib/node-summary'; -import { loader, resolve } from './helpers'; -import { assertCrateRef } from './remote-utils'; -import { TreeNodeInputSchema } from './schemas'; +import { prerender, query } from "$app/server"; +import { getLogger } from "#lib/log"; +import { perf } from "#lib/perf"; +import { isHosted } from "#lib/platform"; +import type { NodeSummary } from "#lib/schema"; +import { summarizeNode } from "#lib/node-summary"; +import { loader, resolve } from "./helpers"; +import { assertCrateRef } from "./remote-utils"; +import { TreeNodeInputSchema } from "./schemas"; -const log = getLogger('rpc.ancestors'); +const log = getLogger("rpc.ancestors"); /** * Ancestor chain for a node — used for breadcrumbs. * Returns NodeSummary[] from root → ... → parent (excludes the node itself). */ async function loadTreeAncestors({ - name, - version, - nodeId, + name, + version, + nodeId, }: { - name: string; - version?: string; - nodeId: string; + name: string; + version?: string; + nodeId: string; }) { - assertCrateRef(name, version ?? 'latest'); - return perf.timeAsync( - 'server', - `getTreeAncestors(${nodeId})`, - async () => { - const resolvedVersion = version ?? 'latest'; - const provider = await loader.provider(); - if (isHosted && provider.loadTreeAncestorsDirect) { - return ((await provider.loadTreeAncestorsDirect(name, resolvedVersion, nodeId)) ?? - []) satisfies NodeSummary[]; - } + assertCrateRef(name, version ?? "latest"); + return perf.timeAsync( + "server", + `getTreeAncestors(${nodeId})`, + async () => { + const resolvedVersion = version ?? "latest"; + const provider = await loader.provider(); + if (isHosted && provider.loadTreeAncestorsDirect) { + return ((await provider.loadTreeAncestorsDirect(name, resolvedVersion, nodeId)) ?? + []) satisfies NodeSummary[]; + } - const idx = await resolve.treeIndex(name, resolvedVersion, provider); - if (!idx) { - if (provider.loadTreeAncestorsDirect) { - return ((await provider.loadTreeAncestorsDirect(name, resolvedVersion, nodeId)) ?? - []) satisfies NodeSummary[]; - } - log.info`getTreeAncestors no index for ${name}@${resolvedVersion}`; - return []; - } + const idx = await resolve.treeIndex(name, resolvedVersion, provider); + if (!idx) { + if (provider.loadTreeAncestorsDirect) { + return ((await provider.loadTreeAncestorsDirect(name, resolvedVersion, nodeId)) ?? + []) satisfies NodeSummary[]; + } + log.info`getTreeAncestors no index for ${name}@${resolvedVersion}`; + return []; + } - const ancestors: NodeSummary[] = []; - let currentId: string | undefined = idx.parents.get(nodeId); - const visited = new Set(); + const ancestors: NodeSummary[] = []; + let currentId: string | undefined = idx.parents.get(nodeId); + const visited = new Set(); - while (currentId && !visited.has(currentId)) { - visited.add(currentId); - const node = idx.getNode(currentId); - if (node) ancestors.unshift(summarizeNode(node)); - currentId = idx.parents.get(currentId); - } + while (currentId && !visited.has(currentId)) { + visited.add(currentId); + const node = idx.getNode(currentId); + if (node) ancestors.unshift(summarizeNode(node)); + currentId = idx.parents.get(currentId); + } - return ancestors; - }, - { detail: (r) => `${r.length} ancestors` }, - ); + return ancestors; + }, + { detail: (r) => `${r.length} ancestors` }, + ); } export const getTreeAncestors = query(TreeNodeInputSchema, loadTreeAncestors); export const getStaticTreeAncestors = prerender(TreeNodeInputSchema, loadTreeAncestors, { - dynamic: true, + dynamic: true, }); diff --git a/codeview-ui/src/lib/rpc/children.remote.ts b/codeview-ui/src/lib/rpc/children.remote.ts index 680c670..06bdb9a 100644 --- a/codeview-ui/src/lib/rpc/children.remote.ts +++ b/codeview-ui/src/lib/rpc/children.remote.ts @@ -1,41 +1,41 @@ -import { prerender, query } from '$app/server'; -import * as Effect from 'effect/Effect'; -import * as Schema from 'effect/Schema'; -import { getLogger } from '#lib/log'; -import { perf } from '#lib/perf'; -import type { TreeNodeDTO } from '#lib/schema'; -import { resolve } from './helpers'; -import { assertCrateRef } from './remote-utils'; -import { TreeNodeInputSchema } from './schemas'; +import { prerender, query } from "$app/server"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { getLogger } from "#lib/log"; +import { perf } from "#lib/perf"; +import type { TreeNodeDTO } from "#lib/schema"; +import { resolve } from "./helpers"; +import { assertCrateRef } from "./remote-utils"; +import { TreeNodeInputSchema } from "./schemas"; -const log = getLogger('rpc.children'); +const log = getLogger("rpc.children"); -class TreeChildrenLoadError extends Schema.TaggedErrorClass()( - 'TreeChildrenLoadError', - { - key: Schema.String, - cause: Schema.Defect(), - message: Schema.String, - }, +class TreeChildrenLoadError extends Schema.TaggedError()( + "TreeChildrenLoadError", + { + key: Schema.String, + cause: Schema.Defect(), + message: Schema.String, + }, ) {} function unknownMessage(cause: unknown): string { - return cause instanceof Error ? cause.message : String(cause); + return cause instanceof Error ? cause.message : String(cause); } async function loadTreeChildren({ - name, - version, - nodeId, + name, + version, + nodeId, }: { - name: string; - version?: string; - nodeId: string; + name: string; + version?: string; + nodeId: string; }): Promise { - assertCrateRef(name, version ?? 'latest'); - const children = await resolve.treeChildren(name, version ?? 'latest', nodeId); - log.info`getTreeChildren done ${name}@${version ?? 'latest'} parent=${nodeId} children=${children.length}`; - return children; + assertCrateRef(name, version ?? "latest"); + const children = await resolve.treeChildren(name, version ?? "latest", nodeId); + log.info`getTreeChildren done ${name}@${version ?? "latest"} parent=${nodeId} children=${children.length}`; + return children; } /** @@ -46,50 +46,50 @@ async function loadTreeChildren({ * into a single HTTP request (e.g. pre-fetching children for all ancestors). */ export const getTreeChildren = query.batch(TreeNodeInputSchema, async (inputs) => { - return perf.timeAsync( - 'server', - `getTreeChildren.batch(${inputs.length})`, - async () => { - // Resolve children once per unique (crate, version, nodeId) - const uniqueInputs = new Map(); - for (const input of inputs) { - const { name, version, nodeId } = input; - const key = `${name}@${version ?? 'latest'}:${nodeId}`; - if (!uniqueInputs.has(key)) uniqueInputs.set(key, input); - } + return perf.timeAsync( + "server", + `getTreeChildren.batch(${inputs.length})`, + async () => { + // Resolve children once per unique (crate, version, nodeId) + const uniqueInputs = new Map(); + for (const input of inputs) { + const { name, version, nodeId } = input; + const key = `${name}@${version ?? "latest"}:${nodeId}`; + if (!uniqueInputs.has(key)) uniqueInputs.set(key, input); + } - log.info`getTreeChildren.batch resolving ${inputs.length} parents`; + log.info`getTreeChildren.batch resolving ${inputs.length} parents`; - const loaded = await Effect.runPromise( - Effect.forEach( - Array.from(uniqueInputs.entries()), - ([key, input]) => - Effect.tryPromise({ - try: async () => [key, await loadTreeChildren(input)] as const, - catch: (cause) => - new TreeChildrenLoadError({ - key, - cause, - message: `Failed to load tree children for ${key}: ${unknownMessage(cause)}`, - }), - }), - { concurrency: 8 }, - ), - ); + const loaded = await Effect.runPromise( + Effect.forEach( + Array.from(uniqueInputs.entries()), + ([key, input]) => + Effect.tryPromise({ + try: async () => [key, await loadTreeChildren(input)] as const, + catch: (cause) => + new TreeChildrenLoadError({ + key, + cause, + message: `Failed to load tree children for ${key}: ${unknownMessage(cause)}`, + }), + }), + { concurrency: 8 }, + ), + ); - const resultsByKey = new Map(loaded); + const resultsByKey = new Map(loaded); - return ({ name, version, nodeId }: { name: string; version?: string; nodeId: string }) => { - const key = `${name}@${version ?? 'latest'}:${nodeId}`; - const children = resultsByKey.get(key) ?? []; - log.info`getTreeChildren done ${name}@${version ?? 'latest'} parent=${nodeId} children=${children.length}`; - return children; - }; - }, - { detail: () => `${inputs.length} parents` }, - ); + return ({ name, version, nodeId }: { name: string; version?: string; nodeId: string }) => { + const key = `${name}@${version ?? "latest"}:${nodeId}`; + const children = resultsByKey.get(key) ?? []; + log.info`getTreeChildren done ${name}@${version ?? "latest"} parent=${nodeId} children=${children.length}`; + return children; + }; + }, + { detail: () => `${inputs.length} parents` }, + ); }); export const getStaticTreeChildren = prerender(TreeNodeInputSchema, loadTreeChildren, { - dynamic: true, + dynamic: true, }); diff --git a/codeview-ui/src/lib/rpc/crate.remote.ts b/codeview-ui/src/lib/rpc/crate.remote.ts index 9c3d049..44dc459 100644 --- a/codeview-ui/src/lib/rpc/crate.remote.ts +++ b/codeview-ui/src/lib/rpc/crate.remote.ts @@ -1,84 +1,84 @@ -import { query, command, form } from '$app/server'; -import { isHosted } from '#lib/platform'; -import { sanitizeSearchQuery } from '#lib/server/validation'; +import { query, command, form } from "$app/server"; +import { isHosted } from "#lib/platform"; +import { sanitizeSearchQuery } from "#lib/server/validation"; import { - type CrateSummary, - type CrateIndex, - type CrateTree, - type CrateStatus, - type CrateSearchResult, -} from '#lib/schema'; -import { summarizeNode } from '#lib/node-summary'; -import { loader } from './helpers'; -import { assertCrateName, assertCrateRef, throwIfProviderErr } from './remote-utils'; + type CrateSummary, + type CrateIndex, + type CrateTree, + type CrateStatus, + type CrateSearchResult, +} from "#lib/schema"; +import { summarizeNode } from "#lib/node-summary"; +import { loader } from "./helpers"; +import { assertCrateName, assertCrateRef, throwIfProviderErr } from "./remote-utils"; import { - CrateRefSchema, - ProcessingInputSchema, - CrateVersionInputSchema, - CrateNameInputSchema, - RegistrySearchInputSchema, - TriggerParseInputSchema, - InstallStdDocsInputSchema, -} from './schemas'; + CrateRefSchema, + ProcessingInputSchema, + CrateVersionInputSchema, + CrateNameInputSchema, + RegistrySearchInputSchema, + TriggerParseInputSchema, + InstallStdDocsInputSchema, +} from "./schemas"; /** Get local CLI workspace crates. Hosted mode has no workspace. */ export const getLocalCrates = query(async (): Promise => { - if (isHosted) return []; - const ws = await loader.localWorkspace(); - if (!ws) return []; - return ws.crates.map((c) => ({ - id: c.id, - name: c.name, - version: c.version, - })); + if (isHosted) return []; + const ws = await loader.localWorkspace(); + if (!ws) return []; + return ws.crates.map((c) => ({ + id: c.id, + name: c.name, + version: c.version, + })); }); /** Get a hosted-friendly list of top crates (registry-backed). */ export const getTopCrates = query(async (): Promise => { - const provider = await loader.provider(); - return provider.getTopCrates(10); + const provider = await loader.provider(); + return provider.getTopCrates(10); }); /** Get currently processing crates (cloud mode). */ export const getProcessingCrates = query( - ProcessingInputSchema, - async (): Promise => { - const provider = await loader.provider(); - return provider.getProcessingCrates(20); - }, + ProcessingInputSchema, + async (): Promise => { + const provider = await loader.provider(); + return provider.getProcessingCrates(20); + }, ); /** Get available versions for a crate */ export const getCrateVersions = query(CrateNameInputSchema, async ({ name }): Promise => { - assertCrateName(name); - const provider = await loader.provider(); - return await provider.getCrateVersions(name); + assertCrateName(name); + const provider = await loader.provider(); + return await provider.getCrateVersions(name); }); /** Get a lightweight crate index for hosted mode (external crate list + versions). */ export const getCrateIndex = query( - CrateRefSchema, - async ({ name, version }): Promise => { - const provider = await loader.provider(); - return await provider.loadCrateIndex(name, version ?? 'latest'); - }, + CrateRefSchema, + async ({ name, version }): Promise => { + const provider = await loader.provider(); + return await provider.loadCrateIndex(name, version ?? "latest"); + }, ); /** Get the parse status of a crate (cloud mode). */ export const getCrateStatus = query( - CrateVersionInputSchema, - async ({ name, version }): Promise => { - assertCrateRef(name, version); - const provider = await loader.provider(); - return provider.getCrateStatus(name, version); - }, + CrateVersionInputSchema, + async ({ name, version }): Promise => { + assertCrateRef(name, version); + const provider = await loader.provider(); + return provider.getCrateStatus(name, version); + }, ); async function requestParse({ name, version }: { name: string; version: string }): Promise { - assertCrateRef(name, version); - const provider = await loader.provider(); - const result = await provider.triggerParse(name, version, false); - throwIfProviderErr(result, { RateLimitError: 429 }); + assertCrateRef(name, version); + const provider = await loader.provider(); + const result = await provider.triggerParse(name, version, false); + throwIfProviderErr(result, { RateLimitError: 429 }); } /** Trigger parsing from an imperative client flow. */ @@ -89,44 +89,44 @@ export const requestCrateParse = form(TriggerParseInputSchema, requestParse); /** Trigger std crate install + parse (local mode, requires user consent). */ export const installStdDocs = form( - InstallStdDocsInputSchema, - async ({ name, version }): Promise => { - assertCrateRef(name, version); - const provider = await loader.provider(); - const result = await provider.triggerStdInstall(name, version); - throwIfProviderErr(result); - }, + InstallStdDocsInputSchema, + async ({ name, version }): Promise => { + assertCrateRef(name, version); + const provider = await loader.provider(); + const result = await provider.triggerStdInstall(name, version); + throwIfProviderErr(result); + }, ); /** Search the registry for crates (cloud mode). */ export const searchRegistry = query( - RegistrySearchInputSchema, - async ({ q }): Promise => { - const queryText = sanitizeSearchQuery(q); - if (!queryText) return []; - const provider = await loader.provider(); - return provider.searchRegistry(queryText); - }, + RegistrySearchInputSchema, + async ({ q }): Promise => { + const queryText = sanitizeSearchQuery(q); + if (!queryText) return []; + const provider = await loader.provider(); + return provider.searchRegistry(queryText); + }, ); /** Load a single crate graph from R2 (cloud mode). */ export const loadCrateGraph = query( - CrateRefSchema, - async ({ name, version }): Promise => { - assertCrateRef(name, version ?? 'latest'); - const provider = await loader.provider(); - if (isHosted) return null; - const graph = await provider.loadCrateGraph(name, version ?? 'latest'); - if (!graph) return null; + CrateRefSchema, + async ({ name, version }): Promise => { + assertCrateRef(name, version ?? "latest"); + const provider = await loader.provider(); + if (isHosted) return null; + const graph = await provider.loadCrateGraph(name, version ?? "latest"); + if (!graph) return null; - // Filter to tree-relevant edges only - const treeEdges = graph.edges.filter( - (e: { kind: string }) => e.kind === 'Contains' || e.kind === 'Defines', - ); + // Filter to tree-relevant edges only + const treeEdges = graph.edges.filter( + (e: { kind: string }) => e.kind === "Contains" || e.kind === "Defines", + ); - return { - nodes: graph.nodes.map(summarizeNode), - edges: treeEdges, - }; - }, + return { + nodes: graph.nodes.map(summarizeNode), + edges: treeEdges, + }; + }, ); diff --git a/codeview-ui/src/lib/rpc/crateMap.remote.ts b/codeview-ui/src/lib/rpc/crateMap.remote.ts index 5606ad4..6406dc3 100644 --- a/codeview-ui/src/lib/rpc/crateMap.remote.ts +++ b/codeview-ui/src/lib/rpc/crateMap.remote.ts @@ -1,12 +1,12 @@ -import { prerender, query } from '$app/server'; -import { getLogger } from '#lib/log'; -import { perf } from '#lib/perf'; -import type { CrateMapData } from '#lib/graph/crate-map'; -import { loader } from './helpers'; -import { assertCrateRef } from './remote-utils'; -import { CrateRefSchema } from './schemas'; +import { prerender, query } from "$app/server"; +import { getLogger } from "#lib/log"; +import { perf } from "#lib/perf"; +import type { CrateMapData } from "#lib/graph/crate-map"; +import { loader } from "./helpers"; +import { assertCrateRef } from "./remote-utils"; +import { CrateRefSchema } from "./schemas"; -const log = getLogger('rpc.crate-map'); +const log = getLogger("rpc.crate-map"); /** * Aggregated crate-wide module map for high-level visualization. @@ -16,35 +16,35 @@ const log = getLogger('rpc.crate-map'); * in-process in local mode) to avoid transferring full graphs. */ async function loadCrateMap({ name, version }: { name: string; version?: string }) { - const resolvedVersion = version ?? 'latest'; - assertCrateRef(name, resolvedVersion); + const resolvedVersion = version ?? "latest"; + assertCrateRef(name, resolvedVersion); - return perf.timeAsync( - 'server', - `getCrateMap(${name}@${resolvedVersion})`, - async () => { - const provider = await loader.provider(); - const map = await provider.loadCrateMap(name, resolvedVersion, { - maxHierarchyModules: 180, - maxMatrixModules: 24, - }); + return perf.timeAsync( + "server", + `getCrateMap(${name}@${resolvedVersion})`, + async () => { + const provider = await loader.provider(); + const map = await provider.loadCrateMap(name, resolvedVersion, { + maxHierarchyModules: 180, + maxMatrixModules: 24, + }); - if (map) { - log.info`getCrateMap done name=${name} version=${resolvedVersion} modules=${map.moduleNodes.length} matrix=${map.matrixModuleIds.length} edges=${map.moduleEdges.length}`; - } - return map satisfies CrateMapData | null; - }, - { - detail: (result) => - result - ? `${result.moduleNodes.length}m ${result.matrixModuleIds.length}mx ${result.moduleEdges.length}e` - : 'null', - }, - ); + if (map) { + log.info`getCrateMap done name=${name} version=${resolvedVersion} modules=${map.moduleNodes.length} matrix=${map.matrixModuleIds.length} edges=${map.moduleEdges.length}`; + } + return map satisfies CrateMapData | null; + }, + { + detail: (result) => + result + ? `${result.moduleNodes.length}m ${result.matrixModuleIds.length}mx ${result.moduleEdges.length}e` + : "null", + }, + ); } export const getCrateMap = query(CrateRefSchema, loadCrateMap); export const getStaticCrateMap = prerender(CrateRefSchema, loadCrateMap, { - dynamic: true, + dynamic: true, }); diff --git a/codeview-ui/src/lib/rpc/detail.remote.ts b/codeview-ui/src/lib/rpc/detail.remote.ts index b66a7e7..729600b 100644 --- a/codeview-ui/src/lib/rpc/detail.remote.ts +++ b/codeview-ui/src/lib/rpc/detail.remote.ts @@ -1,22 +1,22 @@ -import { query } from '$app/server'; -import * as Effect from 'effect/Effect'; -import type { NodeDetail } from '#lib/schema'; -import { loader, resolve, type NodeDetailInput } from './helpers'; -import { NodeDetailInputSchema } from './schemas'; +import { query } from "$app/server"; +import * as Effect from "effect/Effect"; +import type { NodeDetail } from "#lib/schema"; +import { loader, resolve, type NodeDetailInput } from "./helpers"; +import { NodeDetailInputSchema } from "./schemas"; /** Get full node detail + all edges (for the detail panel) */ export const getNodeDetail = query.batch( - NodeDetailInputSchema, - async (inputs): Promise<(input: NodeDetailInput, index: number) => NodeDetail | null> => { - const provider = await loader.provider(); - const workspace = await loader.localWorkspace(provider); - const results = await Effect.runPromise( - Effect.forEach( - inputs, - (input) => Effect.promise(() => resolve.nodeDetail(input, provider, workspace)), - { concurrency: 8 }, - ), - ); - return (_input, index) => results[index] ?? null; - }, + NodeDetailInputSchema, + async (inputs): Promise<(input: NodeDetailInput, index: number) => NodeDetail | null> => { + const provider = await loader.provider(); + const workspace = await loader.localWorkspace(provider); + const results = await Effect.runPromise( + Effect.forEach( + inputs, + (input) => Effect.promise(() => resolve.nodeDetail(input, provider, workspace)), + { concurrency: 8 }, + ), + ); + return (_input, index) => results[index] ?? null; + }, ); diff --git a/codeview-ui/src/lib/rpc/helpers.ts b/codeview-ui/src/lib/rpc/helpers.ts index 5d3db6d..9b75524 100644 --- a/codeview-ui/src/lib/rpc/helpers.ts +++ b/codeview-ui/src/lib/rpc/helpers.ts @@ -1,195 +1,195 @@ -import { getRequestEvent } from '$app/server'; -import * as Effect from 'effect/Effect'; -import { hasLocalWorkspace, initProvider } from '#lib/server/provider'; -import { perf } from '#lib/perf'; -import { isHosted } from '#lib/platform'; -import { normalizeCrateName, hyphenateCrateName } from '#lib/crate-names'; -import { TreeIndex } from '#lib/graph/tree-index'; -import type { Node, Edge, Workspace } from '#lib/graph'; +import { getRequestEvent } from "$app/server"; +import * as Effect from "effect/Effect"; +import { hasLocalWorkspace, initProvider } from "#lib/server/provider"; +import { perf } from "#lib/perf"; +import { isHosted } from "#lib/platform"; +import { normalizeCrateName, hyphenateCrateName } from "#lib/crate-names"; +import { TreeIndex } from "#lib/graph/tree-index"; +import type { Node, Edge, Workspace } from "#lib/graph"; import type { - NodeSummary, - CrateTree, - NodeDetail, - CrateMeta, - KindFacet, - TreeNodeDTO, - NodeView, -} from '#lib/schema'; -import { kindLabels, nodeKindOrder } from '#lib/display-names'; -import { getLogger } from '#lib/log'; -import { summarizeNode } from '#lib/node-summary'; -import type { NodeViewInput } from './schemas'; - -const log = getLogger('rpc.helpers'); - -export type Provider = Awaited>; + NodeSummary, + CrateTree, + NodeDetail, + CrateMeta, + KindFacet, + TreeNodeDTO, + NodeView, +} from "#lib/schema"; +import { kindLabels, nodeKindOrder } from "#lib/display-names"; +import { getLogger } from "#lib/log"; +import { summarizeNode } from "#lib/node-summary"; +import type { NodeViewInput } from "./schemas"; + +const log = getLogger("rpc.helpers"); + +export type Provider = ReturnType; export type NodeDetailInput = { - nodeId: string; - version?: string; - refresh?: number; + nodeId: string; + version?: string; + refresh?: number; }; -export type TreeMode = 'structural' | 'complete'; +export type TreeMode = "structural" | "complete"; // ── Tree utilities ───────────────────────────────────────────────────── interface TreeOps { - canonicalize( - name: string, - crateTree: CrateTree, - options?: { mode?: TreeMode; includeExternal?: boolean }, - ): CrateTree; - kindCounts(idx: TreeIndex): Record; + canonicalize( + name: string, + crateTree: CrateTree, + options?: { mode?: TreeMode; includeExternal?: boolean }, + ): CrateTree; + kindCounts(idx: TreeIndex): Record; } export const tree = { - canonicalize( - name: string, - crateTree: CrateTree, - options?: { mode?: TreeMode; includeExternal?: boolean }, - ): CrateTree { - const mode = options?.mode ?? 'structural'; - const includeExternal = options?.includeExternal ?? false; - const normalizedName = normalizeCrateName(name); - const structuralOnly = mode === 'structural'; - const allowedNodeIds = new Set(); - const nodeById = new Map(crateTree.nodes.map((n) => [n.id, n])); - const outEdges: CrateTree['edges'] = []; - const parentByChild = structuralOnly ? new Map() : null; - - for (const edge of crateTree.edges) { - if (structuralOnly && edge.kind !== 'Contains' && edge.kind !== 'Defines') continue; - const from = nodeById.get(edge.from); - const to = nodeById.get(edge.to); - if (!from || !to) continue; - if (!includeExternal && (from.is_external || to.is_external)) continue; - if (parentByChild && !parentByChild.has(edge.to)) parentByChild.set(edge.to, edge.from); - allowedNodeIds.add(edge.from); - allowedNodeIds.add(edge.to); - outEdges.push(edge); - } - - if (structuralOnly && parentByChild) { - const preferredRoot = nodeById.has(normalizedName) - ? normalizedName - : nodeById.has(name) - ? name - : null; - const crateRoot = - preferredRoot ?? - crateTree.nodes.find( - (node) => node.kind === 'Crate' && (!node.is_external || includeExternal), - )?.id ?? - null; - - if (crateRoot) { - const reachMemo = new Map(); - reachMemo.set(crateRoot, true); - - const isReachableFromRoot = (startId: string): boolean => { - const cached = reachMemo.get(startId); - if (cached !== undefined) return cached; - - const path: string[] = []; - const seen = new Set(); - let current = startId; - - while (true) { - const memoized = reachMemo.get(current); - if (memoized !== undefined) { - for (const id of path) reachMemo.set(id, memoized); - return memoized; - } - if (current === crateRoot) { - for (const id of path) reachMemo.set(id, true); - reachMemo.set(current, true); - return true; - } - if (seen.has(current)) { - for (const id of path) reachMemo.set(id, false); - return false; - } - seen.add(current); - path.push(current); - - const parent = parentByChild.get(current); - if (!parent) { - for (const id of path) reachMemo.set(id, false); - return false; - } - current = parent; - } - }; - - const prunedEdges = outEdges.filter( - (edge) => isReachableFromRoot(edge.from) && isReachableFromRoot(edge.to), - ); - - allowedNodeIds.clear(); - for (const edge of prunedEdges) { - allowedNodeIds.add(edge.from); - allowedNodeIds.add(edge.to); - } - allowedNodeIds.add(crateRoot); - - outEdges.length = 0; - for (const edge of prunedEdges) outEdges.push(edge); - } - } - - if (structuralOnly) { - if (nodeById.has(name)) allowedNodeIds.add(name); - if (nodeById.has(normalizedName)) allowedNodeIds.add(normalizedName); - } - - const outNodes: CrateTree['nodes'] = []; - for (const node of crateTree.nodes) { - if (!includeExternal && node.is_external) continue; - if (structuralOnly && !allowedNodeIds.has(node.id)) continue; - outNodes.push(node); - } - - return { nodes: outNodes, edges: outEdges }; - }, - - kindCounts(idx: TreeIndex): Record { - const counts: Record = {}; - for (const node of idx.nodes.values()) { - counts[node.kind] = (counts[node.kind] ?? 0) + 1; - } - return counts; - }, + canonicalize( + name: string, + crateTree: CrateTree, + options?: { mode?: TreeMode; includeExternal?: boolean }, + ): CrateTree { + const mode = options?.mode ?? "structural"; + const includeExternal = options?.includeExternal ?? false; + const normalizedName = normalizeCrateName(name); + const structuralOnly = mode === "structural"; + const allowedNodeIds = new Set(); + const nodeById = new Map(crateTree.nodes.map((n) => [n.id, n])); + const outEdges: CrateTree["edges"] = []; + const parentByChild = structuralOnly ? new Map() : null; + + for (const edge of crateTree.edges) { + if (structuralOnly && edge.kind !== "Contains" && edge.kind !== "Defines") continue; + const from = nodeById.get(edge.from); + const to = nodeById.get(edge.to); + if (!from || !to) continue; + if (!includeExternal && (from.is_external || to.is_external)) continue; + if (parentByChild && !parentByChild.has(edge.to)) parentByChild.set(edge.to, edge.from); + allowedNodeIds.add(edge.from); + allowedNodeIds.add(edge.to); + outEdges.push(edge); + } + + if (structuralOnly && parentByChild) { + const preferredRoot = nodeById.has(normalizedName) + ? normalizedName + : nodeById.has(name) + ? name + : null; + const crateRoot = + preferredRoot ?? + crateTree.nodes.find( + (node) => node.kind === "Crate" && (!node.is_external || includeExternal), + )?.id ?? + null; + + if (crateRoot) { + const reachMemo = new Map(); + reachMemo.set(crateRoot, true); + + const isReachableFromRoot = (startId: string): boolean => { + const cached = reachMemo.get(startId); + if (cached !== undefined) return cached; + + const path: string[] = []; + const seen = new Set(); + let current = startId; + + while (true) { + const memoized = reachMemo.get(current); + if (memoized !== undefined) { + for (const id of path) reachMemo.set(id, memoized); + return memoized; + } + if (current === crateRoot) { + for (const id of path) reachMemo.set(id, true); + reachMemo.set(current, true); + return true; + } + if (seen.has(current)) { + for (const id of path) reachMemo.set(id, false); + return false; + } + seen.add(current); + path.push(current); + + const parent = parentByChild.get(current); + if (!parent) { + for (const id of path) reachMemo.set(id, false); + return false; + } + current = parent; + } + }; + + const prunedEdges = outEdges.filter( + (edge) => isReachableFromRoot(edge.from) && isReachableFromRoot(edge.to), + ); + + allowedNodeIds.clear(); + for (const edge of prunedEdges) { + allowedNodeIds.add(edge.from); + allowedNodeIds.add(edge.to); + } + allowedNodeIds.add(crateRoot); + + outEdges.length = 0; + for (const edge of prunedEdges) outEdges.push(edge); + } + } + + if (structuralOnly) { + if (nodeById.has(name)) allowedNodeIds.add(name); + if (nodeById.has(normalizedName)) allowedNodeIds.add(normalizedName); + } + + const outNodes: CrateTree["nodes"] = []; + for (const node of crateTree.nodes) { + if (!includeExternal && node.is_external) continue; + if (structuralOnly && !allowedNodeIds.has(node.id)) continue; + outNodes.push(node); + } + + return { nodes: outNodes, edges: outEdges }; + }, + + kindCounts(idx: TreeIndex): Record { + const counts: Record = {}; + for (const node of idx.nodes.values()) { + counts[node.kind] = (counts[node.kind] ?? 0) + 1; + } + return counts; + }, } satisfies TreeOps; function buildKindFacets(kindCounts: Record): KindFacet[] { - return nodeKindOrder.map((kind) => ({ - kind, - label: kindLabels[kind], - count: kindCounts[kind] ?? 0, - })); + return nodeKindOrder.map((kind) => ({ + kind, + label: kindLabels[kind], + count: kindCounts[kind] ?? 0, + })); } // ── Loader class ────────────────────────────────────────────────────── export class Loader { - async provider(p?: Provider): Promise { - return p ?? initProvider(getRequestEvent()); - } - - async localWorkspace(p?: Provider): Promise { - const resolved = await this.provider(p); - if (isHosted || !hasLocalWorkspace(resolved)) return null; - return resolved.loadWorkspace(); - } - - async crateGraph( - name: string, - version?: string, - p?: Provider, - ): Promise { - const resolved = await this.provider(p); - return resolved.loadCrateGraph(name, version ?? 'latest'); - } + async provider(p?: Provider): Promise { + return p ?? initProvider(getRequestEvent()); + } + + async localWorkspace(p?: Provider): Promise { + const resolved = await this.provider(p); + if (isHosted || !hasLocalWorkspace(resolved)) return null; + return resolved.loadWorkspace(); + } + + async crateGraph( + name: string, + version?: string, + p?: Provider, + ): Promise { + const resolved = await this.provider(p); + return resolved.loadCrateGraph(name, version ?? "latest"); + } } export const loader = new Loader(); @@ -198,42 +198,42 @@ export const loader = new Loader(); // Cached lookup structures (built once from the cached workspace) let _allNodesCache: Map | null = null; -let _edgesBySrcCache: Map | null = null; -let _edgesByDstCache: Map | null = null; +let _edgesBySrcCache: Map | null = null; +let _edgesByDstCache: Map | null = null; let _cachedWorkspaceRef: Workspace | null = null; export function getAllNodes(ws: Workspace): Map { - if (_allNodesCache && _cachedWorkspaceRef === ws) return _allNodesCache; - const map = new Map(); - for (const c of ws.crates) { - for (const n of c.nodes) map.set(n.id, n); - } - for (const ext of ws.external_crates) { - for (const n of ext.nodes) map.set(n.id, n); - } - _allNodesCache = map; - _cachedWorkspaceRef = ws; - return map; + if (_allNodesCache && _cachedWorkspaceRef === ws) return _allNodesCache; + const map = new Map(); + for (const c of ws.crates) { + for (const n of c.nodes) map.set(n.id, n); + } + for (const ext of ws.external_crates) { + for (const n of ext.nodes) map.set(n.id, n); + } + _allNodesCache = map; + _cachedWorkspaceRef = ws; + return map; } export function getCrossEdgesByNode(ws: Workspace): { - bySrc: Map; - byDst: Map; + bySrc: Map; + byDst: Map; } { - if (_edgesBySrcCache && _edgesByDstCache && _cachedWorkspaceRef === ws) { - return { bySrc: _edgesBySrcCache, byDst: _edgesByDstCache }; - } - const bySrc = new Map(); - const byDst = new Map(); - for (const e of ws.cross_crate_edges) { - if (!bySrc.has(e.from)) bySrc.set(e.from, []); - bySrc.get(e.from)!.push(e); - if (!byDst.has(e.to)) byDst.set(e.to, []); - byDst.get(e.to)!.push(e); - } - _edgesBySrcCache = bySrc; - _edgesByDstCache = byDst; - return { bySrc, byDst }; + if (_edgesBySrcCache && _edgesByDstCache && _cachedWorkspaceRef === ws) { + return { bySrc: _edgesBySrcCache, byDst: _edgesByDstCache }; + } + const bySrc = new Map(); + const byDst = new Map(); + for (const e of ws.cross_crate_edges) { + if (!bySrc.has(e.from)) bySrc.set(e.from, []); + bySrc.get(e.from)!.push(e); + if (!byDst.has(e.to)) byDst.set(e.to, []); + byDst.get(e.to)!.push(e); + } + _edgesBySrcCache = bySrc; + _edgesByDstCache = byDst; + return { bySrc, byDst }; } // ── Crate edge index (O(1) per-node edge lookup) ────────────────────── @@ -242,37 +242,37 @@ let _crateEdgeIndex: Map | null = null; let _crateEdgeCrateRef: object | null = null; function getCrateEdgeIndex(crate: { edges: Edge[] }): Map { - if (_crateEdgeIndex && _crateEdgeCrateRef === crate) return _crateEdgeIndex; - const index = new Map(); - for (const e of crate.edges) { - for (const id of [e.from, e.to]) { - let list = index.get(id); - if (!list) { - list = []; - index.set(id, list); - } - list.push(e); - } - } - _crateEdgeIndex = index; - _crateEdgeCrateRef = crate; - return index; + if (_crateEdgeIndex && _crateEdgeCrateRef === crate) return _crateEdgeIndex; + const index = new Map(); + for (const e of crate.edges) { + for (const id of [e.from, e.to]) { + let list = index.get(id); + if (!list) { + list = []; + index.set(id, list); + } + list.push(e); + } + } + _crateEdgeIndex = index; + _crateEdgeCrateRef = crate; + return index; } function nodeFromSummary(summary: NodeSummary): Node { - return { - id: summary.id, - name: summary.name, - kind: summary.kind, - visibility: summary.visibility, - span: null, - attrs: [], - is_external: summary.is_external, - is_deprecated: summary.is_deprecated, - generics: summary.generics, - impl_category: summary.impl_category, - impl_trait: summary.impl_trait, - }; + return { + id: summary.id, + name: summary.name, + kind: summary.kind, + visibility: summary.visibility, + span: null, + attrs: [], + is_external: summary.is_external, + is_deprecated: summary.is_deprecated, + generics: summary.generics, + impl_category: summary.impl_category, + impl_trait: summary.impl_trait, + }; } // ── Resolver class ──────────────────────────────────────────────────── @@ -282,420 +282,420 @@ function nodeFromSummary(summary: NodeSummary): Node { * Remote functions delegate to these — keeps logic DRY and testable. */ export class Resolver { - readonly #cache = new Map(); - readonly #loader: Loader; - - constructor(loader: Loader) { - this.#loader = loader; - } - - async nodeDetail( - input: NodeDetailInput, - provider: Provider, - workspace: Workspace | null, - ): Promise { - const { nodeId, version } = input; - return perf.timeAsync( - 'server', - `getNodeDetail(${nodeId})`, - async () => { - const cratePrefix = nodeId.split('::')[0]; - // Provider lookups (DO/R2) are keyed by hyphenated name (URL convention), - // but node IDs use underscores (Rust convention). - const crateNameForProvider = hyphenateCrateName(cratePrefix); - - if (workspace) { - const crate = workspace.crates.find( - (c) => - normalizeCrateName(c.id) === normalizeCrateName(cratePrefix) || - normalizeCrateName(c.name) === normalizeCrateName(cratePrefix), - ); - if (crate) { - const allNodes = getAllNodes(workspace); - const node = allNodes.get(nodeId); - if (!node) return null; - - // Collect edges: from the crate's internal edges + cross-crate indexed edges - const { bySrc, byDst } = getCrossEdgesByNode(workspace); - const edges = [ - ...(getCrateEdgeIndex(crate).get(nodeId) ?? []), - ...(bySrc.get(nodeId) ?? []), - ...(byDst.get(nodeId) ?? []), - ]; - - // Related nodes referenced by those edges - const relatedIds = new Set(); - for (const e of edges) { - relatedIds.add(e.from); - relatedIds.add(e.to); - } - relatedIds.delete(nodeId); - - const relatedNodes: Node[] = []; - for (const id of relatedIds) { - const n = allNodes.get(id); - if (n) relatedNodes.push(n); - } - - return { node, edges, relatedNodes }; - } - // Not a local workspace crate — fall through to universal path - } - - // Universal path: prefer provider-level node detail to avoid loading full graphs. - if (provider.loadNodeDetail) { - const detail = await provider.loadNodeDetail( - crateNameForProvider, - version ?? 'latest', - nodeId, - ); - if (detail) return detail; - } - - // Fallback: load crate graph by ref (skip in hosted to avoid RPC limits) - if (isHosted) return null; - const graph = await provider.loadCrateGraph(crateNameForProvider, version ?? 'latest'); - if (!graph) return null; - - const nodesById = new Map(); - for (const n of graph.nodes) nodesById.set(n.id, n); - const node = nodesById.get(nodeId); - if (!node) return null; - - const edges = graph.edges.filter((e) => e.from === nodeId || e.to === nodeId); - const crossData = await provider.getCrossEdgeData(nodeId); - const edgeKey = (e: { - from: string; - to: string; - kind: string; - confidence: string; - is_glob?: boolean; - }) => `${e.from}|${e.to}|${e.kind}|${e.confidence}|${e.is_glob ? 'glob' : 'named'}`; - const edgeKeys = new Set(edges.map((e) => edgeKey(e))); - for (const e of crossData.edges) { - if (!edgeKeys.has(edgeKey(e))) { - edges.push(e); - edgeKeys.add(edgeKey(e)); - } - } - const relatedIds = new Set(); - for (const e of edges) { - relatedIds.add(e.from); - relatedIds.add(e.to); - } - relatedIds.delete(nodeId); - - const relatedNodesMap = new Map(); - for (const id of relatedIds) { - const n = nodesById.get(id); - if (n) relatedNodesMap.set(id, n); - } - for (const n of crossData.nodes) { - if (!relatedNodesMap.has(n.id)) relatedNodesMap.set(n.id, nodeFromSummary(n)); - } - const relatedNodes = Array.from(relatedNodesMap.values()); - - return { node, edges, relatedNodes }; - }, - { - detail: (r) => (r ? `${r.edges.length}e ${r.relatedNodes.length}r` : 'null'), - }, - ); - } - - async treeIndex(name: string, version: string, provider?: Provider): Promise { - const key = `${name}@${version}`; - const cached = this.#cache.get(key); - const resolved = await this.#loader.provider(provider); - let status: { status: string } | null = null; - if (cached) { - if (cached.ready) return cached.idx; - status = await resolved.getCrateStatus(name, version); - if (status.status !== 'ready') return cached.idx; - } - - return perf.timeAsync('server', `resolveTreeIndex(${key})`, async () => { - const ws = await this.#loader.localWorkspace(resolved); - let crateTree: CrateTree | null = null; - - // Local workspace path - const normalizedName = normalizeCrateName(name); - const wsCrate = - ws?.crates.find( - (c) => - normalizeCrateName(c.id) === normalizedName || - normalizeCrateName(c.name) === normalizedName, - ) ?? null; - if (wsCrate) { - const internalNodes = wsCrate.nodes.filter((n) => !n.is_external); - const internalIds = new Set(internalNodes.map((n) => n.id)); - const treeEdges = wsCrate.edges.filter( - (e) => - (e.kind === 'Contains' || e.kind === 'Defines') && - internalIds.has(e.from) && - internalIds.has(e.to), - ); - crateTree = tree.canonicalize(name, { - nodes: internalNodes.map(summarizeNode), - edges: treeEdges, - }); - } - - // Provider tree - if (!crateTree) { - crateTree = await resolved.loadCrateTree(name, version); - if (crateTree) crateTree = tree.canonicalize(name, crateTree); - } - - if (!crateTree) { - status ??= await resolved.getCrateStatus(name, version); - } - - // Fallback: full graph (local only) - if (!crateTree && !isHosted) { - const graph = await this.#loader.crateGraph( - name, - version === 'latest' ? undefined : version, - resolved, - ); - if (graph) { - const internalNodes = graph.nodes.filter((n) => !n.is_external); - const internalIds = new Set(internalNodes.map((n) => n.id)); - const treeEdges = graph.edges.filter( - (e) => - (e.kind === 'Contains' || e.kind === 'Defines') && - internalIds.has(e.from) && - internalIds.has(e.to), - ); - crateTree = tree.canonicalize(name, { - nodes: internalNodes.map(summarizeNode), - edges: treeEdges, - }); - } - } - - if (!crateTree) return null; - - const idx = new TreeIndex(); - // NodeSummary is a subset of Node — TreeIndex only uses id/kind/name - idx.ensure({ nodes: crateTree.nodes as Node[], edges: crateTree.edges }); - status ??= await resolved.getCrateStatus(name, version); - this.#cache.set(key, { idx, ready: status.status === 'ready' }); - log.info`resolveTreeIndex cached ${key} nodes=${crateTree.nodes.length} edges=${crateTree.edges.length} roots=${idx.rootCount}`; - return idx; - }); - } - - async crateMeta(name: string, version: string, p?: Provider): Promise { - const provider = await this.#loader.provider(p); - const [index, versions, treeMeta] = await Effect.runPromise( - Effect.all( - [ - Effect.promise(() => provider.loadCrateIndex(name, version)), - Effect.promise(() => provider.getCrateVersions(name)), - Effect.promise(() => provider.loadTreeMeta?.(name, version) ?? Promise.resolve(null)), - ] as const, - { concurrency: 3 }, - ), - ); - if (treeMeta) { - return { - index, - versions, - kindCounts: treeMeta.kindCounts, - kindFacets: buildKindFacets(treeMeta.kindCounts), - }; - } - const treeIdx = await this.treeIndex(name, version, provider); - const kindCounts = treeIdx ? tree.kindCounts(treeIdx) : {}; - return { index, versions, kindCounts, kindFacets: buildKindFacets(kindCounts) }; - } - - async treeRoots(name: string, version: string, p?: Provider): Promise { - const provider = await this.#loader.provider(p); - if (isHosted && provider.loadTreeRootsDirect) { - return (await provider.loadTreeRootsDirect(name, version)) ?? []; - } - const idx = await this.treeIndex(name, version, provider); - if (idx) { - const rootIds = idx.getRootIds(); - const roots: TreeNodeDTO[] = []; - for (const id of rootIds) { - const node = idx.getNode(id); - if (!node) continue; - roots.push({ node: summarizeNode(node), hasChildren: idx.hasChildren(id) }); - } - return roots; - } - // Fallback: query DB directly (works mid-parse before treeJson is written) - if (provider.loadTreeRootsDirect) { - return (await provider.loadTreeRootsDirect(name, version)) ?? []; - } - return []; - } - - async nodeView({ name, version, nodeId }: NodeViewInput, p?: Provider): Promise { - const provider = await this.#loader.provider(p); - const resolvedVersion = version ?? 'latest'; - if (isHosted && provider.loadNodeViewDirect) { - const direct = await provider.loadNodeViewDirect(name, resolvedVersion, nodeId); - return direct; - } - const ws = await this.#loader.localWorkspace(provider); - if (isHosted) { - const [detail, ancestors] = await Effect.runPromise( - Effect.all( - [ - Effect.promise(() => - this.nodeDetail({ nodeId, version: resolvedVersion }, provider, ws), - ), - Effect.promise( - () => - provider.loadTreeAncestorsDirect?.(name, resolvedVersion, nodeId) ?? - Promise.resolve([]), - ), - ] as const, - { concurrency: 2 }, - ), - ); - if (detail) return { detail, ancestors: ancestors ?? [] }; - } - const [detail, idx] = await Effect.runPromise( - Effect.all( - [ - Effect.promise(() => this.nodeDetail({ nodeId, version: resolvedVersion }, provider, ws)), - Effect.promise(() => this.treeIndex(name, resolvedVersion, provider)), - ] as const, - { concurrency: 2 }, - ), - ); - - let resolvedDetail = detail; - let resolvedNodeId = nodeId; - - // If direct lookup failed, try resolving as a re-exported item. - // e.g. URL "syn::Item" → canonical "syn::item::Item" - if (!detail && idx) { - const canonical = this.#findCanonicalNodeId(idx, nodeId); - if (canonical) { - resolvedNodeId = canonical; - log.info`resolved re-export ${nodeId} → ${canonical}`; - resolvedDetail = await this.nodeDetail( - { nodeId: canonical, version: resolvedVersion }, - provider, - ws, - ); - } - } - - if (!resolvedDetail) return null; - - // If tree index available, walk ancestors normally - // If not (mid-parse), try direct DB query or return empty ancestors - let ancestors: NodeSummary[] = []; - if (idx) { - ancestors = this.#walkAncestors(idx, resolvedNodeId); - } else if (provider.loadTreeAncestorsDirect) { - ancestors = - (await provider.loadTreeAncestorsDirect(name, resolvedVersion, resolvedNodeId)) ?? []; - } - - return { detail: resolvedDetail, ancestors }; - } - - /** - * Resolve a canonical node ID for a potentially re-exported item. - * Returns the canonical ID if the tree contains a node whose - * ID is `null` if no match is found. - */ - async resolveCanonicalNodeId( - name: string, - version: string, - nodeId: string, - ): Promise { - const idx = await this.treeIndex(name, version); - if (!idx) return null; - if (idx.getNode(nodeId)) return nodeId; - return this.#findCanonicalNodeId(idx, nodeId); - } - - /** - * Search the tree for a node matching a re-exported path. - * Given "syn::Item", finds "syn::item::Item" by suffix match. - * Skips impl-scoped nodes (associated types/methods) since those - * can't be re-exported to the crate root. - * Prefers the shallowest match (fewest :: segments). - */ - #findCanonicalNodeId(idx: TreeIndex, nodeId: string): string | null { - const parts = nodeId.split('::'); - if (parts.length < 2) return null; - const cratePrefix = parts[0]; - const targetSuffix = `::${parts.slice(1).join('::')}`; - - let best: string | null = null; - let bestSegments = Infinity; - - for (const id of idx.nodes.keys()) { - if (!id.startsWith(`${cratePrefix}::`) || id === nodeId) continue; - // Skip impl-scoped nodes (e.g. "syn::impl-10584::Item") — associated - // types and methods live under impl blocks and can't be re-exported. - if (id.includes('::impl-')) continue; - if (id.endsWith(targetSuffix)) { - const segments = id.split('::').length; - if (segments < bestSegments) { - bestSegments = segments; - best = id; - } - } - } - - return best; - } - - #walkAncestors(idx: TreeIndex, nodeId: string): NodeSummary[] { - const ancestors: NodeSummary[] = []; - let currentId: string | undefined = idx.parents.get(nodeId); - const visited = new Set(); - while (currentId && !visited.has(currentId)) { - visited.add(currentId); - const node = idx.getNode(currentId); - if (node) ancestors.unshift(summarizeNode(node)); - currentId = idx.parents.get(currentId); - } - return ancestors; - } - - async treeChildren( - name: string, - version: string, - parentId: string, - p?: Provider, - ): Promise { - const provider = await this.#loader.provider(p); - if (isHosted && provider.loadTreeChildrenDirect) { - return (await provider.loadTreeChildrenDirect(name, version, parentId)) ?? []; - } - const idx = await this.treeIndex(name, version, provider); - if (idx) { - return this.#childDTOs(idx, parentId); - } - // Fallback: direct DB query (works mid-parse) - if (provider.loadTreeChildrenDirect) { - return (await provider.loadTreeChildrenDirect(name, version, parentId)) ?? []; - } - return []; - } - - #childDTOs(idx: TreeIndex, parentId: string): TreeNodeDTO[] { - const ids = idx.getChildIds(parentId); - const result: TreeNodeDTO[] = []; - for (const id of ids) { - const node = idx.getNode(id); - if (!node) continue; - result.push({ node: summarizeNode(node), hasChildren: idx.hasChildren(id) }); - } - return result; - } + readonly #cache = new Map(); + readonly #loader: Loader; + + constructor(loader: Loader) { + this.#loader = loader; + } + + async nodeDetail( + input: NodeDetailInput, + provider: Provider, + workspace: Workspace | null, + ): Promise { + const { nodeId, version } = input; + return perf.timeAsync( + "server", + `getNodeDetail(${nodeId})`, + async () => { + const cratePrefix = nodeId.split("::")[0]; + // Provider lookups (DO/R2) are keyed by hyphenated name (URL convention), + // but node IDs use underscores (Rust convention). + const crateNameForProvider = hyphenateCrateName(cratePrefix); + + if (workspace) { + const crate = workspace.crates.find( + (c) => + normalizeCrateName(c.id) === normalizeCrateName(cratePrefix) || + normalizeCrateName(c.name) === normalizeCrateName(cratePrefix), + ); + if (crate) { + const allNodes = getAllNodes(workspace); + const node = allNodes.get(nodeId); + if (!node) return null; + + // Collect edges: from the crate's internal edges + cross-crate indexed edges + const { bySrc, byDst } = getCrossEdgesByNode(workspace); + const edges = [ + ...(getCrateEdgeIndex(crate).get(nodeId) ?? []), + ...(bySrc.get(nodeId) ?? []), + ...(byDst.get(nodeId) ?? []), + ]; + + // Related nodes referenced by those edges + const relatedIds = new Set(); + for (const e of edges) { + relatedIds.add(e.from); + relatedIds.add(e.to); + } + relatedIds.delete(nodeId); + + const relatedNodes: Node[] = []; + for (const id of relatedIds) { + const n = allNodes.get(id); + if (n) relatedNodes.push(n); + } + + return { node, edges, relatedNodes }; + } + // Not a local workspace crate — fall through to universal path + } + + // Universal path: prefer provider-level node detail to avoid loading full graphs. + if (provider.loadNodeDetail) { + const detail = await provider.loadNodeDetail( + crateNameForProvider, + version ?? "latest", + nodeId, + ); + if (detail) return detail; + } + + // Fallback: load crate graph by ref (skip in hosted to avoid RPC limits) + if (isHosted) return null; + const graph = await provider.loadCrateGraph(crateNameForProvider, version ?? "latest"); + if (!graph) return null; + + const nodesById = new Map(); + for (const n of graph.nodes) nodesById.set(n.id, n); + const node = nodesById.get(nodeId); + if (!node) return null; + + const edges = graph.edges.filter((e) => e.from === nodeId || e.to === nodeId); + const crossData = await provider.getCrossEdgeData(nodeId); + const edgeKey = (e: { + from: string; + to: string; + kind: string; + confidence: string; + is_glob?: boolean; + }) => `${e.from}|${e.to}|${e.kind}|${e.confidence}|${e.is_glob ? "glob" : "named"}`; + const edgeKeys = new Set(edges.map((e) => edgeKey(e))); + for (const e of crossData.edges) { + if (!edgeKeys.has(edgeKey(e))) { + edges.push(e); + edgeKeys.add(edgeKey(e)); + } + } + const relatedIds = new Set(); + for (const e of edges) { + relatedIds.add(e.from); + relatedIds.add(e.to); + } + relatedIds.delete(nodeId); + + const relatedNodesMap = new Map(); + for (const id of relatedIds) { + const n = nodesById.get(id); + if (n) relatedNodesMap.set(id, n); + } + for (const n of crossData.nodes) { + if (!relatedNodesMap.has(n.id)) relatedNodesMap.set(n.id, nodeFromSummary(n)); + } + const relatedNodes = Array.from(relatedNodesMap.values()); + + return { node, edges, relatedNodes }; + }, + { + detail: (r) => (r ? `${r.edges.length}e ${r.relatedNodes.length}r` : "null"), + }, + ); + } + + async treeIndex(name: string, version: string, provider?: Provider): Promise { + const key = `${name}@${version}`; + const cached = this.#cache.get(key); + const resolved = await this.#loader.provider(provider); + let status: { status: string } | null = null; + if (cached) { + if (cached.ready) return cached.idx; + status = await resolved.getCrateStatus(name, version); + if (status.status !== "ready") return cached.idx; + } + + return perf.timeAsync("server", `resolveTreeIndex(${key})`, async () => { + const ws = await this.#loader.localWorkspace(resolved); + let crateTree: CrateTree | null = null; + + // Local workspace path + const normalizedName = normalizeCrateName(name); + const wsCrate = + ws?.crates.find( + (c) => + normalizeCrateName(c.id) === normalizedName || + normalizeCrateName(c.name) === normalizedName, + ) ?? null; + if (wsCrate) { + const internalNodes = wsCrate.nodes.filter((n) => !n.is_external); + const internalIds = new Set(internalNodes.map((n) => n.id)); + const treeEdges = wsCrate.edges.filter( + (e) => + (e.kind === "Contains" || e.kind === "Defines") && + internalIds.has(e.from) && + internalIds.has(e.to), + ); + crateTree = tree.canonicalize(name, { + nodes: internalNodes.map(summarizeNode), + edges: treeEdges, + }); + } + + // Provider tree + if (!crateTree) { + crateTree = await resolved.loadCrateTree(name, version); + if (crateTree) crateTree = tree.canonicalize(name, crateTree); + } + + if (!crateTree) { + status ??= await resolved.getCrateStatus(name, version); + } + + // Fallback: full graph (local only) + if (!crateTree && !isHosted) { + const graph = await this.#loader.crateGraph( + name, + version === "latest" ? undefined : version, + resolved, + ); + if (graph) { + const internalNodes = graph.nodes.filter((n) => !n.is_external); + const internalIds = new Set(internalNodes.map((n) => n.id)); + const treeEdges = graph.edges.filter( + (e) => + (e.kind === "Contains" || e.kind === "Defines") && + internalIds.has(e.from) && + internalIds.has(e.to), + ); + crateTree = tree.canonicalize(name, { + nodes: internalNodes.map(summarizeNode), + edges: treeEdges, + }); + } + } + + if (!crateTree) return null; + + const idx = new TreeIndex(); + // NodeSummary is a subset of Node — TreeIndex only uses id/kind/name + idx.ensure({ nodes: crateTree.nodes as Node[], edges: crateTree.edges }); + status ??= await resolved.getCrateStatus(name, version); + this.#cache.set(key, { idx, ready: status.status === "ready" }); + log.info`resolveTreeIndex cached ${key} nodes=${crateTree.nodes.length} edges=${crateTree.edges.length} roots=${idx.rootCount}`; + return idx; + }); + } + + async crateMeta(name: string, version: string, p?: Provider): Promise { + const provider = await this.#loader.provider(p); + const [index, versions, treeMeta] = await Effect.runPromise( + Effect.all( + [ + Effect.promise(() => provider.loadCrateIndex(name, version)), + Effect.promise(() => provider.getCrateVersions(name)), + Effect.promise(() => provider.loadTreeMeta?.(name, version) ?? Promise.resolve(null)), + ] as const, + { concurrency: 3 }, + ), + ); + if (treeMeta) { + return { + index, + versions, + kindCounts: treeMeta.kindCounts, + kindFacets: buildKindFacets(treeMeta.kindCounts), + }; + } + const treeIdx = await this.treeIndex(name, version, provider); + const kindCounts = treeIdx ? tree.kindCounts(treeIdx) : {}; + return { index, versions, kindCounts, kindFacets: buildKindFacets(kindCounts) }; + } + + async treeRoots(name: string, version: string, p?: Provider): Promise { + const provider = await this.#loader.provider(p); + if (isHosted && provider.loadTreeRootsDirect) { + return (await provider.loadTreeRootsDirect(name, version)) ?? []; + } + const idx = await this.treeIndex(name, version, provider); + if (idx) { + const rootIds = idx.getRootIds(); + const roots: TreeNodeDTO[] = []; + for (const id of rootIds) { + const node = idx.getNode(id); + if (!node) continue; + roots.push({ node: summarizeNode(node), hasChildren: idx.hasChildren(id) }); + } + return roots; + } + // Fallback: query DB directly (works mid-parse before treeJson is written) + if (provider.loadTreeRootsDirect) { + return (await provider.loadTreeRootsDirect(name, version)) ?? []; + } + return []; + } + + async nodeView({ name, version, nodeId }: NodeViewInput, p?: Provider): Promise { + const provider = await this.#loader.provider(p); + const resolvedVersion = version ?? "latest"; + if (isHosted && provider.loadNodeViewDirect) { + const direct = await provider.loadNodeViewDirect(name, resolvedVersion, nodeId); + return direct; + } + const ws = await this.#loader.localWorkspace(provider); + if (isHosted) { + const [detail, ancestors] = await Effect.runPromise( + Effect.all( + [ + Effect.promise(() => + this.nodeDetail({ nodeId, version: resolvedVersion }, provider, ws), + ), + Effect.promise( + () => + provider.loadTreeAncestorsDirect?.(name, resolvedVersion, nodeId) ?? + Promise.resolve([]), + ), + ] as const, + { concurrency: 2 }, + ), + ); + if (detail) return { detail, ancestors: ancestors ?? [] }; + } + const [detail, idx] = await Effect.runPromise( + Effect.all( + [ + Effect.promise(() => this.nodeDetail({ nodeId, version: resolvedVersion }, provider, ws)), + Effect.promise(() => this.treeIndex(name, resolvedVersion, provider)), + ] as const, + { concurrency: 2 }, + ), + ); + + let resolvedDetail = detail; + let resolvedNodeId = nodeId; + + // If direct lookup failed, try resolving as a re-exported item. + // e.g. URL "syn::Item" → canonical "syn::item::Item" + if (!detail && idx) { + const canonical = this.#findCanonicalNodeId(idx, nodeId); + if (canonical) { + resolvedNodeId = canonical; + log.info`resolved re-export ${nodeId} → ${canonical}`; + resolvedDetail = await this.nodeDetail( + { nodeId: canonical, version: resolvedVersion }, + provider, + ws, + ); + } + } + + if (!resolvedDetail) return null; + + // If tree index available, walk ancestors normally + // If not (mid-parse), try direct DB query or return empty ancestors + let ancestors: NodeSummary[] = []; + if (idx) { + ancestors = this.#walkAncestors(idx, resolvedNodeId); + } else if (provider.loadTreeAncestorsDirect) { + ancestors = + (await provider.loadTreeAncestorsDirect(name, resolvedVersion, resolvedNodeId)) ?? []; + } + + return { detail: resolvedDetail, ancestors }; + } + + /** + * Resolve a canonical node ID for a potentially re-exported item. + * Returns the canonical ID if the tree contains a node whose + * ID is `null` if no match is found. + */ + async resolveCanonicalNodeId( + name: string, + version: string, + nodeId: string, + ): Promise { + const idx = await this.treeIndex(name, version); + if (!idx) return null; + if (idx.getNode(nodeId)) return nodeId; + return this.#findCanonicalNodeId(idx, nodeId); + } + + /** + * Search the tree for a node matching a re-exported path. + * Given "syn::Item", finds "syn::item::Item" by suffix match. + * Skips impl-scoped nodes (associated types/methods) since those + * can't be re-exported to the crate root. + * Prefers the shallowest match (fewest :: segments). + */ + #findCanonicalNodeId(idx: TreeIndex, nodeId: string): string | null { + const parts = nodeId.split("::"); + if (parts.length < 2) return null; + const cratePrefix = parts[0]; + const targetSuffix = `::${parts.slice(1).join("::")}`; + + let best: string | null = null; + let bestSegments = Infinity; + + for (const id of idx.nodes.keys()) { + if (!id.startsWith(`${cratePrefix}::`) || id === nodeId) continue; + // Skip impl-scoped nodes (e.g. "syn::impl-10584::Item") — associated + // types and methods live under impl blocks and can't be re-exported. + if (id.includes("::impl-")) continue; + if (id.endsWith(targetSuffix)) { + const segments = id.split("::").length; + if (segments < bestSegments) { + bestSegments = segments; + best = id; + } + } + } + + return best; + } + + #walkAncestors(idx: TreeIndex, nodeId: string): NodeSummary[] { + const ancestors: NodeSummary[] = []; + let currentId: string | undefined = idx.parents.get(nodeId); + const visited = new Set(); + while (currentId && !visited.has(currentId)) { + visited.add(currentId); + const node = idx.getNode(currentId); + if (node) ancestors.unshift(summarizeNode(node)); + currentId = idx.parents.get(currentId); + } + return ancestors; + } + + async treeChildren( + name: string, + version: string, + parentId: string, + p?: Provider, + ): Promise { + const provider = await this.#loader.provider(p); + if (isHosted && provider.loadTreeChildrenDirect) { + return (await provider.loadTreeChildrenDirect(name, version, parentId)) ?? []; + } + const idx = await this.treeIndex(name, version, provider); + if (idx) { + return this.#childDTOs(idx, parentId); + } + // Fallback: direct DB query (works mid-parse) + if (provider.loadTreeChildrenDirect) { + return (await provider.loadTreeChildrenDirect(name, version, parentId)) ?? []; + } + return []; + } + + #childDTOs(idx: TreeIndex, parentId: string): TreeNodeDTO[] { + const ids = idx.getChildIds(parentId); + const result: TreeNodeDTO[] = []; + for (const id of ids) { + const node = idx.getNode(id); + if (!node) continue; + result.push({ node: summarizeNode(node), hasChildren: idx.hasChildren(id) }); + } + return result; + } } export const resolve = new Resolver(loader); diff --git a/codeview-ui/src/lib/rpc/meta.remote.ts b/codeview-ui/src/lib/rpc/meta.remote.ts index 76221cd..0d61189 100644 --- a/codeview-ui/src/lib/rpc/meta.remote.ts +++ b/codeview-ui/src/lib/rpc/meta.remote.ts @@ -1,36 +1,36 @@ -import { prerender, query } from '$app/server'; -import { getLogger } from '#lib/log'; -import { perf } from '#lib/perf'; -import type { CrateMeta } from '#lib/schema'; -import { resolve } from './helpers'; -import { assertCrateRef } from './remote-utils'; -import { CrateRefSchema } from './schemas'; +import { prerender, query } from "$app/server"; +import { getLogger } from "#lib/log"; +import { perf } from "#lib/perf"; +import type { CrateMeta } from "#lib/schema"; +import { resolve } from "./helpers"; +import { assertCrateRef } from "./remote-utils"; +import { CrateRefSchema } from "./schemas"; -const log = getLogger('rpc.meta'); +const log = getLogger("rpc.meta"); /** * Lightweight crate metadata: index + versions + kind counts. * No tree nodes or edges are sent — kind counts are computed server-side. */ async function loadCrateMeta({ name, version }: { name: string; version?: string }) { - assertCrateRef(name, version ?? 'latest'); - return perf.timeAsync( - 'server', - `getCrateMeta(${name})`, - async () => { - log.info`getCrateMeta start name=${name} version=${version ?? 'latest'}`; - const result = await resolve.crateMeta(name, version ?? 'latest'); - log.info`getCrateMeta done name=${name} versions=${result?.versions.length ?? 0} kinds=${result ? Object.keys(result.kindCounts).length : 0}`; - return result satisfies CrateMeta | null; - }, - { - detail: (r) => (r ? `${r.versions.length}v ${Object.keys(r.kindCounts).length}k` : 'null'), - }, - ); + assertCrateRef(name, version ?? "latest"); + return perf.timeAsync( + "server", + `getCrateMeta(${name})`, + async () => { + log.info`getCrateMeta start name=${name} version=${version ?? "latest"}`; + const result = await resolve.crateMeta(name, version ?? "latest"); + log.info`getCrateMeta done name=${name} versions=${result?.versions.length ?? 0} kinds=${result ? Object.keys(result.kindCounts).length : 0}`; + return result satisfies CrateMeta | null; + }, + { + detail: (r) => (r ? `${r.versions.length}v ${Object.keys(r.kindCounts).length}k` : "null"), + }, + ); } export const getCrateMeta = query(CrateRefSchema, loadCrateMeta); export const getStaticCrateMeta = prerender(CrateRefSchema, loadCrateMeta, { - dynamic: true, + dynamic: true, }); diff --git a/codeview-ui/src/lib/rpc/nodeView.remote.ts b/codeview-ui/src/lib/rpc/nodeView.remote.ts index f32288c..5b6ef0f 100644 --- a/codeview-ui/src/lib/rpc/nodeView.remote.ts +++ b/codeview-ui/src/lib/rpc/nodeView.remote.ts @@ -1,48 +1,48 @@ -import { prerender, query } from '$app/server'; -import { getLogger } from '#lib/log'; -import { perf } from '#lib/perf'; -import type { NodeView } from '#lib/schema'; -import { resolve } from './helpers'; -import { assertCrateRef } from './remote-utils'; -import { NodeViewInputSchema } from './schemas'; +import { prerender, query } from "$app/server"; +import { getLogger } from "#lib/log"; +import { perf } from "#lib/perf"; +import type { NodeView } from "#lib/schema"; +import { resolve } from "./helpers"; +import { assertCrateRef } from "./remote-utils"; +import { NodeViewInputSchema } from "./schemas"; -const log = getLogger('rpc.nodeView'); +const log = getLogger("rpc.nodeView"); /** * Combined per-node endpoint: detail + ancestors + expand children. * Eliminates the 3-roundtrip waterfall (detail → ancestors → childrenxN). */ async function loadNodeView({ - name, - version, - nodeId, + name, + version, + nodeId, }: { - name: string; - version?: string; - nodeId: string; + name: string; + version?: string; + nodeId: string; }) { - assertCrateRef(name, version ?? 'latest'); - return perf.timeAsync( - 'server', - `getNodeView(${nodeId})`, - async () => { - log.info`getNodeView start name=${name} version=${version ?? 'latest'} nodeId=${nodeId}`; - const result = await resolve.nodeView({ name, version, nodeId }); - if (result) { - log.info`getNodeView done nodeId=${nodeId} ancestors=${result.ancestors.length}`; - } else { - log.info`getNodeView returned null for nodeId=${nodeId}`; - } - return result satisfies NodeView | null; - }, - { - detail: (r) => (r ? `${r.ancestors.length}a ${r.detail.edges.length}e` : 'null'), - }, - ); + assertCrateRef(name, version ?? "latest"); + return perf.timeAsync( + "server", + `getNodeView(${nodeId})`, + async () => { + log.info`getNodeView start name=${name} version=${version ?? "latest"} nodeId=${nodeId}`; + const result = await resolve.nodeView({ name, version, nodeId }); + if (result) { + log.info`getNodeView done nodeId=${nodeId} ancestors=${result.ancestors.length}`; + } else { + log.info`getNodeView returned null for nodeId=${nodeId}`; + } + return result satisfies NodeView | null; + }, + { + detail: (r) => (r ? `${r.ancestors.length}a ${r.detail.edges.length}e` : "null"), + }, + ); } export const getNodeView = query(NodeViewInputSchema, loadNodeView); export const getStaticNodeView = prerender(NodeViewInputSchema, loadNodeView, { - dynamic: true, + dynamic: true, }); diff --git a/codeview-ui/src/lib/rpc/remote-utils.ts b/codeview-ui/src/lib/rpc/remote-utils.ts index 62d701c..c5bc0ed 100644 --- a/codeview-ui/src/lib/rpc/remote-utils.ts +++ b/codeview-ui/src/lib/rpc/remote-utils.ts @@ -1,33 +1,33 @@ -import { error } from '@sveltejs/kit'; -import type { Result } from 'better-result'; -import { isValidCrateName, isValidVersion } from '#lib/server/validation'; +import { error } from "@sveltejs/kit"; +import type { Result } from "better-result"; +import { isValidCrateName, isValidVersion } from "#lib/server/validation"; -const VERSION_ALIASES = new Set(['latest']); +const VERSION_ALIASES = new Set(["latest"]); function isAllowedVersion(version: string): boolean { - return VERSION_ALIASES.has(version) || isValidVersion(version); + return VERSION_ALIASES.has(version) || isValidVersion(version); } export function assertCrateName(name: string): void { - if (!isValidCrateName(name)) { - throw error(400, 'Invalid crate name'); - } + if (!isValidCrateName(name)) { + throw error(400, "Invalid crate name"); + } } export function assertCrateRef(name: string, version: string): void { - if (!isValidCrateName(name) || !isAllowedVersion(version)) { - throw error(400, 'Invalid crate name or version'); - } + if (!isValidCrateName(name) || !isAllowedVersion(version)) { + throw error(400, "Invalid crate name or version"); + } } type ProviderError = { _tag: string; message: string }; export function throwIfProviderErr( - result: Result, - statusByTag: Partial> = {}, - defaultStatus = 422, + result: Result, + statusByTag: Partial> = {}, + defaultStatus = 422, ): void { - if (!result.isErr()) return; - const err = result.error; - throw error(statusByTag[err._tag] ?? defaultStatus, err.message); + if (!result.isErr()) return; + const err = result.error; + throw error(statusByTag[err._tag] ?? defaultStatus, err.message); } diff --git a/codeview-ui/src/lib/rpc/roots.remote.ts b/codeview-ui/src/lib/rpc/roots.remote.ts index 21351b1..f9356e4 100644 --- a/codeview-ui/src/lib/rpc/roots.remote.ts +++ b/codeview-ui/src/lib/rpc/roots.remote.ts @@ -1,33 +1,33 @@ -import { prerender, query } from '$app/server'; -import { getLogger } from '#lib/log'; -import { perf } from '#lib/perf'; -import type { TreeNodeDTO } from '#lib/schema'; -import { resolve } from './helpers'; -import { assertCrateRef } from './remote-utils'; -import { CrateRefSchema } from './schemas'; +import { prerender, query } from "$app/server"; +import { getLogger } from "#lib/log"; +import { perf } from "#lib/perf"; +import type { TreeNodeDTO } from "#lib/schema"; +import { resolve } from "./helpers"; +import { assertCrateRef } from "./remote-utils"; +import { CrateRefSchema } from "./schemas"; -const log = getLogger('rpc.roots'); +const log = getLogger("rpc.roots"); /** * Root tree nodes for the sidebar. Returns TreeNodeDTO[] with hasChildren flags. */ async function loadTreeRoots({ name, version }: { name: string; version?: string }) { - assertCrateRef(name, version ?? 'latest'); - return perf.timeAsync( - 'server', - `getTreeRoots(${name})`, - async () => { - const resolvedVersion = version ?? 'latest'; - const roots = await resolve.treeRoots(name, resolvedVersion); - log.info`getTreeRoots done name=${name} roots=${roots.length}`; - return roots satisfies TreeNodeDTO[]; - }, - { detail: (r) => `${r.length} roots` }, - ); + assertCrateRef(name, version ?? "latest"); + return perf.timeAsync( + "server", + `getTreeRoots(${name})`, + async () => { + const resolvedVersion = version ?? "latest"; + const roots = await resolve.treeRoots(name, resolvedVersion); + log.info`getTreeRoots done name=${name} roots=${roots.length}`; + return roots satisfies TreeNodeDTO[]; + }, + { detail: (r) => `${r.length} roots` }, + ); } export const getTreeRoots = query(CrateRefSchema, loadTreeRoots); export const getStaticTreeRoots = prerender(CrateRefSchema, loadTreeRoots, { - dynamic: true, + dynamic: true, }); diff --git a/codeview-ui/src/lib/rpc/schemas.ts b/codeview-ui/src/lib/rpc/schemas.ts index 5c00172..caecf38 100644 --- a/codeview-ui/src/lib/rpc/schemas.ts +++ b/codeview-ui/src/lib/rpc/schemas.ts @@ -1,94 +1,94 @@ -import * as Schema from 'effect/Schema'; - -const NodeKind = Schema.Literal( - 'Crate', - 'Module', - 'Struct', - 'StructField', - 'Union', - 'Enum', - 'Variant', - 'Trait', - 'TraitAlias', - 'Impl', - 'Function', - 'TypeAlias', - 'AssocType', - 'Constant', - 'AssocConst', - 'Static', - 'Macro', - 'Primitive', - 'ExternCrate', - 'Import', - 'ProcMacro', -); +import * as Schema from "effect/Schema"; + +const NodeKind = Schema.Literals([ + "Crate", + "Module", + "Struct", + "StructField", + "Union", + "Enum", + "Variant", + "Trait", + "TraitAlias", + "Impl", + "Function", + "TypeAlias", + "AssocType", + "Constant", + "AssocConst", + "Static", + "Macro", + "Primitive", + "ExternCrate", + "Import", + "ProcMacro", +]); const SearchNodesInput = Schema.Struct({ - crate: Schema.optional(Schema.String), - version: Schema.optional(Schema.String), - q: Schema.optional(Schema.String), - kinds: Schema.optional(Schema.Array(NodeKind)), + crate: Schema.optional(Schema.String), + version: Schema.optional(Schema.String), + q: Schema.optional(Schema.String), + kinds: Schema.optional(Schema.Array(NodeKind)), }); const GetSourceInput = Schema.Struct({ - file: Schema.String, - crateName: Schema.optional(Schema.String), - crateVersion: Schema.optional(Schema.String), - sourceProvider: Schema.optional(Schema.Literal('auto', 'crates-io', 'github')), + file: Schema.String, + crateName: Schema.optional(Schema.String), + crateVersion: Schema.optional(Schema.String), + sourceProvider: Schema.optional(Schema.Literals(["auto", "crates-io", "github"])), }); const CrateNameInput = Schema.Struct({ - name: Schema.String, + name: Schema.String, }); const CrateVersionInput = Schema.Struct({ - name: Schema.String, - version: Schema.String, + name: Schema.String, + version: Schema.String, }); const TriggerParseInput = Schema.Struct({ - name: Schema.String, - version: Schema.String, - force: Schema.optional(Schema.Boolean), + name: Schema.String, + version: Schema.String, + force: Schema.optional(Schema.Boolean), }); const InstallStdDocsInput = Schema.Struct({ - name: Schema.String, - version: Schema.String, + name: Schema.String, + version: Schema.String, }); const RegistrySearchInput = Schema.Struct({ - q: Schema.String, + q: Schema.String, }); const CrateRef = Schema.Struct({ - name: Schema.String, - version: Schema.optional(Schema.String), - mode: Schema.optional(Schema.Literal('structural', 'complete')), - includeExternal: Schema.optional(Schema.Boolean), + name: Schema.String, + version: Schema.optional(Schema.String), + mode: Schema.optional(Schema.Literals(["structural", "complete"])), + includeExternal: Schema.optional(Schema.Boolean), }); const NodeDetailInput = Schema.Struct({ - nodeId: Schema.String, - version: Schema.optional(Schema.String), - refresh: Schema.optional(Schema.Number), + nodeId: Schema.String, + version: Schema.optional(Schema.String), + refresh: Schema.optional(Schema.Number), }); const ProcessingInput = Schema.Struct({ - refresh: Schema.optional(Schema.Number), + refresh: Schema.optional(Schema.Number), }); const TreeNodeInput = Schema.Struct({ - name: Schema.String, - version: Schema.optional(Schema.String), - nodeId: Schema.String, + name: Schema.String, + version: Schema.optional(Schema.String), + nodeId: Schema.String, }); const NodeViewInput = Schema.Struct({ - name: Schema.String, - version: Schema.optional(Schema.String), - nodeId: Schema.String, + name: Schema.String, + version: Schema.optional(Schema.String), + nodeId: Schema.String, }); const NodeIds = Schema.Array(Schema.String); diff --git a/codeview-ui/src/lib/rpc/search.remote.ts b/codeview-ui/src/lib/rpc/search.remote.ts index ac52ba0..ba33def 100644 --- a/codeview-ui/src/lib/rpc/search.remote.ts +++ b/codeview-ui/src/lib/rpc/search.remote.ts @@ -1,97 +1,97 @@ -import { query } from '$app/server'; -import { type NodeKind, type NodeSummary } from '#lib/schema'; -import { normalizeCrateName } from '#lib/crate-names'; -import { sanitizeSearchQuery } from '#lib/server/validation'; -import { summarizeNode } from '#lib/node-summary'; -import { loader, getAllNodes } from './helpers'; -import { assertCrateRef } from './remote-utils'; -import { NodeIdsSchema, SearchNodesInputSchema, type SearchNodesInput } from './schemas'; +import { query } from "$app/server"; +import { type NodeKind, type NodeSummary } from "#lib/schema"; +import { normalizeCrateName } from "#lib/crate-names"; +import { sanitizeSearchQuery } from "#lib/server/validation"; +import { summarizeNode } from "#lib/node-summary"; +import { loader, getAllNodes } from "./helpers"; +import { assertCrateRef } from "./remote-utils"; +import { NodeIdsSchema, SearchNodesInputSchema, type SearchNodesInput } from "./schemas"; const DEFAULT_SEARCH_LIMIT = 500; function matchesNodeSearch(node: NodeSummary, queryText: string, kinds: Set): boolean { - if (node.is_external || node.kind === 'Impl') return false; - if (kinds.size > 0 && !kinds.has(node.kind)) return false; - if (!queryText) return true; - const lower = queryText.toLowerCase(); - return node.name.toLowerCase().includes(lower) || node.id.toLowerCase().includes(lower); + if (node.is_external || node.kind === "Impl") return false; + if (kinds.size > 0 && !kinds.has(node.kind)) return false; + if (!queryText) return true; + const lower = queryText.toLowerCase(); + return node.name.toLowerCase().includes(lower) || node.id.toLowerCase().includes(lower); } /** Search nodes by name/id, optionally scoped to a crate */ export const searchNodes = query( - SearchNodesInputSchema, - async ({ crate: crateId, version, q, kinds = [] }: SearchNodesInput): Promise => { - const queryText = sanitizeSearchQuery(q ?? ''); - const kindSet = new Set(kinds); - if (!queryText && kindSet.size === 0) return []; - if (crateId && version) assertCrateRef(crateId, version); + SearchNodesInputSchema, + async ({ crate: crateId, version, q, kinds = [] }: SearchNodesInput): Promise => { + const queryText = sanitizeSearchQuery(q ?? ""); + const kindSet = new Set(kinds); + if (!queryText && kindSet.size === 0) return []; + if (crateId && version) assertCrateRef(crateId, version); - const provider = await loader.provider(); - const ws = await loader.localWorkspace(provider); + const provider = await loader.provider(); + const ws = await loader.localWorkspace(provider); - if (ws) { - // If scoped to a specific crate that isn't in the local workspace, fall through - const normalizedCrateId = crateId ? normalizeCrateName(crateId) : null; - const isWorkspaceCrate = - !normalizedCrateId || - ws.crates.some( - (c) => - normalizeCrateName(c.id) === normalizedCrateId || - normalizeCrateName(c.name) === normalizedCrateId, - ); - if (isWorkspaceCrate) { - const results: NodeSummary[] = []; - for (const c of ws.crates) { - if ( - normalizedCrateId && - normalizeCrateName(c.id) !== normalizedCrateId && - normalizeCrateName(c.name) !== normalizedCrateId - ) { - continue; - } - for (const n of c.nodes) { - const summary = summarizeNode(n); - if (matchesNodeSearch(summary, queryText, kindSet)) { - results.push(summary); - } - } - } - return results.slice(0, DEFAULT_SEARCH_LIMIT); - } - // Not a local workspace crate — fall through to universal path - } + if (ws) { + // If scoped to a specific crate that isn't in the local workspace, fall through + const normalizedCrateId = crateId ? normalizeCrateName(crateId) : null; + const isWorkspaceCrate = + !normalizedCrateId || + ws.crates.some( + (c) => + normalizeCrateName(c.id) === normalizedCrateId || + normalizeCrateName(c.name) === normalizedCrateId, + ); + if (isWorkspaceCrate) { + const results: NodeSummary[] = []; + for (const c of ws.crates) { + if ( + normalizedCrateId && + normalizeCrateName(c.id) !== normalizedCrateId && + normalizeCrateName(c.name) !== normalizedCrateId + ) { + continue; + } + for (const n of c.nodes) { + const summary = summarizeNode(n); + if (matchesNodeSearch(summary, queryText, kindSet)) { + results.push(summary); + } + } + } + return results.slice(0, DEFAULT_SEARCH_LIMIT); + } + // Not a local workspace crate — fall through to universal path + } - if (!crateId) return []; - if (provider.searchNodesDirect) { - const direct = await provider.searchNodesDirect( - crateId, - version ?? 'latest', - queryText, - DEFAULT_SEARCH_LIMIT, - kinds, - ); - if (direct) return direct; - } - const graph = await loader.crateGraph(crateId, version, provider); - if (!graph) return []; - return graph.nodes - .map(summarizeNode) - .filter((node) => matchesNodeSearch(node, queryText, kindSet)) - .slice(0, DEFAULT_SEARCH_LIMIT); - }, + if (!crateId) return []; + if (provider.searchNodesDirect) { + const direct = await provider.searchNodesDirect( + crateId, + version ?? "latest", + queryText, + DEFAULT_SEARCH_LIMIT, + kinds ? [...kinds] : undefined, + ); + if (direct) return direct; + } + const graph = await loader.crateGraph(crateId, version, provider); + if (!graph) return []; + return graph.nodes + .map(summarizeNode) + .filter((node) => matchesNodeSearch(node, queryText, kindSet)) + .slice(0, DEFAULT_SEARCH_LIMIT); + }, ); /** Check whether node IDs exist in the local workspace (for link validation) */ export const checkNodeExists = query( - NodeIdsSchema, - async (nodeIds: string[]): Promise> => { - const ws = await loader.localWorkspace(); - if (!ws) return {}; - const allNodes = getAllNodes(ws); - const result: Record = {}; - for (const id of nodeIds) { - result[id] = allNodes.has(id); - } - return result; - }, + NodeIdsSchema, + async (nodeIds: readonly string[]): Promise> => { + const ws = await loader.localWorkspace(); + if (!ws) return {}; + const allNodes = getAllNodes(ws); + const result: Record = {}; + for (const id of nodeIds) { + result[id] = allNodes.has(id); + } + return result; + }, ); diff --git a/codeview-ui/src/lib/rpc/source.remote.ts b/codeview-ui/src/lib/rpc/source.remote.ts index b17a687..b12620b 100644 --- a/codeview-ui/src/lib/rpc/source.remote.ts +++ b/codeview-ui/src/lib/rpc/source.remote.ts @@ -1,82 +1,82 @@ -import { getRequestEvent, query } from '$app/server'; -import * as Effect from 'effect/Effect'; -import * as Schema from 'effect/Schema'; -import { initProvider } from '#lib/server/provider'; -import type { SourceResult } from '#lib/schema'; -import { assertCrateName, assertCrateRef } from './remote-utils'; -import { GetSourceInputSchema } from './schemas'; +import { getRequestEvent, query } from "$app/server"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { initProvider } from "#lib/server/provider"; +import type { SourceResult } from "#lib/schema"; +import { assertCrateName, assertCrateRef } from "./remote-utils"; +import { GetSourceInputSchema } from "./schemas"; -class SourceLoadError extends Schema.TaggedErrorClass()('SourceLoadError', { - key: Schema.String, - cause: Schema.Defect(), - message: Schema.String, +class SourceLoadError extends Schema.TaggedError()("SourceLoadError", { + key: Schema.String, + cause: Schema.Defect(), + message: Schema.String, }) {} function unknownMessage(cause: unknown): string { - return cause instanceof Error ? cause.message : String(cause); + return cause instanceof Error ? cause.message : String(cause); } export const getSource = query.batch( - GetSourceInputSchema, - async ( - inputs, - ): Promise< - ( - input: { - file: string; - crateName?: string; - crateVersion?: string; - sourceProvider?: 'auto' | 'crates-io' | 'github'; - }, - index: number, - ) => SourceResult - > => { - const provider = await initProvider(getRequestEvent()); - const inputKey = (input: (typeof inputs)[number]) => - `${input.sourceProvider ?? 'auto'}|${input.crateName ?? ''}|${input.crateVersion ?? ''}|${input.file}`; - const uniqueInputs = new Map(); - for (const input of inputs) { - if (input.crateName && input.crateVersion) { - assertCrateRef(input.crateName, input.crateVersion); - } else if (input.crateName) { - assertCrateName(input.crateName); - } - const key = inputKey(input); - if (!uniqueInputs.has(key)) uniqueInputs.set(key, input); - } + GetSourceInputSchema, + async ( + inputs, + ): Promise< + ( + input: { + file: string; + crateName?: string; + crateVersion?: string; + sourceProvider?: "auto" | "crates-io" | "github"; + }, + index: number, + ) => SourceResult + > => { + const provider = initProvider(getRequestEvent()); + const inputKey = (input: (typeof inputs)[number]) => + `${input.sourceProvider ?? "auto"}|${input.crateName ?? ""}|${input.crateVersion ?? ""}|${input.file}`; + const uniqueInputs = new Map(); + for (const input of inputs) { + if (input.crateName && input.crateVersion) { + assertCrateRef(input.crateName, input.crateVersion); + } else if (input.crateName) { + assertCrateName(input.crateName); + } + const key = inputKey(input); + if (!uniqueInputs.has(key)) uniqueInputs.set(key, input); + } - const loaded = await Effect.runPromise( - Effect.forEach( - Array.from(uniqueInputs.entries()), - ([key, input]) => - Effect.tryPromise({ - try: async () => - [ - key, - await provider.loadSourceFile( - input.file, - input.crateName, - input.crateVersion, - input.sourceProvider, - ), - ] as const, - catch: (cause) => - new SourceLoadError({ - key, - cause, - message: `Failed to load source ${key}: ${unknownMessage(cause)}`, - }), - }), - { concurrency: 6 }, - ), - ); - const results = new Map(loaded); - return (_input, index) => - results.get(inputKey(inputs[index])) ?? { - error: 'Failed to fetch source', - content: null, - absolutePath: null, - repoUrl: null, - }; - }, + const loaded = await Effect.runPromise( + Effect.forEach( + Array.from(uniqueInputs.entries()), + ([key, input]) => + Effect.tryPromise({ + try: async () => + [ + key, + await provider.loadSourceFile( + input.file, + input.crateName, + input.crateVersion, + input.sourceProvider, + ), + ] as const, + catch: (cause) => + new SourceLoadError({ + key, + cause, + message: `Failed to load source ${key}: ${unknownMessage(cause)}`, + }), + }), + { concurrency: 6 }, + ), + ); + const results = new Map(loaded); + return (_input, index) => + results.get(inputKey(inputs[index])) ?? { + error: "Failed to fetch source", + content: null, + absolutePath: null, + repoUrl: null, + }; + }, ); diff --git a/codeview-ui/src/lib/schema.ts b/codeview-ui/src/lib/schema.ts index 382bc6d..96c1bcf 100644 --- a/codeview-ui/src/lib/schema.ts +++ b/codeview-ui/src/lib/schema.ts @@ -1,37 +1,37 @@ -import * as v from 'valibot'; +import * as v from "valibot"; import type { - ArgumentInfo, - AssocItemConstraint, - Confidence, - CrateGraph, - Deprecation, - Edge, - EdgeKind, - ExternalCrate, - FieldInfo, - FunctionPointerSig, - FunctionSignature, - GenericArg, - GenericArgs, - GenericBound, - GenericParam, - Generics, - ImplCategory, - ImplType, - Node, - NodeKind, - PolyTrait, - ProvidedDefaultUnstable, - Span, - StabilityInfo, - Term, - TypeRef, - VariantInfo, - VariantKind, - Visibility, - WherePredicate, - Workspace, -} from './generated/codeview-schema'; + ArgumentInfo, + AssocItemConstraint, + Confidence, + CrateGraph, + Deprecation, + Edge, + EdgeKind, + ExternalCrate, + FieldInfo, + FunctionPointerSig, + FunctionSignature, + GenericArg, + GenericArgs, + GenericBound, + GenericParam, + Generics, + ImplCategory, + ImplType, + Node, + NodeKind, + PolyTrait, + ProvidedDefaultUnstable, + Span, + StabilityInfo, + Term, + TypeRef, + VariantInfo, + VariantKind, + Visibility, + WherePredicate, + Workspace, +} from "./generated/codeview-schema"; /** Current graph schema version supported by this UI */ /** @@ -47,37 +47,37 @@ export const SCHEMA_VERSION = 1; // --- Enums --- export const NodeKindSchema = v.picklist([ - 'Crate', - 'Module', - 'Struct', - 'StructField', - 'Union', - 'Enum', - 'Variant', - 'Trait', - 'TraitAlias', - 'Impl', - 'Function', - 'TypeAlias', - 'AssocType', - 'Constant', - 'AssocConst', - 'Static', - 'Macro', - 'Primitive', - 'ExternCrate', - 'Import', - 'ProcMacro', + "Crate", + "Module", + "Struct", + "StructField", + "Union", + "Enum", + "Variant", + "Trait", + "TraitAlias", + "Impl", + "Function", + "TypeAlias", + "AssocType", + "Constant", + "AssocConst", + "Static", + "Macro", + "Primitive", + "ExternCrate", + "Import", + "ProcMacro", ]); -export const ImplTypeSchema = v.picklist(['Trait', 'Inherent']); +export const ImplTypeSchema = v.picklist(["Trait", "Inherent"]); export const ImplCategorySchema = v.picklist([ - 'Inherent', - 'Trait', - 'Blanket', - 'Negative', - 'Synthetic', + "Inherent", + "Trait", + "Blanket", + "Negative", + "Synthetic", ]); /** @@ -90,35 +90,35 @@ export const ImplCategorySchema = v.picklist([ * `Visibility` from codeview-schema.d.ts (verified by the * `_VisibilitySchemaMatchesGenerated` Assert below). */ -export const VisibilitySchema = v.variant('kind', [ - v.object({ kind: v.literal('Public') }), - v.object({ kind: v.literal('Crate') }), - v.object({ kind: v.literal('Restricted'), path: v.string() }), - v.object({ kind: v.literal('Inherited') }), - v.object({ kind: v.literal('Unknown') }), +export const VisibilitySchema = v.variant("kind", [ + v.object({ kind: v.literal("Public") }), + v.object({ kind: v.literal("Crate") }), + v.object({ kind: v.literal("Restricted"), path: v.string() }), + v.object({ kind: v.literal("Inherited") }), + v.object({ kind: v.literal("Unknown") }), ]); export const EdgeKindSchema = v.picklist([ - 'Contains', - 'Defines', - 'Implements', - 'UsesType', - 'CallsStatic', - 'CallsRuntime', - 'Derives', - 'ReExports', + "Contains", + "Defines", + "Implements", + "UsesType", + "CallsStatic", + "CallsRuntime", + "Derives", + "ReExports", ]); -export const ConfidenceSchema = v.picklist(['Static', 'Runtime', 'Inferred']); +export const ConfidenceSchema = v.picklist(["Static", "Runtime", "Inferred"]); // --- Nested structures --- export const SpanSchema = v.object({ - file: v.string(), - line: v.number(), - column: v.number(), - end_line: v.optional(v.nullable(v.number())), - end_column: v.optional(v.nullable(v.number())), + file: v.string(), + line: v.number(), + column: v.number(), + end_line: v.optional(v.nullable(v.number())), + end_column: v.optional(v.nullable(v.number())), }); // ─── Type AST (recursive) ──────────────────────────────────────────── @@ -127,586 +127,586 @@ export const SpanSchema = v.object({ // All tagged unions use `kind` discriminator. Recursion is fed through // `v.lazy()` so the runtime resolves the back-references at first use. -const TraitBoundModifierSchema = v.picklist(['none', 'maybe', 'maybe_const']); +const TraitBoundModifierSchema = v.picklist(["none", "maybe", "maybe_const"]); -const PreciseCaptureSchema = v.variant('kind', [ - v.object({ kind: v.literal('Lifetime'), name: v.string() }), - v.object({ kind: v.literal('Param'), name: v.string() }), +const PreciseCaptureSchema = v.variant("kind", [ + v.object({ kind: v.literal("Lifetime"), name: v.string() }), + v.object({ kind: v.literal("Param"), name: v.string() }), ]); export const TypeRefSchema: v.GenericSchema = v.lazy(() => - v.variant('kind', [ - v.object({ - kind: v.literal('ResolvedPath'), - id: v.string(), - path: v.string(), - args: v.optional(v.nullable(GenericArgsSchema)), - }), - v.object({ - kind: v.literal('DynTrait'), - traits: v.array(PolyTraitSchema), - lifetime: v.optional(v.nullable(v.string())), - }), - v.object({ kind: v.literal('Generic'), name: v.string() }), - v.object({ kind: v.literal('Primitive'), name: v.string() }), - v.object({ - kind: v.literal('BorrowedRef'), - lifetime: v.optional(v.nullable(v.string())), - mutable: v.boolean(), - inner: TypeRefSchema, - }), - v.object({ kind: v.literal('Tuple'), elements: v.array(TypeRefSchema) }), - v.object({ kind: v.literal('Slice'), element: TypeRefSchema }), - v.object({ kind: v.literal('Array'), element: TypeRefSchema, len: v.string() }), - v.object({ - kind: v.literal('ImplTrait'), - bounds: v.array(GenericBoundSchema), - }), - v.object({ - kind: v.literal('RawPointer'), - mutable: v.boolean(), - inner: TypeRefSchema, - }), - v.object({ - kind: v.literal('QualifiedPath'), - name: v.string(), - args: v.optional(v.nullable(GenericArgsSchema)), - self_type: TypeRefSchema, - trait: v.optional(v.nullable(TypeRefSchema)), - }), - v.object({ - kind: v.literal('FunctionPointer'), - sig: FunctionPointerSigSchema, - }), - v.object({ kind: v.literal('Infer') }), - v.object({ kind: v.literal('Pat'), base: TypeRefSchema, pat: v.string() }), - ]), + v.variant("kind", [ + v.object({ + kind: v.literal("ResolvedPath"), + id: v.string(), + path: v.string(), + args: v.optional(v.nullable(GenericArgsSchema)), + }), + v.object({ + kind: v.literal("DynTrait"), + traits: v.array(PolyTraitSchema), + lifetime: v.optional(v.nullable(v.string())), + }), + v.object({ kind: v.literal("Generic"), name: v.string() }), + v.object({ kind: v.literal("Primitive"), name: v.string() }), + v.object({ + kind: v.literal("BorrowedRef"), + lifetime: v.optional(v.nullable(v.string())), + mutable: v.boolean(), + inner: TypeRefSchema, + }), + v.object({ kind: v.literal("Tuple"), elements: v.array(TypeRefSchema) }), + v.object({ kind: v.literal("Slice"), element: TypeRefSchema }), + v.object({ kind: v.literal("Array"), element: TypeRefSchema, len: v.string() }), + v.object({ + kind: v.literal("ImplTrait"), + bounds: v.array(GenericBoundSchema), + }), + v.object({ + kind: v.literal("RawPointer"), + mutable: v.boolean(), + inner: TypeRefSchema, + }), + v.object({ + kind: v.literal("QualifiedPath"), + name: v.string(), + args: v.optional(v.nullable(GenericArgsSchema)), + self_type: TypeRefSchema, + trait: v.optional(v.nullable(TypeRefSchema)), + }), + v.object({ + kind: v.literal("FunctionPointer"), + sig: FunctionPointerSigSchema, + }), + v.object({ kind: v.literal("Infer") }), + v.object({ kind: v.literal("Pat"), base: TypeRefSchema, pat: v.string() }), + ]), ); const GenericArgsSchema: v.GenericSchema = v.lazy(() => - v.variant('kind', [ - v.object({ - kind: v.literal('AngleBracketed'), - args: v.array(GenericArgSchema), - constraints: v.optional(v.array(AssocItemConstraintSchema)), - }), - v.object({ - kind: v.literal('Parenthesized'), - inputs: v.array(TypeRefSchema), - output: v.optional(v.nullable(TypeRefSchema)), - }), - v.object({ kind: v.literal('ReturnTypeNotation') }), - ]), + v.variant("kind", [ + v.object({ + kind: v.literal("AngleBracketed"), + args: v.array(GenericArgSchema), + constraints: v.optional(v.array(AssocItemConstraintSchema)), + }), + v.object({ + kind: v.literal("Parenthesized"), + inputs: v.array(TypeRefSchema), + output: v.optional(v.nullable(TypeRefSchema)), + }), + v.object({ kind: v.literal("ReturnTypeNotation") }), + ]), ); const GenericArgSchema: v.GenericSchema = v.lazy(() => - v.variant('kind', [ - v.object({ kind: v.literal('Lifetime'), name: v.string() }), - v.object({ kind: v.literal('Type'), value: TypeRefSchema }), - v.object({ - kind: v.literal('Const'), - expr: v.string(), - is_literal: v.boolean(), - }), - v.object({ kind: v.literal('Infer') }), - ]), + v.variant("kind", [ + v.object({ kind: v.literal("Lifetime"), name: v.string() }), + v.object({ kind: v.literal("Type"), value: TypeRefSchema }), + v.object({ + kind: v.literal("Const"), + expr: v.string(), + is_literal: v.boolean(), + }), + v.object({ kind: v.literal("Infer") }), + ]), ); const TermSchema: v.GenericSchema = v.lazy(() => - v.variant('kind', [ - v.object({ kind: v.literal('Type'), value: TypeRefSchema }), - v.object({ - kind: v.literal('Const'), - expr: v.string(), - is_literal: v.boolean(), - }), - ]), + v.variant("kind", [ + v.object({ kind: v.literal("Type"), value: TypeRefSchema }), + v.object({ + kind: v.literal("Const"), + expr: v.string(), + is_literal: v.boolean(), + }), + ]), ); const AssocItemConstraintSchema: v.GenericSchema = v.lazy(() => - v.object({ - name: v.string(), - args: v.optional(v.nullable(GenericArgsSchema)), - binding: v.variant('kind', [ - v.object({ kind: v.literal('Equality'), value: TermSchema }), - v.object({ - kind: v.literal('Constraint'), - bounds: v.array(GenericBoundSchema), - }), - ]), - }), + v.object({ + name: v.string(), + args: v.optional(v.nullable(GenericArgsSchema)), + binding: v.variant("kind", [ + v.object({ kind: v.literal("Equality"), value: TermSchema }), + v.object({ + kind: v.literal("Constraint"), + bounds: v.array(GenericBoundSchema), + }), + ]), + }), ); const PolyTraitSchema: v.GenericSchema = v.lazy(() => - v.object({ - trait: TypeRefSchema, - hrtb_params: v.optional(v.array(GenericParamSchema)), - }), + v.object({ + trait: TypeRefSchema, + hrtb_params: v.optional(v.array(GenericParamSchema)), + }), ); const FunctionPointerSigSchema: v.GenericSchema = v.lazy(() => - v.object({ - inputs: v.array(v.object({ name: v.string(), type: TypeRefSchema })), - output: v.optional(v.nullable(TypeRefSchema)), - is_unsafe: v.boolean(), - is_const: v.boolean(), - is_async: v.boolean(), - abi: v.optional(v.nullable(v.string())), - is_c_variadic: v.boolean(), - hrtb_params: v.optional(v.array(GenericParamSchema)), - }), + v.object({ + inputs: v.array(v.object({ name: v.string(), type: TypeRefSchema })), + output: v.optional(v.nullable(TypeRefSchema)), + is_unsafe: v.boolean(), + is_const: v.boolean(), + is_async: v.boolean(), + abi: v.optional(v.nullable(v.string())), + is_c_variadic: v.boolean(), + hrtb_params: v.optional(v.array(GenericParamSchema)), + }), ); const GenericBoundSchema: v.GenericSchema = v.lazy(() => - v.variant('kind', [ - v.object({ - kind: v.literal('Trait'), - trait: TypeRefSchema, - modifier: TraitBoundModifierSchema, - hrtb_params: v.optional(v.array(GenericParamSchema)), - }), - v.object({ kind: v.literal('Outlives'), lifetime: v.string() }), - v.object({ - kind: v.literal('Use'), - captures: v.array(PreciseCaptureSchema), - }), - ]), + v.variant("kind", [ + v.object({ + kind: v.literal("Trait"), + trait: TypeRefSchema, + modifier: TraitBoundModifierSchema, + hrtb_params: v.optional(v.array(GenericParamSchema)), + }), + v.object({ kind: v.literal("Outlives"), lifetime: v.string() }), + v.object({ + kind: v.literal("Use"), + captures: v.array(PreciseCaptureSchema), + }), + ]), ); const GenericParamSchema: v.GenericSchema = v.lazy(() => - v.object({ - name: v.string(), - kind: v.variant('kind', [ - v.object({ - kind: v.literal('Lifetime'), - outlives: v.optional(v.array(v.string())), - }), - v.object({ - kind: v.literal('Type'), - bounds: v.optional(v.array(GenericBoundSchema)), - default: v.optional(v.nullable(TypeRefSchema)), - synthetic: v.optional(v.boolean()), - }), - v.object({ - kind: v.literal('Const'), - type: TypeRefSchema, - default: v.optional(v.nullable(v.string())), - }), - ]), - }), + v.object({ + name: v.string(), + kind: v.variant("kind", [ + v.object({ + kind: v.literal("Lifetime"), + outlives: v.optional(v.array(v.string())), + }), + v.object({ + kind: v.literal("Type"), + bounds: v.optional(v.array(GenericBoundSchema)), + default: v.optional(v.nullable(TypeRefSchema)), + synthetic: v.optional(v.boolean()), + }), + v.object({ + kind: v.literal("Const"), + type: TypeRefSchema, + default: v.optional(v.nullable(v.string())), + }), + ]), + }), ); const WherePredicateSchema: v.GenericSchema = v.lazy(() => - v.variant('kind', [ - v.object({ - kind: v.literal('Bound'), - type: TypeRefSchema, - bounds: v.array(GenericBoundSchema), - hrtb_params: v.optional(v.array(GenericParamSchema)), - }), - v.object({ - kind: v.literal('Lifetime'), - lifetime: v.string(), - outlives: v.array(v.string()), - }), - v.object({ - kind: v.literal('Eq'), - lhs: TypeRefSchema, - rhs: TermSchema, - }), - ]), + v.variant("kind", [ + v.object({ + kind: v.literal("Bound"), + type: TypeRefSchema, + bounds: v.array(GenericBoundSchema), + hrtb_params: v.optional(v.array(GenericParamSchema)), + }), + v.object({ + kind: v.literal("Lifetime"), + lifetime: v.string(), + outlives: v.array(v.string()), + }), + v.object({ + kind: v.literal("Eq"), + lhs: TypeRefSchema, + rhs: TermSchema, + }), + ]), ); export const GenericsSchema = v.object({ - params: v.optional(v.array(GenericParamSchema)), - where_predicates: v.optional(v.array(WherePredicateSchema)), + params: v.optional(v.array(GenericParamSchema)), + where_predicates: v.optional(v.array(WherePredicateSchema)), }); export const FieldInfoSchema = v.object({ - name: v.string(), - type: TypeRefSchema, - visibility: VisibilitySchema, + name: v.string(), + type: TypeRefSchema, + visibility: VisibilitySchema, }); export const VariantInfoSchema = v.object({ - name: v.string(), - fields: v.array(FieldInfoSchema), + name: v.string(), + fields: v.array(FieldInfoSchema), }); export const ArgumentInfoSchema = v.object({ - name: v.string(), - type: TypeRefSchema, + name: v.string(), + type: TypeRefSchema, }); export const FunctionSignatureSchema = v.object({ - inputs: v.array(ArgumentInfoSchema), - output: v.optional(v.nullable(TypeRefSchema)), - is_async: v.boolean(), - is_unsafe: v.boolean(), - is_const: v.boolean(), - abi: v.optional(v.nullable(v.string())), - is_c_variadic: v.optional(v.boolean()), - generics: v.optional(GenericsSchema), + inputs: v.array(ArgumentInfoSchema), + output: v.optional(v.nullable(TypeRefSchema)), + is_async: v.boolean(), + is_unsafe: v.boolean(), + is_const: v.boolean(), + abi: v.optional(v.nullable(v.string())), + is_c_variadic: v.optional(v.boolean()), + generics: v.optional(GenericsSchema), }); export const DeprecationSchema = v.object({ - since: v.optional(v.nullable(v.string())), - note: v.optional(v.nullable(v.string())), + since: v.optional(v.nullable(v.string())), + note: v.optional(v.nullable(v.string())), }); export const StabilityInfoSchema = v.intersect([ - v.object({ - feature: v.string(), - }), - v.variant('level', [ - v.object({ - level: v.literal('stable'), - since: v.optional(v.nullable(v.string())), - }), - v.object({ - level: v.literal('unstable'), - }), - ]), + v.object({ + feature: v.string(), + }), + v.variant("level", [ + v.object({ + level: v.literal("stable"), + since: v.optional(v.nullable(v.string())), + }), + v.object({ + level: v.literal("unstable"), + }), + ]), ]); export const ProvidedDefaultUnstableSchema = v.object({ - feature: v.string(), + feature: v.string(), }); // --- Node & Edge --- export const NodeSchema = v.object({ - id: v.string(), - name: v.string(), - kind: NodeKindSchema, - visibility: VisibilitySchema, - span: v.optional(v.nullable(SpanSchema)), - line_count: v.optional(v.nullable(v.number())), - attrs: v.array(v.string()), - is_external: v.optional(v.boolean()), - is_deprecated: v.optional(v.boolean()), - is_unsafe: v.optional(v.boolean()), - is_auto: v.optional(v.boolean()), - is_mutable: v.optional(v.boolean()), - is_stripped: v.optional(v.boolean()), - has_stripped_fields: v.optional(v.boolean()), - has_stripped_variants: v.optional(v.boolean()), - is_dyn_compatible: v.optional(v.nullable(v.boolean())), - deprecation: v.optional(v.nullable(DeprecationSchema)), - stability: v.optional(v.nullable(StabilityInfoSchema)), - const_stability: v.optional(v.nullable(StabilityInfoSchema)), - default_unstable: v.optional(v.nullable(ProvidedDefaultUnstableSchema)), - fields: v.optional(v.nullable(v.array(FieldInfoSchema))), - variants: v.optional(v.nullable(v.array(VariantInfoSchema))), - signature: v.optional(v.nullable(FunctionSignatureSchema)), - // Structured generics (params + where-clause). - generics: v.optional(GenericsSchema), - docs: v.optional(v.nullable(v.string())), - doc_links: v.optional(v.record(v.string(), v.string())), - impl_type: v.optional(v.nullable(ImplTypeSchema)), - impl_category: v.optional(v.nullable(ImplCategorySchema)), - parent_impl: v.optional(v.nullable(v.string())), - impl_trait: v.optional(v.nullable(v.string())), - provided_trait_methods: v.optional(v.nullable(v.array(v.string()))), - required_trait_methods: v.optional(v.nullable(v.array(v.string()))), - default_trait_methods: v.optional(v.nullable(v.array(v.string()))), - // StructField / AssocType / AssocConst / Constant / Static / TypeAlias: the type - type: v.optional(v.nullable(TypeRefSchema)), - // Variant: unit, tuple, or struct - variant_kind: v.optional(v.nullable(v.picklist(['unit', 'tuple', 'struct']))), - // Variant: discriminant value if specified - discriminant: v.optional(v.nullable(v.string())), - // AssocConst: the constant's value expression - const_value: v.optional(v.nullable(v.string())), - // Trait / TraitAlias / AssocType bounds (structured) - bounds: v.optional(v.array(GenericBoundSchema)), - // Import / extern crate / macro metadata preserved from rustdoc JSON - import_source: v.optional(v.nullable(v.string())), - import_name: v.optional(v.nullable(v.string())), - is_glob: v.optional(v.boolean()), - extern_crate_name: v.optional(v.nullable(v.string())), - extern_crate_rename: v.optional(v.nullable(v.string())), - macro_source: v.optional(v.nullable(v.string())), - proc_macro_kind: v.optional(v.nullable(v.string())), - proc_macro_helpers: v.optional(v.array(v.string())), + id: v.string(), + name: v.string(), + kind: NodeKindSchema, + visibility: VisibilitySchema, + span: v.optional(v.nullable(SpanSchema)), + line_count: v.optional(v.nullable(v.number())), + attrs: v.array(v.string()), + is_external: v.optional(v.boolean()), + is_deprecated: v.optional(v.boolean()), + is_unsafe: v.optional(v.boolean()), + is_auto: v.optional(v.boolean()), + is_mutable: v.optional(v.boolean()), + is_stripped: v.optional(v.boolean()), + has_stripped_fields: v.optional(v.boolean()), + has_stripped_variants: v.optional(v.boolean()), + is_dyn_compatible: v.optional(v.nullable(v.boolean())), + deprecation: v.optional(v.nullable(DeprecationSchema)), + stability: v.optional(v.nullable(StabilityInfoSchema)), + const_stability: v.optional(v.nullable(StabilityInfoSchema)), + default_unstable: v.optional(v.nullable(ProvidedDefaultUnstableSchema)), + fields: v.optional(v.nullable(v.array(FieldInfoSchema))), + variants: v.optional(v.nullable(v.array(VariantInfoSchema))), + signature: v.optional(v.nullable(FunctionSignatureSchema)), + // Structured generics (params + where-clause). + generics: v.optional(GenericsSchema), + docs: v.optional(v.nullable(v.string())), + doc_links: v.optional(v.record(v.string(), v.string())), + impl_type: v.optional(v.nullable(ImplTypeSchema)), + impl_category: v.optional(v.nullable(ImplCategorySchema)), + parent_impl: v.optional(v.nullable(v.string())), + impl_trait: v.optional(v.nullable(v.string())), + provided_trait_methods: v.optional(v.nullable(v.array(v.string()))), + required_trait_methods: v.optional(v.nullable(v.array(v.string()))), + default_trait_methods: v.optional(v.nullable(v.array(v.string()))), + // StructField / AssocType / AssocConst / Constant / Static / TypeAlias: the type + type: v.optional(v.nullable(TypeRefSchema)), + // Variant: unit, tuple, or struct + variant_kind: v.optional(v.nullable(v.picklist(["unit", "tuple", "struct"]))), + // Variant: discriminant value if specified + discriminant: v.optional(v.nullable(v.string())), + // AssocConst: the constant's value expression + const_value: v.optional(v.nullable(v.string())), + // Trait / TraitAlias / AssocType bounds (structured) + bounds: v.optional(v.array(GenericBoundSchema)), + // Import / extern crate / macro metadata preserved from rustdoc JSON + import_source: v.optional(v.nullable(v.string())), + import_name: v.optional(v.nullable(v.string())), + is_glob: v.optional(v.boolean()), + extern_crate_name: v.optional(v.nullable(v.string())), + extern_crate_rename: v.optional(v.nullable(v.string())), + macro_source: v.optional(v.nullable(v.string())), + proc_macro_kind: v.optional(v.nullable(v.string())), + proc_macro_helpers: v.optional(v.array(v.string())), }); export const EdgeSchema = v.object({ - from: v.string(), - to: v.string(), - kind: EdgeKindSchema, - confidence: ConfidenceSchema, - occurrences: v.optional(v.array(SpanSchema)), - is_glob: v.optional(v.boolean()), + from: v.string(), + to: v.string(), + kind: EdgeKindSchema, + confidence: ConfidenceSchema, + occurrences: v.optional(v.array(SpanSchema)), + is_glob: v.optional(v.boolean()), }); // --- Per-crate graph --- export const CrateGraphSchema = v.object({ - id: v.string(), - name: v.string(), - version: v.string(), - nodes: v.array(NodeSchema), - edges: v.array(EdgeSchema), - // public_path → canonical_node_id; skipped in JSON when empty (matches - // `#[serde(skip_serializing_if = "HashMap::is_empty")]` on the Rust side). - aliases: v.optional(v.record(v.string(), v.string())), + id: v.string(), + name: v.string(), + version: v.string(), + nodes: v.array(NodeSchema), + edges: v.array(EdgeSchema), + // public_path → canonical_node_id; skipped in JSON when empty (matches + // `#[serde(skip_serializing_if = "HashMap::is_empty")]` on the Rust side). + aliases: v.optional(v.record(v.string(), v.string())), }); export const ExternalCrateSchema = v.object({ - id: v.string(), - name: v.string(), - version: v.optional(v.nullable(v.string())), - nodes: v.array(NodeSchema), + id: v.string(), + name: v.string(), + version: v.optional(v.nullable(v.string())), + nodes: v.array(NodeSchema), }); // --- Top-level Workspace --- export const WorkspaceSchema = v.object({ - version: v.optional(v.number()), - crates: v.array(CrateGraphSchema), - external_crates: v.array(ExternalCrateSchema), - cross_crate_edges: v.array(EdgeSchema), - repo: v.optional(v.nullable(v.string())), - ref: v.optional(v.nullable(v.string())), + version: v.optional(v.number()), + crates: v.array(CrateGraphSchema), + external_crates: v.array(ExternalCrateSchema), + cross_crate_edges: v.array(EdgeSchema), + repo: v.optional(v.nullable(v.string())), + ref: v.optional(v.nullable(v.string())), }); // --- Response schemas --- /** Lightweight node summary for tree/list display */ export const NodeSummarySchema = v.object({ - id: v.string(), - name: v.string(), - kind: NodeKindSchema, - visibility: VisibilitySchema, - is_external: v.optional(v.boolean()), - is_deprecated: v.optional(v.boolean()), - // Impl-specific fields (only populated for Impl nodes) - impl_trait: v.optional(v.nullable(v.string())), - impl_category: v.optional(v.nullable(ImplCategorySchema)), - generics: v.optional(GenericsSchema), + id: v.string(), + name: v.string(), + kind: NodeKindSchema, + visibility: VisibilitySchema, + is_external: v.optional(v.boolean()), + is_deprecated: v.optional(v.boolean()), + // Impl-specific fields (only populated for Impl nodes) + impl_trait: v.optional(v.nullable(v.string())), + impl_category: v.optional(v.nullable(ImplCategorySchema)), + generics: v.optional(GenericsSchema), }); /** getCrates response item */ export const CrateSummarySchema = v.object({ - id: v.string(), - name: v.string(), - version: v.string(), + id: v.string(), + name: v.string(), + version: v.string(), }); /** Lightweight crate index entry (for hosted pseudo-workspace) */ export const CrateIndexEntrySchema = v.object({ - id: v.string(), - name: v.string(), - version: v.string(), - is_external: v.optional(v.boolean()), + id: v.string(), + name: v.string(), + version: v.string(), + is_external: v.optional(v.boolean()), }); /** Per-crate hosted index response */ export const CrateIndexSchema = v.object({ - name: v.string(), - version: v.string(), - crates: v.array(CrateIndexEntrySchema), + name: v.string(), + version: v.string(), + crates: v.array(CrateIndexEntrySchema), }); /** getCrateTree response */ export const CrateTreeSchema = v.object({ - nodes: v.array(NodeSummarySchema), - edges: v.array(EdgeSchema), + nodes: v.array(NodeSummarySchema), + edges: v.array(EdgeSchema), }); /** getNodeDetail response */ export const NodeDetailSchema = v.object({ - node: NodeSchema, - edges: v.array(EdgeSchema), - relatedNodes: v.array(NodeSchema), + node: NodeSchema, + edges: v.array(EdgeSchema), + relatedNodes: v.array(NodeSchema), }); /** getSource response */ export const SourceResultSchema = v.object({ - error: v.nullable(v.string()), - content: v.nullable(v.string()), - absolutePath: v.nullable(v.string()), - repoUrl: v.nullable(v.string()), + error: v.nullable(v.string()), + content: v.nullable(v.string()), + absolutePath: v.nullable(v.string()), + repoUrl: v.nullable(v.string()), }); // --- Crate status (for cloud multi-crate mode) --- -export const CrateStatusValueSchema = v.picklist(['unknown', 'processing', 'ready', 'failed']); +export const CrateStatusValueSchema = v.picklist(["unknown", "processing", "ready", "failed"]); export const CrateStatusSchema = v.object({ - status: CrateStatusValueSchema, - error: v.optional(v.string()), - step: v.optional(v.string()), - action: v.optional(v.picklist(['install_std_docs', 'docs_unavailable'])), - installedVersion: v.optional(v.string()), + status: CrateStatusValueSchema, + error: v.optional(v.string()), + step: v.optional(v.string()), + action: v.optional(v.picklist(["install_std_docs", "docs_unavailable"])), + installedVersion: v.optional(v.string()), }); export const CrateSearchResultSchema = v.object({ - id: v.optional(v.string()), - name: v.string(), - version: v.string(), - description: v.optional(v.string()), + id: v.optional(v.string()), + name: v.string(), + version: v.string(), + description: v.optional(v.string()), }); // --- Types --- type IsEqual = - (() => T extends Actual ? 1 : 2) extends () => T extends Expected ? 1 : 2 - ? (() => T extends Expected ? 1 : 2) extends () => T extends Actual ? 1 : 2 - ? true - : false - : false; + (() => T extends Actual ? 1 : 2) extends () => T extends Expected ? 1 : 2 + ? (() => T extends Expected ? 1 : 2) extends () => T extends Actual ? 1 : 2 + ? true + : false + : false; type Assert = T; type _ConfidenceSchemaMatchesGenerated = Assert< - IsEqual, Confidence> + IsEqual, Confidence> >; type _CrateGraphSchemaMatchesGenerated = Assert< - IsEqual, CrateGraph> + IsEqual, CrateGraph> >; type _DeprecationSchemaMatchesGenerated = Assert< - IsEqual, Deprecation> + IsEqual, Deprecation> >; type _EdgeKindSchemaMatchesGenerated = Assert< - IsEqual, EdgeKind> + IsEqual, EdgeKind> >; type _EdgeSchemaMatchesGenerated = Assert, Edge>>; type _ExternalCrateSchemaMatchesGenerated = Assert< - IsEqual, ExternalCrate> + IsEqual, ExternalCrate> >; type _FieldInfoSchemaMatchesGenerated = Assert< - IsEqual, FieldInfo> + IsEqual, FieldInfo> >; type _FunctionSignatureSchemaMatchesGenerated = Assert< - IsEqual, FunctionSignature> + IsEqual, FunctionSignature> >; type _ImplCategorySchemaMatchesGenerated = Assert< - IsEqual, ImplCategory> + IsEqual, ImplCategory> >; type _ImplTypeSchemaMatchesGenerated = Assert< - IsEqual, ImplType> + IsEqual, ImplType> >; type _NodeKindSchemaMatchesGenerated = Assert< - IsEqual, NodeKind> + IsEqual, NodeKind> >; type _NodeSchemaMatchesGenerated = Assert, Node>>; type _ProvidedDefaultUnstableSchemaMatchesGenerated = Assert< - IsEqual, ProvidedDefaultUnstable> + IsEqual, ProvidedDefaultUnstable> >; type _SpanSchemaMatchesGenerated = Assert, Span>>; type _StabilityInfoSchemaMatchesGenerated = Assert< - IsEqual, StabilityInfo> + IsEqual, StabilityInfo> >; type _VariantInfoSchemaMatchesGenerated = Assert< - IsEqual, VariantInfo> + IsEqual, VariantInfo> >; type _VisibilitySchemaMatchesGenerated = Assert< - IsEqual, Visibility> + IsEqual, Visibility> >; type _WorkspaceSchemaMatchesGenerated = Assert< - IsEqual, Workspace> + IsEqual, Workspace> >; export type { - ArgumentInfo, - AssocItemConstraint, - Confidence, - CrateGraph, - Deprecation, - Edge, - EdgeKind, - ExternalCrate, - FieldInfo, - FunctionPointerSig, - FunctionSignature, - GenericArg, - GenericArgs, - GenericBound, - GenericParam, - Generics, - ImplCategory, - ImplType, - Node, - NodeKind, - PolyTrait, - ProvidedDefaultUnstable, - Span, - StabilityInfo, - Term, - TypeRef, - VariantInfo, - VariantKind, - Visibility, - WherePredicate, - Workspace, + ArgumentInfo, + AssocItemConstraint, + Confidence, + CrateGraph, + Deprecation, + Edge, + EdgeKind, + ExternalCrate, + FieldInfo, + FunctionPointerSig, + FunctionSignature, + GenericArg, + GenericArgs, + GenericBound, + GenericParam, + Generics, + ImplCategory, + ImplType, + Node, + NodeKind, + PolyTrait, + ProvidedDefaultUnstable, + Span, + StabilityInfo, + Term, + TypeRef, + VariantInfo, + VariantKind, + Visibility, + WherePredicate, + Workspace, }; export type WorkspaceOutput = Workspace; export type NodeSummary = Pick< - Node, - | 'id' - | 'name' - | 'kind' - | 'visibility' - | 'is_external' - | 'is_deprecated' - | 'impl_trait' - | 'impl_category' - | 'generics' + Node, + | "id" + | "name" + | "kind" + | "visibility" + | "is_external" + | "is_deprecated" + | "impl_trait" + | "impl_category" + | "generics" >; export type CrateSummary = v.InferOutput; export type CrateIndexEntry = v.InferOutput; export type CrateIndex = v.InferOutput; export type CrateTree = { - nodes: NodeSummary[]; - edges: Edge[]; + nodes: NodeSummary[]; + edges: Edge[]; }; export type NodeDetail = { - node: Node; - edges: Edge[]; - relatedNodes: Node[]; + node: Node; + edges: Edge[]; + relatedNodes: Node[]; }; export type SelectedEdges = { incoming: Edge[]; outgoing: Edge[] }; export type DetailMethodGroup = { implId: string; methodIds: string[] }; export type TocEntry = { anchor: string; title: string; count: number | null }; export type WhereUsedRef = { id: string; name: string }; export type DetailDocModel = { - selectedEdges: SelectedEdges; - filteredEdges: SelectedEdges; - relatedNodeIds: string[]; - implBlockIds: string[]; - sourceImplIds: string[]; - blanketImplIds: string[]; - methodGroups: DetailMethodGroup[]; - traitImplGroups: DetailMethodGroup[]; - requiredTraitMethodIds: string[]; - providedTraitMethodIds: string[]; - traitAssocItemIds: string[]; - methodCount: number; - totalImpls: number; - tocEntries: TocEntry[]; - whereUsed: WhereUsedRef[]; + selectedEdges: SelectedEdges; + filteredEdges: SelectedEdges; + relatedNodeIds: string[]; + implBlockIds: string[]; + sourceImplIds: string[]; + blanketImplIds: string[]; + methodGroups: DetailMethodGroup[]; + traitImplGroups: DetailMethodGroup[]; + requiredTraitMethodIds: string[]; + providedTraitMethodIds: string[]; + traitAssocItemIds: string[]; + methodCount: number; + totalImpls: number; + tocEntries: TocEntry[]; + whereUsed: WhereUsedRef[]; }; export type DesignRelation = - | 'contains' - | 'reexports' - | 'defines' - | 'implements' - | 'uses' - | 'calls' - | 'calls-runtime' - | 'derives'; + | "contains" + | "reexports" + | "defines" + | "implements" + | "uses" + | "calls" + | "calls-runtime" + | "derives"; export type RelationshipGroupItem = { node: NodeSummary; count: number }; export type RelationshipGroup = { - rel: DesignRelation; - label: string; - color: string; - items: RelationshipGroupItem[]; + rel: DesignRelation; + label: string; + color: string; + items: RelationshipGroupItem[]; }; export type RelationshipGroups = { - incoming: RelationshipGroup[]; - outgoing: RelationshipGroup[]; + incoming: RelationshipGroup[]; + outgoing: RelationshipGroup[]; }; export type SourceResult = v.InferOutput; export type CrateStatus = v.InferOutput; @@ -714,139 +714,139 @@ export type CrateSearchResult = v.InferOutput; /** Combined response from getCrateData (tree + index + versions in one call). */ export type CrateData = { - tree: CrateTree; - index: CrateIndex | null; - versions: string[]; + tree: CrateTree; + index: CrateIndex | null; + versions: string[]; }; /** A tree node with a hasChildren flag — used by lazy tree endpoints. */ export const TreeNodeDTOSchema = v.object({ - node: NodeSummarySchema, - hasChildren: v.boolean(), + node: NodeSummarySchema, + hasChildren: v.boolean(), }); export type TreeNodeDTO = v.InferOutput; export const STATIC_ARTIFACT_SCHEMA_VERSION = 2; export const StaticCrateManifestSchema = v.object({ - schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), - name: v.string(), - version: v.string(), - index: CrateIndexSchema, - nodeCount: v.number(), - edgeCount: v.number(), - kindCounts: v.record(v.string(), v.number()), - roots: v.array(TreeNodeDTOSchema), - rootChildren: v.record(v.string(), v.array(TreeNodeDTOSchema)), - /** - * Lists of populated shard buckets per kind (hex strings like `"00f"`). - * Worker reads these before issuing a shard GET to skip empty buckets. - */ - populatedShards: v.object({ - nodes: v.array(v.string()), - nodeDetails: v.array(v.string()), - treeChildren: v.array(v.string()), - }), + schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), + name: v.string(), + version: v.string(), + index: CrateIndexSchema, + nodeCount: v.number(), + edgeCount: v.number(), + kindCounts: v.record(v.string(), v.number()), + roots: v.array(TreeNodeDTOSchema), + rootChildren: v.record(v.string(), v.array(TreeNodeDTOSchema)), + /** + * Lists of populated shard buckets per kind (hex strings like `"00f"`). + * Worker reads these before issuing a shard GET to skip empty buckets. + */ + populatedShards: v.object({ + nodes: v.array(v.string()), + nodeDetails: v.array(v.string()), + treeChildren: v.array(v.string()), + }), }); export type StaticCrateManifest = v.InferOutput; export const StaticCrateCatalogEntrySchema = v.object({ - name: v.string(), - version: v.string(), - storageName: v.optional(v.string()), - source: v.optional(v.picklist(['std', 'crates.io'])), - description: v.optional(v.string()), - nodeCount: v.optional(v.number()), - edgeCount: v.optional(v.number()), + name: v.string(), + version: v.string(), + storageName: v.optional(v.string()), + source: v.optional(v.picklist(["std", "crates.io"])), + description: v.optional(v.string()), + nodeCount: v.optional(v.number()), + edgeCount: v.optional(v.number()), }); export type StaticCrateCatalogEntry = v.InferOutput; export const StaticCrateCatalogSchema = v.object({ - schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), - generatedAt: v.optional(v.string()), - crates: v.array(StaticCrateCatalogEntrySchema), + schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), + generatedAt: v.optional(v.string()), + crates: v.array(StaticCrateCatalogEntrySchema), }); export type StaticCrateCatalog = v.InferOutput; export const StaticTreeChildrenShardSchema = v.object({ - schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), - name: v.string(), - version: v.string(), - bucket: v.string(), - parents: v.record( - v.string(), - v.object({ - parent: NodeSummarySchema, - children: v.array(TreeNodeDTOSchema), - }), - ), + schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), + name: v.string(), + version: v.string(), + bucket: v.string(), + parents: v.record( + v.string(), + v.object({ + parent: NodeSummarySchema, + children: v.array(TreeNodeDTOSchema), + }), + ), }); export type StaticTreeChildrenShard = v.InferOutput; export const StaticSearchShardSchema = v.object({ - schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), - name: v.string(), - version: v.string(), - prefix: v.string(), - entries: v.array(NodeSummarySchema), + schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), + name: v.string(), + version: v.string(), + prefix: v.string(), + entries: v.array(NodeSummarySchema), }); export type StaticSearchShard = v.InferOutput; export const StaticSearchManifestSchema = v.object({ - schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), - name: v.string(), - version: v.string(), - prefixes: v.array(v.string()), + schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), + name: v.string(), + version: v.string(), + prefixes: v.array(v.string()), }); export type StaticSearchManifest = v.InferOutput; /** Lightweight crate metadata: index + versions + kind counts (no tree nodes). */ export const KindFacetSchema = v.object({ - kind: NodeKindSchema, - label: v.string(), - count: v.number(), + kind: NodeKindSchema, + label: v.string(), + count: v.number(), }); export type KindFacet = v.InferOutput; export const CrateMetaSchema = v.object({ - index: v.nullable(CrateIndexSchema), - versions: v.array(v.string()), - kindCounts: v.record(NodeKindSchema, v.number()), - kindFacets: v.array(KindFacetSchema), + index: v.nullable(CrateIndexSchema), + versions: v.array(v.string()), + kindCounts: v.record(NodeKindSchema, v.number()), + kindFacets: v.array(KindFacetSchema), }); export type CrateMeta = v.InferOutput; /** Canonical per-node response shared by hosted artifacts and RPCs. */ export const NodeViewSchema = v.object({ - detail: NodeDetailSchema, - ancestors: v.array(NodeSummarySchema), + detail: NodeDetailSchema, + ancestors: v.array(NodeSummarySchema), }); export type NodeView = v.InferOutput; export type NodeViewBase = NodeView; export const StaticNodeShardSchema = v.object({ - schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), - name: v.string(), - version: v.string(), - bucket: v.string(), - nodes: v.record(v.string(), NodeSchema), + schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), + name: v.string(), + version: v.string(), + bucket: v.string(), + nodes: v.record(v.string(), NodeSchema), }); export type StaticNodeShard = v.InferOutput; export const StaticNodeDetailEntrySchema = v.object({ - nodeId: v.string(), - edges: v.array(EdgeSchema), - relatedIds: v.array(v.string()), - ancestors: v.array(NodeSummarySchema), + nodeId: v.string(), + edges: v.array(EdgeSchema), + relatedIds: v.array(v.string()), + ancestors: v.array(NodeSummarySchema), }); export type StaticNodeDetailEntry = v.InferOutput; export const StaticNodeDetailShardSchema = v.object({ - schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), - name: v.string(), - version: v.string(), - bucket: v.string(), - details: v.record(v.string(), StaticNodeDetailEntrySchema), + schema_version: v.literal(STATIC_ARTIFACT_SCHEMA_VERSION), + name: v.string(), + version: v.string(), + bucket: v.string(), + details: v.record(v.string(), StaticNodeDetailEntrySchema), }); export type StaticNodeDetailShard = v.InferOutput; @@ -855,5 +855,5 @@ export type StaticNodeDetailShard = v.InferOutput { - const auth = createAuth(event); - if (!auth) return new Response('GitHub OAuth is not configured', { status: 503 }); - return auth.handler(event.request); + const auth = createAuth(event); + if (!auth) return new Response("GitHub OAuth is not configured", { status: 503 }); + return auth.handler(event.request); } export async function getAuthState(event: RequestEvent): Promise { - const env = authEnv(event); - const adminAllowlistConfigured = parseLoginAllowlist(env.GITHUB_ADMIN_LOGINS).size > 0; - const auth = createAuth(event); - if (!auth) { - return { - user: null, - session: null, - isAdmin: false, - authConfigured: false, - adminAllowlistConfigured, - }; - } - - const response = await auth.api - .getSession({ headers: event.request.headers }) - .catch(() => null); - const user = normalizeUser(response?.user); - return { - user, - session: normalizeSession(response?.session), - isAdmin: isAdminUser(user, env), - authConfigured: true, - adminAllowlistConfigured, - }; + const env = authEnv(event); + const adminAllowlistConfigured = parseLoginAllowlist(env.GITHUB_ADMIN_LOGINS).size > 0; + const auth = createAuth(event); + if (!auth) { + return { + user: null, + session: null, + isAdmin: false, + authConfigured: false, + adminAllowlistConfigured, + }; + } + + const response = await auth.api.getSession({ headers: event.request.headers }).catch(() => null); + const user = normalizeUser(response?.user); + return { + user, + session: normalizeSession(response?.session), + isAdmin: isAdminUser(user, env), + authConfigured: true, + adminAllowlistConfigured, + }; } -export async function getAuthStateFromRequest( - request: Request, - env: AuthEnv, -): Promise { - const adminAllowlistConfigured = parseLoginAllowlist(env.GITHUB_ADMIN_LOGINS).size > 0; - if (!isAuthConfigured(env)) { - return { - user: null, - session: null, - isAdmin: false, - authConfigured: false, - adminAllowlistConfigured, - }; - } - - const auth = betterAuth(authOptions(env)); - const response = await auth.api.getSession({ headers: request.headers }).catch(() => null); - const user = normalizeUser(response?.user); - return { - user, - session: normalizeSession(response?.session), - isAdmin: isAdminUser(user, env), - authConfigured: true, - adminAllowlistConfigured, - }; +export async function getAuthStateFromRequest(request: Request, env: AuthEnv): Promise { + const adminAllowlistConfigured = parseLoginAllowlist(env.GITHUB_ADMIN_LOGINS).size > 0; + if (!isAuthConfigured(env)) { + return { + user: null, + session: null, + isAdmin: false, + authConfigured: false, + adminAllowlistConfigured, + }; + } + + const auth = betterAuth(authOptions(env)); + const response = await auth.api.getSession({ headers: request.headers }).catch(() => null); + const user = normalizeUser(response?.user); + return { + user, + session: normalizeSession(response?.session), + isAdmin: isAdminUser(user, env), + authConfigured: true, + adminAllowlistConfigured, + }; } export function actorFromUser(user: AuthUser | null): ParseRequestActor | undefined { - if (!user?.githubLogin) return undefined; - return { - provider: 'github', - id: user.id, - login: user.githubLogin, - avatarUrl: user.image ?? undefined, - }; + if (!user?.githubLogin) return undefined; + return { + provider: "github", + id: user.id, + login: user.githubLogin, + avatarUrl: user.image ?? undefined, + }; } export function isAdminUser(user: AuthUser | null, env: AuthEnv): boolean { - const login = user?.githubLogin?.trim().toLowerCase(); - if (!login) return false; - return parseLoginAllowlist(env.GITHUB_ADMIN_LOGINS).has(login); + const login = user?.githubLogin?.trim().toLowerCase(); + if (!login) return false; + return parseLoginAllowlist(env.GITHUB_ADMIN_LOGINS).has(login); } function authOptions(env: AuthEnv) { - const db = drizzle(env.AUTH_DB!, { relations: authRelations }); - return { - baseURL: env.BETTER_AUTH_URL, - secret: env.BETTER_AUTH_SECRET, - database: drizzleAdapter(db, { - provider: 'sqlite', - schema: authTables, - }), - user: { - additionalFields: { - githubLogin: githubLoginField, - }, - }, - account: { - accountLinking: { - trustedProviders: ['github'], - }, - }, - socialProviders: { - github: { - clientId: env.GITHUB_OAUTH_CLIENT_ID!, - clientSecret: env.GITHUB_OAUTH_CLIENT_SECRET!, - overrideUserInfoOnSignIn: true, - mapProfileToUser: (profile: { login?: string }) => ({ - githubLogin: profile.login, - }), - }, - }, - advanced: { - ipAddress: { - ipAddressHeaders: ['cf-connecting-ip', 'x-forwarded-for'], - }, - }, - plugins: [sveltekitCookies(getRequestEvent)], - }; + const db = drizzle(env.AUTH_DB!, { relations: authRelations }); + return { + baseURL: env.BETTER_AUTH_URL, + secret: env.BETTER_AUTH_SECRET, + database: drizzleAdapter(db, { + provider: "sqlite", + schema: authTables, + }), + user: { + additionalFields: { + githubLogin: githubLoginField, + }, + }, + account: { + accountLinking: { + trustedProviders: ["github"], + }, + }, + socialProviders: { + github: { + clientId: env.GITHUB_OAUTH_CLIENT_ID!, + clientSecret: env.GITHUB_OAUTH_CLIENT_SECRET!, + overrideUserInfoOnSignIn: true, + mapProfileToUser: (profile: { login?: string }) => ({ + githubLogin: profile.login, + }), + }, + }, + advanced: { + ipAddress: { + ipAddressHeaders: ["cf-connecting-ip", "x-forwarded-for"], + }, + }, + plugins: [sveltekitCookies(getRequestEvent)], + }; } function normalizeUser(value: unknown): AuthUser | null { - if (!value || typeof value !== 'object') return null; - const raw = value as Record; - if (typeof raw.id !== 'string' || typeof raw.email !== 'string') return null; - return { - id: raw.id, - name: typeof raw.name === 'string' ? raw.name : '', - email: raw.email, - emailVerified: raw.emailVerified === true, - image: typeof raw.image === 'string' ? raw.image : null, - githubLogin: typeof raw.githubLogin === 'string' ? raw.githubLogin : null, - }; + if (!value || typeof value !== "object") return null; + const raw = value as Record; + if (typeof raw.id !== "string" || typeof raw.email !== "string") return null; + return { + id: raw.id, + name: typeof raw.name === "string" ? raw.name : "", + email: raw.email, + emailVerified: raw.emailVerified === true, + image: typeof raw.image === "string" ? raw.image : null, + githubLogin: typeof raw.githubLogin === "string" ? raw.githubLogin : null, + }; } function normalizeSession(value: unknown): AuthSession | null { - if (!value || typeof value !== 'object') return null; - const raw = value as Record; - if (typeof raw.id !== 'string' || typeof raw.userId !== 'string') return null; - const expiresAt = raw.expiresAt instanceof Date ? raw.expiresAt : new Date(String(raw.expiresAt)); - return { - id: raw.id, - userId: raw.userId, - expiresAt, - token: typeof raw.token === 'string' ? raw.token : undefined, - }; + if (!value || typeof value !== "object") return null; + const raw = value as Record; + if (typeof raw.id !== "string" || typeof raw.userId !== "string") return null; + const expiresAt = raw.expiresAt instanceof Date ? raw.expiresAt : new Date(String(raw.expiresAt)); + return { + id: raw.id, + userId: raw.userId, + expiresAt, + token: typeof raw.token === "string" ? raw.token : undefined, + }; } function parseLoginAllowlist(raw: string | undefined): Set { - return new Set( - (raw ?? '') - .split(',') - .map((entry) => entry.trim().toLowerCase()) - .filter(Boolean), - ); + return new Set( + (raw ?? "") + .split(",") + .map((entry) => entry.trim().toLowerCase()) + .filter(Boolean), + ); } diff --git a/codeview-ui/src/lib/server/cloudflare/catalog.test.ts b/codeview-ui/src/lib/server/cloudflare/catalog.test.ts index e2afafa..45087dd 100644 --- a/codeview-ui/src/lib/server/cloudflare/catalog.test.ts +++ b/codeview-ui/src/lib/server/cloudflare/catalog.test.ts @@ -1,29 +1,29 @@ -import { describe, expect, test } from 'vitest'; -import { catalogEntryToSummary, orderCatalogSummaries } from './catalog'; +import { describe, expect, test } from "vite-plus/test"; +import { catalogEntryToSummary, orderCatalogSummaries } from "./catalog"; -describe('cloudflare catalog', () => { - test('uses version as the concrete crate version', () => { - expect( - catalogEntryToSummary({ - name: 'proc_macro', - storageName: 'proc_macro', - version: '1.98.0-nightly', - nodeCount: 10, - edgeCount: 20, - }), - ).toMatchObject({ - id: 'proc_macro', - name: 'proc_macro', - version: '1.98.0-nightly', - }); - }); +describe("cloudflare catalog", () => { + test("uses version as the concrete crate version", () => { + expect( + catalogEntryToSummary({ + name: "proc_macro", + storageName: "proc_macro", + version: "1.98.0-nightly", + nodeCount: 10, + edgeCount: 20, + }), + ).toMatchObject({ + id: "proc_macro", + name: "proc_macro", + version: "1.98.0-nightly", + }); + }); - test('drops malformed entries instead of returning undefined versions', () => { - expect( - orderCatalogSummaries([ - { name: 'bad-crate', version: '' }, - { name: 'serde', storageName: 'serde', version: '1.0.0' }, - ]), - ).toEqual([{ id: 'serde', name: 'serde', version: '1.0.0', description: undefined }]); - }); + test("drops malformed entries instead of returning undefined versions", () => { + expect( + orderCatalogSummaries([ + { name: "bad-crate", version: "" }, + { name: "serde", storageName: "serde", version: "1.0.0" }, + ]), + ).toEqual([{ id: "serde", name: "serde", version: "1.0.0", description: undefined }]); + }); }); diff --git a/codeview-ui/src/lib/server/cloudflare/catalog.ts b/codeview-ui/src/lib/server/cloudflare/catalog.ts index a6e1ace..0420f0e 100644 --- a/codeview-ui/src/lib/server/cloudflare/catalog.ts +++ b/codeview-ui/src/lib/server/cloudflare/catalog.ts @@ -1,38 +1,38 @@ -import type { StaticCrateCatalogEntry } from '#lib/schema'; -import { isStdCrate } from '#lib/std'; -import { crateNameVariants, normalizeCrateName } from '../validation'; +import type { StaticCrateCatalogEntry } from "#lib/schema"; +import { isStdCrate } from "#lib/std"; +import { crateNameVariants, normalizeCrateName } from "../validation"; export type CatalogCrateSummary = { - id?: string; - name: string; - version: string; - description?: string; + id?: string; + name: string; + version: string; + description?: string; }; function catalogEntryVersion(entry: StaticCrateCatalogEntry): string | null { - const version = entry.version; - return typeof version === 'string' && version.length > 0 ? version : null; + const version = entry.version; + return typeof version === "string" && version.length > 0 ? version : null; } export function catalogEntryToSummary(entry: StaticCrateCatalogEntry): CatalogCrateSummary | null { - const version = catalogEntryVersion(entry); - if (!version) return null; - return { - id: entry.storageName ?? crateNameVariants(entry.name)[1], - name: entry.name, - version, - description: entry.description, - }; + const version = catalogEntryVersion(entry); + if (!version) return null; + return { + id: entry.storageName ?? crateNameVariants(entry.name)[1], + name: entry.name, + version, + description: entry.description, + }; } export function orderCatalogSummaries(entries: StaticCrateCatalogEntry[]): CatalogCrateSummary[] { - const std: CatalogCrateSummary[] = []; - const thirdParty: CatalogCrateSummary[] = []; - for (const entry of entries) { - const summary = catalogEntryToSummary(entry); - if (!summary) continue; - const source = entry.source === 'std' || isStdCrate(normalizeCrateName(entry.name)); - (source ? std : thirdParty).push(summary); - } - return [...thirdParty, ...std]; + const std: CatalogCrateSummary[] = []; + const thirdParty: CatalogCrateSummary[] = []; + for (const entry of entries) { + const summary = catalogEntryToSummary(entry); + if (!summary) continue; + const source = entry.source === "std" || isStdCrate(normalizeCrateName(entry.name)); + (source ? std : thirdParty).push(summary); + } + return [...thirdParty, ...std]; } diff --git a/codeview-ui/src/lib/server/cloudflare/parse-contract.test.ts b/codeview-ui/src/lib/server/cloudflare/parse-contract.test.ts index 396fa9a..83d35e6 100644 --- a/codeview-ui/src/lib/server/cloudflare/parse-contract.test.ts +++ b/codeview-ui/src/lib/server/cloudflare/parse-contract.test.ts @@ -1,56 +1,56 @@ -import { describe, expect, test } from 'vitest'; +import { describe, expect, test } from "vite-plus/test"; import { - makeParseRequest, - shouldAcceptQueuedParseRequest, - type StoredParseStatus, -} from './parse-contract'; + makeParseRequest, + shouldAcceptQueuedParseRequest, + type StoredParseStatus, +} from "./parse-contract"; function storedStatus( - status: StoredParseStatus['status'], - updatedAt = '2026-07-09T12:00:00.000Z', + status: StoredParseStatus["status"], + updatedAt = "2026-07-09T12:00:00.000Z", ): StoredParseStatus { - return { - ecosystem: 'rust', - kind: 'crate', - name: 'serde', - version: '1.0.228', - status, - createdAt: '2026-07-09T11:00:00.000Z', - updatedAt, - sequence: 1, - }; + return { + ecosystem: "rust", + kind: "crate", + name: "serde", + version: "1.0.228", + status, + createdAt: "2026-07-09T11:00:00.000Z", + updatedAt, + sequence: 1, + }; } -describe('queued parse registration', () => { - test('accepts work with no existing status', () => { - expect(shouldAcceptQueuedParseRequest(null, makeParseRequest('serde', '1.0.228', false))).toBe( - true, - ); - }); +describe("queued parse registration", () => { + test("accepts work with no existing status", () => { + expect(shouldAcceptQueuedParseRequest(null, makeParseRequest("serde", "1.0.228", false))).toBe( + true, + ); + }); - test('does not replace active work', () => { - expect( - shouldAcceptQueuedParseRequest( - storedStatus('processing'), - makeParseRequest('serde', '1.0.228', true), - ), - ).toBe(false); - }); + test("does not replace active work", () => { + expect( + shouldAcceptQueuedParseRequest( + storedStatus("processing"), + makeParseRequest("serde", "1.0.228", true), + ), + ).toBe(false); + }); - test('replaces an older terminal status', () => { - expect( - shouldAcceptQueuedParseRequest( - storedStatus('ready', '2020-01-01T00:00:00.000Z'), - makeParseRequest('serde', '1.0.228', false), - ), - ).toBe(true); - }); + test("replaces an older terminal status", () => { + expect( + shouldAcceptQueuedParseRequest( + storedStatus("ready", "2020-01-01T00:00:00.000Z"), + makeParseRequest("serde", "1.0.228", false), + ), + ).toBe(true); + }); - test('rejects a delayed registration older than the terminal status', () => { - const request = { - ...makeParseRequest('serde', '1.0.228', false), - requestedAt: '2026-07-09T11:59:59.000Z', - }; - expect(shouldAcceptQueuedParseRequest(storedStatus('failed'), request)).toBe(false); - }); + test("rejects a delayed registration older than the terminal status", () => { + const request = { + ...makeParseRequest("serde", "1.0.228", false), + requestedAt: "2026-07-09T11:59:59.000Z", + }; + expect(shouldAcceptQueuedParseRequest(storedStatus("failed"), request)).toBe(false); + }); }); diff --git a/codeview-ui/src/lib/server/cloudflare/parse-contract.ts b/codeview-ui/src/lib/server/cloudflare/parse-contract.ts index 690e723..e320b84 100644 --- a/codeview-ui/src/lib/server/cloudflare/parse-contract.ts +++ b/codeview-ui/src/lib/server/cloudflare/parse-contract.ts @@ -1,196 +1,198 @@ -import type { CrateStatus } from '../provider'; +import type { CrateStatus } from "../provider"; export const PARSE_REQUEST_SCHEMA_VERSION = 1; -export const PARSE_STATUS_OBJECT_NAME = 'rust'; +export const PARSE_STATUS_OBJECT_NAME = "rust"; -export type ParseRequestKind = 'crate' | 'sysroot'; +export type ParseRequestKind = "crate" | "sysroot"; -export type ParseRequestSource = 'ui' | 'manual' | 'planned'; +export type ParseRequestSource = "ui" | "manual" | "planned"; export type ParseRequestActor = { - provider: 'github'; - id: string; - login: string; - avatarUrl?: string; + provider: "github"; + id: string; + login: string; + avatarUrl?: string; }; export type ParseRequestMessage = { - schemaVersion: typeof PARSE_REQUEST_SCHEMA_VERSION; - ecosystem: 'rust'; - kind: ParseRequestKind; - name: string; - version: string; - force: boolean; - requestId: string; - requestedAt: string; - source: ParseRequestSource; - requestedBy?: ParseRequestActor; + schemaVersion: typeof PARSE_REQUEST_SCHEMA_VERSION; + ecosystem: "rust"; + kind: ParseRequestKind; + name: string; + version: string; + force: boolean; + requestId: string; + requestedAt: string; + source: ParseRequestSource; + requestedBy?: ParseRequestActor; }; export type ParseWorkflowParams = ParseRequestMessage & { - callbackBaseUrl?: string; + callbackBaseUrl?: string; }; export type ParseCompletionPayload = { - schemaVersion: 1; - kind?: ParseRequestKind; - workflowId: string; - requestId: string; - name: string; - version: string; - ok: boolean; - runId?: string; - runUrl?: string; - error?: string; - completedAt: string; + schemaVersion: 1; + kind?: ParseRequestKind; + workflowId: string; + requestId: string; + name: string; + version: string; + ok: boolean; + runId?: string; + runUrl?: string; + error?: string; + completedAt: string; }; export type StoredParseStatus = CrateStatus & { - ecosystem: 'rust'; - kind: ParseRequestKind; - name: string; - version: string; - requestId?: string; - workflowId?: string; - githubRunId?: string; - githubRunUrl?: string; - requestedBy?: ParseRequestActor; - createdAt: string; - updatedAt: string; - sequence: number; + ecosystem: "rust"; + kind: ParseRequestKind; + name: string; + version: string; + requestId?: string; + workflowId?: string; + githubRunId?: string; + githubRunUrl?: string; + requestedBy?: ParseRequestActor; + createdAt: string; + updatedAt: string; + sequence: number; }; export type ParseQueueSnapshot = { - active: StoredParseStatus[]; - recent: StoredParseStatus[]; + active: StoredParseStatus[]; + recent: StoredParseStatus[]; }; export type BeginParseResponse = { - accepted: boolean; - leased: boolean; - workflowId: string; - retryAfterSeconds?: number; - status: StoredParseStatus; + accepted: boolean; + leased: boolean; + workflowId: string; + retryAfterSeconds?: number; + status: StoredParseStatus; }; export type QueueParseResponse = { - accepted: boolean; - status: StoredParseStatus; + accepted: boolean; + status: StoredParseStatus; }; export type ParseStatusEvent = { - kind?: ParseRequestKind; - name: string; - version: string; - status: CrateStatus['status']; - step?: string; - error?: string; - action?: CrateStatus['action']; - requestId?: string; - workflowId?: string; - githubRunId?: string; - githubRunUrl?: string; - requestedBy?: ParseRequestActor; + kind?: ParseRequestKind; + name: string; + version: string; + status: CrateStatus["status"]; + step?: string; + error?: string; + action?: CrateStatus["action"]; + requestId?: string; + workflowId?: string; + githubRunId?: string; + githubRunUrl?: string; + requestedBy?: ParseRequestActor; }; export function crateStatusTag(name: string, version: string): string { - return `rust:${name}:${version}`; + return `rust:${name}:${version}`; } export function parseStatusObject(namespace: DurableObjectNamespace): DurableObjectStub { - const id = namespace.idFromName(PARSE_STATUS_OBJECT_NAME); - return namespace.get(id); + const id = namespace.idFromName(PARSE_STATUS_OBJECT_NAME); + return namespace.get(id); } export async function registerQueuedParseRequest( - namespace: DurableObjectNamespace, - message: ParseRequestMessage, + namespace: DurableObjectNamespace, + message: ParseRequestMessage, ): Promise { - const response = await parseStatusObject(namespace).fetch('https://status/queued', { - method: 'POST', - headers: { 'content-type': 'application/json; charset=utf-8' }, - body: JSON.stringify(message), - }); - if (!response.ok) { - throw new Error(`parse queue registration failed: ${response.status}`); - } - return (await response.json()) as QueueParseResponse; + const response = await parseStatusObject(namespace).fetch("https://status/queued", { + method: "POST", + headers: { "content-type": "application/json; charset=utf-8" }, + body: JSON.stringify(message), + }); + if (!response.ok) { + throw new Error(`parse queue registration failed: ${response.status}`); + } + return (await response.json()) as QueueParseResponse; } export function shouldAcceptQueuedParseRequest( - existing: StoredParseStatus | null, - message: ParseRequestMessage, + existing: StoredParseStatus | null, + message: ParseRequestMessage, ): boolean { - if (!existing) return true; - if (existing.status === 'processing') return false; - const requestedAt = Date.parse(message.requestedAt); - const existingUpdatedAt = Date.parse(existing.updatedAt); - return ( - Number.isFinite(requestedAt) && - (!Number.isFinite(existingUpdatedAt) || requestedAt > existingUpdatedAt) - ); + if (!existing) return true; + if (existing.status === "processing") return false; + const requestedAt = Date.parse(message.requestedAt); + const existingUpdatedAt = Date.parse(existing.updatedAt); + return ( + Number.isFinite(requestedAt) && + (!Number.isFinite(existingUpdatedAt) || requestedAt > existingUpdatedAt) + ); } export function parseWorkflowId(requestId: string): string { - return `parse-${requestId}`; + return `parse-${requestId}`; } export function makeParseRequest( - name: string, - version: string, - force: boolean, - source: ParseRequestSource = 'ui', - kind: ParseRequestKind = 'crate', - requestedBy?: ParseRequestActor, + name: string, + version: string, + force: boolean, + source: ParseRequestSource = "ui", + kind: ParseRequestKind = "crate", + requestedBy?: ParseRequestActor, ): ParseRequestMessage { - const requestId = - typeof crypto !== 'undefined' && 'randomUUID' in crypto - ? crypto.randomUUID() - : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; - return { - schemaVersion: PARSE_REQUEST_SCHEMA_VERSION, - ecosystem: 'rust', - kind, - name, - version, - force, - requestId, - requestedAt: new Date().toISOString(), - source, - requestedBy, - }; + const requestId = + typeof crypto !== "undefined" && "randomUUID" in crypto + ? crypto.randomUUID() + : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; + return { + schemaVersion: PARSE_REQUEST_SCHEMA_VERSION, + ecosystem: "rust", + kind, + name, + version, + force, + requestId, + requestedAt: new Date().toISOString(), + source, + requestedBy, + }; } export function isParseRequestMessage(value: unknown): value is ParseRequestMessage { - if (typeof value !== 'object' || value === null) return false; - const candidate = value as Partial; - return ( - candidate.schemaVersion === PARSE_REQUEST_SCHEMA_VERSION && - candidate.ecosystem === 'rust' && - (candidate.kind === 'crate' || candidate.kind === 'sysroot') && - typeof candidate.name === 'string' && - candidate.name.length > 0 && - typeof candidate.version === 'string' && - candidate.version.length > 0 && - typeof candidate.force === 'boolean' && - typeof candidate.requestId === 'string' && - candidate.requestId.length > 0 && - typeof candidate.requestedAt === 'string' && - Number.isFinite(Date.parse(candidate.requestedAt)) && - (candidate.source === 'ui' || candidate.source === 'manual' || candidate.source === 'planned') && - (candidate.requestedBy === undefined || isParseRequestActor(candidate.requestedBy)) - ); + if (typeof value !== "object" || value === null) return false; + const candidate = value as Partial; + return ( + candidate.schemaVersion === PARSE_REQUEST_SCHEMA_VERSION && + candidate.ecosystem === "rust" && + (candidate.kind === "crate" || candidate.kind === "sysroot") && + typeof candidate.name === "string" && + candidate.name.length > 0 && + typeof candidate.version === "string" && + candidate.version.length > 0 && + typeof candidate.force === "boolean" && + typeof candidate.requestId === "string" && + candidate.requestId.length > 0 && + typeof candidate.requestedAt === "string" && + Number.isFinite(Date.parse(candidate.requestedAt)) && + (candidate.source === "ui" || + candidate.source === "manual" || + candidate.source === "planned") && + (candidate.requestedBy === undefined || isParseRequestActor(candidate.requestedBy)) + ); } function isParseRequestActor(value: unknown): value is ParseRequestActor { - if (typeof value !== 'object' || value === null) return false; - const candidate = value as Partial; - return ( - candidate.provider === 'github' && - typeof candidate.id === 'string' && - candidate.id.length > 0 && - typeof candidate.login === 'string' && - candidate.login.length > 0 && - (candidate.avatarUrl === undefined || typeof candidate.avatarUrl === 'string') - ); + if (typeof value !== "object" || value === null) return false; + const candidate = value as Partial; + return ( + candidate.provider === "github" && + typeof candidate.id === "string" && + candidate.id.length > 0 && + typeof candidate.login === "string" && + candidate.login.length > 0 && + (candidate.avatarUrl === undefined || typeof candidate.avatarUrl === "string") + ); } diff --git a/codeview-ui/src/lib/server/cloudflare/provider.test.ts b/codeview-ui/src/lib/server/cloudflare/provider.test.ts index 90462dc..b2ad4c5 100644 --- a/codeview-ui/src/lib/server/cloudflare/provider.test.ts +++ b/codeview-ui/src/lib/server/cloudflare/provider.test.ts @@ -1,1068 +1,1067 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import type { AuthState } from '../auth'; +import { afterEach, describe, expect, test, vi } from "vite-plus/test"; +import type { AuthState } from "../auth"; const mockAuthState = vi.hoisted(() => ({ - value: null as AuthState | null, + value: null as AuthState | null, })); -vi.mock('../auth', async (importOriginal) => { - const actual = await importOriginal(); - const unauthenticated = { - user: null, - session: null, - isAdmin: false, - authConfigured: false, - adminAllowlistConfigured: false, - } satisfies AuthState; - return { - ...actual, - getAuthStateFromRequest: vi.fn(async () => mockAuthState.value ?? unauthenticated), - }; +vi.mock("../auth", async (importOriginal) => { + const actual = await importOriginal(); + const unauthenticated = { + user: null, + session: null, + isAdmin: false, + authConfigured: false, + adminAllowlistConfigured: false, + } satisfies AuthState; + return { + ...actual, + getAuthStateFromRequest: vi.fn(async () => mockAuthState.value ?? unauthenticated), + }; }); -import { createCloudflareProvider } from './provider'; +import { createCloudflareProvider } from "./provider"; function jsonObject(value: unknown): R2ObjectBody { - return new Response( - typeof value === 'string' ? value : JSON.stringify(value), - ) as unknown as R2ObjectBody; + return new Response( + typeof value === "string" ? value : JSON.stringify(value), + ) as unknown as R2ObjectBody; } function fakeBucket(objects: Map): R2Bucket { - return { - async get(key: string) { - const value = objects.get(key); - return value === undefined ? null : jsonObject(value); - }, - async put(key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream) { - if (typeof value === 'string') { - objects.set(key, value); - } else if (value instanceof ReadableStream) { - objects.set(key, await new Response(value).text()); - } else { - objects.set( - key, - new TextDecoder().decode(value instanceof ArrayBuffer ? value : value.buffer), - ); - } - return null; - }, - async head(key: string) { - return objects.has(key) ? ({} as R2Object) : null; - }, - async list(options?: R2ListOptions) { - const prefix = options?.prefix ?? ''; - const keys = [...objects.keys()].filter((key) => key.startsWith(prefix)).sort(); - return { - objects: keys.map((key) => ({ key })), - delimitedPrefixes: [], - truncated: false, - } as unknown as R2Objects; - }, - } as unknown as R2Bucket; + return { + async get(key: string) { + const value = objects.get(key); + return value === undefined ? null : jsonObject(value); + }, + async put(key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream) { + if (typeof value === "string") { + objects.set(key, value); + } else if (value instanceof ReadableStream) { + objects.set(key, await new Response(value).text()); + } else { + objects.set( + key, + new TextDecoder().decode(value instanceof ArrayBuffer ? value : value.buffer), + ); + } + return null; + }, + async head(key: string) { + return objects.has(key) ? ({} as R2Object) : null; + }, + async list(options?: R2ListOptions) { + const prefix = options?.prefix ?? ""; + const keys = [...objects.keys()].filter((key) => key.startsWith(prefix)).sort(); + return { + objects: keys.map((key) => ({ key })), + delimitedPrefixes: [], + truncated: false, + } as unknown as R2Objects; + }, + } as unknown as R2Bucket; } function fakeQueue(sent: unknown[]): Queue { - return { - async send(body: unknown) { - sent.push(body); - }, - } as unknown as Queue; + return { + async send(body: unknown) { + sent.push(body); + }, + } as unknown as Queue; } function fakeRateLimit(success = true): RateLimit { - return { - async limit() { - return { success }; - }, - } as unknown as RateLimit; + return { + async limit() { + return { success }; + }, + } as unknown as RateLimit; } function fakeParseStatusNamespace( - initialStatus: unknown, - registrations: unknown[] = [], - queueSnapshot?: { active: unknown[]; recent: unknown[] }, + initialStatus: unknown, + registrations: unknown[] = [], + queueSnapshot?: { active: unknown[]; recent: unknown[] }, ): DurableObjectNamespace { - let status = initialStatus; - const stub = { - async fetch(input: RequestInfo | URL, init?: RequestInit) { - const url = new URL(input instanceof Request ? input.url : input.toString()); - if (url.pathname === '/queued') { - const message = ( - input instanceof Request - ? await input.clone().json() - : JSON.parse(String(init?.body ?? '{}')) - ) as Record; - registrations.push(message); - status = { - ecosystem: 'rust', - kind: message.kind, - name: message.name, - version: message.version, - status: 'processing', - step: 'queued', - requestId: message.requestId, - workflowId: `parse-${message.requestId}`, - createdAt: message.requestedAt, - updatedAt: message.requestedAt, - sequence: 1, - }; - return Response.json({ accepted: true, status }); - } - if (url.pathname === '/status') return Response.json(status); - if (url.pathname === '/processing') { - return Response.json( - (status as { status?: string } | null)?.status === 'processing' ? [status] : [], - ); - } - if (url.pathname === '/queue') { - return Response.json( - queueSnapshot ?? { - active: - (status as { status?: string } | null)?.status === 'processing' ? [status] : [], - recent: - (status as { status?: string } | null)?.status === 'processing' || !status - ? [] - : [status], - }, - ); - } - return new Response(null, { status: 404 }); - }, - }; - return { - idFromName() { - return {}; - }, - get() { - return stub; - }, - } as unknown as DurableObjectNamespace; + let status = initialStatus; + const stub = { + async fetch(input: RequestInfo | URL, init?: RequestInit) { + const url = new URL(input instanceof Request ? input.url : input.toString()); + if (url.pathname === "/queued") { + const message = ( + input instanceof Request + ? await input.clone().json() + : JSON.parse(String(init?.body ?? "{}")) + ) as Record; + registrations.push(message); + status = { + ecosystem: "rust", + kind: message.kind, + name: message.name, + version: message.version, + status: "processing", + step: "queued", + requestId: message.requestId, + workflowId: `parse-${message.requestId}`, + createdAt: message.requestedAt, + updatedAt: message.requestedAt, + sequence: 1, + }; + return Response.json({ accepted: true, status }); + } + if (url.pathname === "/status") return Response.json(status); + if (url.pathname === "/processing") { + return Response.json( + (status as { status?: string } | null)?.status === "processing" ? [status] : [], + ); + } + if (url.pathname === "/queue") { + return Response.json( + queueSnapshot ?? { + active: (status as { status?: string } | null)?.status === "processing" ? [status] : [], + recent: + (status as { status?: string } | null)?.status === "processing" || !status + ? [] + : [status], + }, + ); + } + return new Response(null, { status: 404 }); + }, + }; + return { + idFromName() { + return {}; + }, + get() { + return stub; + }, + } as unknown as DurableObjectNamespace; } function fnv1a32(value: string): number { - let hash = 0x811c9dc5; - for (let i = 0; i < value.length; i += 1) { - hash ^= value.charCodeAt(i); - hash = Math.imul(hash, 0x01000193) >>> 0; - } - return hash >>> 0; + let hash = 0x811c9dc5; + for (let i = 0; i < value.length; i += 1) { + hash ^= value.charCodeAt(i); + hash = Math.imul(hash, 0x01000193) >>> 0; + } + return hash >>> 0; } function nodeViewBucket(nodeId: string, bucketCount = 128): string { - const bucket = fnv1a32(nodeId) % bucketCount; - const width = Math.max(3, (bucketCount - 1).toString(16).length); - return bucket.toString(16).padStart(width, '0'); + const bucket = fnv1a32(nodeId) % bucketCount; + const width = Math.max(3, (bucketCount - 1).toString(16).length); + return bucket.toString(16).padStart(width, "0"); } function hostedMeta( - nodeViewBucketCount: number, - version = '1.0.0', - artifacts: Record = {}, - name = 'demo', + nodeViewBucketCount: number, + version = "1.0.0", + artifacts: Record = {}, + name = "demo", ) { - return { - schema_version: 2, - name, - version, - index: { - name, - version, - crates: [], - }, - nodeCount: 1, - edgeCount: 0, - kindCounts: {}, - roots: [], - rootChildren: {}, - artifacts: { - nodeViewBucketCount, - treeChildrenBucketCount: 128, - aliasBucketCount: 128, - targetRawShardBytes: 262_144, - searchPrefixLength: 2, - kindIndex: true, - ...artifacts, - }, - }; + return { + schema_version: 2, + name, + version, + index: { + name, + version, + crates: [], + }, + nodeCount: 1, + edgeCount: 0, + kindCounts: {}, + roots: [], + rootChildren: {}, + artifacts: { + nodeViewBucketCount, + treeChildrenBucketCount: 128, + aliasBucketCount: 128, + targetRawShardBytes: 262_144, + searchPrefixLength: 2, + kindIndex: true, + ...artifacts, + }, + }; } -function crateRefs(version = '1.0.0', storageName = 'demo') { - const versions = [...new Set([version, '1.0.0', '1.0.1'])]; - return { - schemaVersion: 1, - storageName, - displayName: storageName, - aliases: { - latest: { - version, - graphHash: `hash-${version}`, - }, - }, - versions: versions.map((entryVersion) => ({ - version: entryVersion, - graphHash: `hash-${entryVersion}`, - })), - }; +function crateRefs(version = "1.0.0", storageName = "demo") { + const versions = [...new Set([version, "1.0.0", "1.0.1"])]; + return { + schemaVersion: 1, + storageName, + displayName: storageName, + aliases: { + latest: { + version, + graphHash: `hash-${version}`, + }, + }, + versions: versions.map((entryVersion) => ({ + version: entryVersion, + graphHash: `hash-${entryVersion}`, + })), + }; } function hostedNodeViewArtifact( - prefix: string, - nodeId: string, - version = '1.0.0', + prefix: string, + nodeId: string, + version = "1.0.0", ): [string, unknown] { - const bucket = nodeViewBucket(nodeId); - return [ - `${prefix}/site/node-views/${bucket}.json`, - { - schema_version: 2, - name: 'demo', - version, - bucket, - bucketCount: 128, - entries: { - [nodeId]: { - detail: { - node: { - id: nodeId, - name: 'demo', - kind: 'Crate', - visibility: { kind: 'Public' }, - attrs: [], - }, - edges: [], - relatedNodes: [], - }, - ancestors: [], - }, - }, - }, - ]; + const bucket = nodeViewBucket(nodeId); + return [ + `${prefix}/site/node-views/${bucket}.json`, + { + schema_version: 2, + name: "demo", + version, + bucket, + bucketCount: 128, + entries: { + [nodeId]: { + detail: { + node: { + id: nodeId, + name: "demo", + kind: "Crate", + visibility: { kind: "Public" }, + attrs: [], + }, + edges: [], + relatedNodes: [], + }, + ancestors: [], + }, + }, + }, + ]; } -describe('createCloudflareProvider', () => { - afterEach(() => { - mockAuthState.value = null; - vi.useRealTimers(); - vi.unstubAllGlobals(); - }); - - test('resolves published crates through canonical refs', async () => { - const objects = new Map([ - [ - 'rust/_refs/proc_macro.json', - { - schemaVersion: 1, - storageName: 'proc_macro', - displayName: 'proc_macro', - aliases: { - latest: { - version: '1.98.0-nightly', - graphHash: 'hash', - }, - }, - versions: [ - { - version: '1.98.0-nightly', - graphHash: 'hash', - }, - ], - }, - ], - [ - 'rust/proc_macro/1.98.0-nightly/site/meta.json', - hostedMeta(128, '1.98.0-nightly', {}, 'proc_macro'), - ], - ]); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - } as unknown as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect(provider.getCrateStatus('proc-macro', '1.98.0-nightly')).resolves.toEqual({ - status: 'ready', - }); - }); - - test('rejects stale ready status when no current artifact is published', async () => { - const objects = new Map([ - ['rust/_refs/demo.json', crateRefs()], - [ - 'rust/demo/1.0.0/site/meta.json', - { - schema_version: 1, - name: 'demo', - version: '1.0.0', - }, - ], - ]); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - PARSE_STATUS: fakeParseStatusNamespace({ - ecosystem: 'rust', - kind: 'crate', - name: 'demo', - version: '1.0.0', - status: 'ready', - createdAt: '2026-07-09T00:00:00.000Z', - updatedAt: '2026-07-09T00:00:00.000Z', - sequence: 1, - }), - } as unknown as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect(provider.getCrateStatus('demo', '1.0.0')).resolves.toEqual({ - status: 'failed', - error: 'No static graph is published for demo@1.0.0.', - action: 'docs_unavailable', - }); - }); - - test('refreshes exact-version refs after a hosted artifact is replaced', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date('2026-07-09T00:00:00.000Z')); - const name = 'mutable-ref-demo'; - const version = '1.0.0'; - const refsKey = `rust/_refs/${name}.json`; - const metaKey = `rust/${name}/${version}/site/meta.json`; - const refs = (graphHash: string) => ({ - schemaVersion: 1, - storageName: name, - displayName: name, - aliases: { latest: { version, graphHash } }, - versions: [{ version, graphHash }], - }); - const objects = new Map([ - [refsKey, refs('old-hash')], - [metaKey, { schema_version: 1, name, version }], - ]); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect(provider.getCrateStatus(name, version)).resolves.toMatchObject({ - status: 'failed', - }); - - objects.set(refsKey, refs('new-hash')); - objects.set(metaKey, hostedMeta(128, version, {}, name)); - vi.advanceTimersByTime(5_001); - - await expect(provider.getCrateStatus(name, version)).resolves.toEqual({ status: 'ready' }); - }); - - test('does not assemble node views from base shards', async () => { - const prefix = 'rust/demo/1.0.0'; - const nodeId = 'demo'; - const objects = new Map([ - ['rust/_refs/demo.json', crateRefs()], - [`${prefix}/site/meta.json`, hostedMeta(128)], - ]); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - } as Env & { CRATE_GRAPHS: R2Bucket }); - const loadNodeViewDirect = provider.loadNodeViewDirect; - expect(loadNodeViewDirect).toBeDefined(); - if (!loadNodeViewDirect) throw new Error('loadNodeViewDirect missing'); - - await expect(loadNodeViewDirect('demo', '1.0.0', nodeId)).resolves.toBeNull(); - }); - - test('loads the complete materialized node view', async () => { - const version = '1.0.1'; - const prefix = `rust/demo/${version}`; - const nodeId = 'demo'; - const objects = new Map([ - ['rust/_refs/demo.json', crateRefs(version)], - [`${prefix}/site/meta.json`, hostedMeta(128, version)], - hostedNodeViewArtifact(prefix, nodeId, version), - ]); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - } as Env & { CRATE_GRAPHS: R2Bucket }); - const loadNodeViewDirect = provider.loadNodeViewDirect; - expect(loadNodeViewDirect).toBeDefined(); - if (!loadNodeViewDirect) throw new Error('loadNodeViewDirect missing'); - - await expect(loadNodeViewDirect('demo', version, nodeId)).resolves.toMatchObject({ - detail: { - node: { - id: nodeId, - }, - edges: [], - relatedNodes: [], - }, - ancestors: [], - }); - }); - - test('filters hosted nodes by kind from hosted kind index', async () => { - const crateName = 'kinddemo'; - const version = '1.0.0'; - const prefix = `rust/${crateName}/${version}`; - const nestedNodeId = `${crateName}::hidden::Widget`; - const objects = new Map([ - [`rust/_refs/${crateName}.json`, crateRefs(version, crateName)], - [`${prefix}/site/meta.json`, hostedMeta(128, version, { kindIndex: true }, crateName)], - [ - `${prefix}/site/kinds/Struct.json`, - { - schema_version: 2, - name: crateName, - version, - kind: 'Struct', - entries: [ - { - id: nestedNodeId, - name: 'Widget', - kind: 'Struct', - visibility: { kind: 'Public' }, - }, - ], - }, - ], - ]); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect( - provider.searchNodesDirect?.(crateName, version, '', 10, ['Struct']), - ).resolves.toEqual([ - { - id: nestedNodeId, - name: 'Widget', - kind: 'Struct', - visibility: { kind: 'Public' }, - }, - ]); - await expect( - provider.searchNodesDirect?.(crateName, version, '', 10, ['Impl']), - ).resolves.toEqual([]); - }); - - test('uses live crates.io metadata for top crates', async () => { - vi.stubGlobal( - 'fetch', - vi.fn( - async () => - new Response( - JSON.stringify({ - crates: [ - { - id: 'rand_core', - name: 'rand_core', - description: 'Core random number generator traits', - repository: 'https://github.com/rust-random/rand', - max_version: '0.9.3', - }, - ], - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ), - ), - ); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(new Map()), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect(provider.getTopCrates(1)).resolves.toEqual([ - { - id: 'rand-core', - name: 'rand_core', - version: '0.9.3', - description: 'Core random number generator traits', - }, - ]); - }); - - test('uses live crates.io versions beyond parsed artifact refs', async () => { - const fetchMock = vi.fn(async (input: RequestInfo | URL) => { - expect(String(input)).toBe('https://index.crates.io/ha/sh/hashbrown'); - return new Response( - [ - JSON.stringify({ name: 'hashbrown', vers: '0.16.1', yanked: false }), - JSON.stringify({ name: 'hashbrown', vers: '0.17.0', yanked: false }), - JSON.stringify({ name: 'hashbrown', vers: '0.17.1', yanked: false }), - '', - ].join('\n'), - { status: 200 }, - ); - }); - vi.stubGlobal('fetch', fetchMock); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket( - new Map([ - [ - 'rust/_refs/hashbrown.json', - { - schemaVersion: 1, - storageName: 'hashbrown', - displayName: 'hashbrown', - aliases: { - latest: { - version: '0.17.1', - graphHash: 'hash-0.17.1', - }, - }, - versions: [ - { - version: '0.17.1', - graphHash: 'hash-0.17.1', - }, - ], - }, - ], - ]), - ), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect(provider.getCrateVersions('hashbrown', 5)).resolves.toEqual([ - '0.17.1', - '0.17.0', - '0.16.1', - ]); - await expect(provider.resolveVersion('hashbrown', 'latest')).resolves.toBe('0.17.1'); - expect(fetchMock).toHaveBeenCalledTimes(2); - }); - - test('lists toolchain channels before concrete published versions', async () => { - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket( - new Map([ - [ - 'rust/_refs/std.json', - { - schemaVersion: 1, - storageName: 'std', - displayName: 'std', - aliases: { - nightly: { version: '1.98.0-nightly', graphHash: 'hash-nightly' }, - }, - versions: [{ version: '1.98.0-nightly', graphHash: 'hash-nightly' }], - }, - ], - ]), - ), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect(provider.getCrateVersions('std')).resolves.toEqual([ - 'stable', - 'beta', - 'nightly', - '1.98.0-nightly', - ]); - }); - - test('searches exact toolchain crate channels independently of crates.io', async () => { - vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response(JSON.stringify({ crates: [] }), { status: 200 })), - ); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(new Map()), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect(provider.searchRegistry('std@nightly')).resolves.toMatchObject([ - { id: 'std', name: 'std', version: 'nightly' }, - ]); - }); - - test('includes active GitHub parse workflow runs in queue snapshots', async () => { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL) => { - const url = new URL(String(input)); - const status = url.searchParams.get('status'); - return new Response( - JSON.stringify({ - workflow_runs: - status === 'in_progress' - ? [ - { - id: 123, - name: 'parse', - display_title: 'parse hashbrown 0.17.1', - status: 'in_progress', - event: 'workflow_dispatch', - head_branch: 'main', - html_url: 'https://github.com/themixednuts/codeview/actions/runs/123', - created_at: '2026-07-07T12:00:00Z', - updated_at: '2026-07-07T12:05:00Z', - }, - ] - : [], - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ); - }), - ); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(new Map()), - GITHUB_REPO: 'themixednuts/codeview', - GITHUB_WORKFLOW_FILE: 'parse.yml', - } as Env & { CRATE_GRAPHS: R2Bucket }); - - await expect(provider.getParseQueue?.(10)).resolves.toMatchObject({ - active: [], - activeRuns: [ - { - id: '123', - title: 'parse hashbrown 0.17.1', - status: 'in_progress', - event: 'workflow_dispatch', - branch: 'main', - url: 'https://github.com/themixednuts/codeview/actions/runs/123', - }, - ], - recent: [], - planned: null, - }); - }); - - test('keeps current plan items visible when an older status row has the same crate version', async () => { - const objects = new Map([ - [ - 'rust/_runs/run-1/plan.json', - { - run_id: 'run-1', - generated_at: '2026-07-28T06:00:00Z', - mode: 'daily', - shard_count: 8, - work: [ - { - work_id: 'crate:demo:1.0.0:default', - kind: 'crate', - name: 'demo', - version: '1.0.0', - channel: 'default', - priority_tier: 'top-download-stale', - reason: 'parser old0000 → target123', - download_rank: 1, - }, - ], - }, - ], - [ - 'rust/_index/by-version/demo/1.0.0.json', - { - name: 'demo', - version: '1.0.0', - parsedAt: '2026-07-28T06:10:00Z', - parserRevision: 'target1234567890', - schemaVersion: 1, - }, - ], - ]); - const oldStatus = { - ecosystem: 'rust', - kind: 'crate', - name: 'demo', - version: '1.0.0', - status: 'ready', - createdAt: '2026-07-01T00:00:00Z', - updatedAt: '2026-07-01T00:05:00Z', - sequence: 1, - }; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - PARSE_STATUS: fakeParseStatusNamespace(null, [], { - active: [], - recent: [oldStatus], - }), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const snapshot = await provider.getParseQueue?.(100); - - expect(snapshot?.planned).toMatchObject({ - runId: 'run-1', - pending: 0, - ready: 1, - items: [ - { - name: 'demo', - version: '1.0.0', - state: 'ready', - }, - ], - }); - }); - - test('builds admin dashboard allowance from GitHub active runs and billing', async () => { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL) => { - const url = new URL(String(input)); - if (url.pathname === '/repos/themixednuts/codeview') { - return new Response( - JSON.stringify({ - full_name: 'themixednuts/codeview', - private: true, - owner: { login: 'themixednuts', type: 'User' }, - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ); - } - if (url.pathname === '/users/themixednuts/settings/billing/usage/summary') { - expect(url.searchParams.get('product')).toBe('Actions'); - expect(url.searchParams.get('repository')).toBe('themixednuts/codeview'); - return new Response( - JSON.stringify({ - usageItems: [ - { - product: 'Actions', - sku: 'actions_linux', - unitType: 'minutes', - grossQuantity: 125, - netQuantity: 12, - }, - { - product: 'Codespaces', - sku: 'codespaces_compute', - unitType: 'hours', - grossQuantity: 10, - }, - ], - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ); - } - if (url.pathname === '/repos/themixednuts/codeview/actions/workflows/parse.yml/runs') { - if (url.searchParams.has('created')) { - return new Response( - JSON.stringify({ - workflow_runs: [ - { - id: 321, - status: 'completed', - created_at: '2026-07-07T12:00:00Z', - updated_at: '2026-07-07T12:30:00Z', - }, - ], - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ); - } - return new Response( - JSON.stringify({ - workflow_runs: - url.searchParams.get('status') === 'in_progress' - ? [ - { - id: 123, - name: 'parse', - display_title: 'parse bitflags 2.13.0', - status: 'in_progress', - event: 'workflow_dispatch', - head_branch: 'main', - html_url: 'https://github.com/themixednuts/codeview/actions/runs/123', - created_at: '2026-07-07T12:00:00Z', - updated_at: '2026-07-07T12:05:00Z', - }, - ] - : [], - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ); - } - return new Response('{}', { status: 404 }); - }), - ); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(new Map()), - GITHUB_REPO: 'themixednuts/codeview', - GITHUB_WORKFLOW_FILE: 'parse.yml', - GITHUB_TOKEN: 'token', - PLAN_DRAIN_ACTIVE_TARGET: '4', - PLAN_DRAIN_BATCH_SIZE: '2', - GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT: '35', - } as unknown as Env & { CRATE_GRAPHS: R2Bucket }); - - const dashboard = await provider.getAdminDashboard?.(10); - - expect(dashboard?.allowance).toMatchObject({ - repo: 'themixednuts/codeview', - activeTarget: 4, - batchSize: 2, - trackedActiveCount: 0, - githubActiveRunCount: 1, - actionsInUse: 1, - availableSlots: 3, - repoUsageTargetPercent: 35, - repoPrivate: true, - standardRunnerMinutesMetered: true, - estimatedRepoMinutesThisMonth: 30, - billing: { - available: true, - totalMinutesUsed: 125, - totalPaidMinutesUsed: 12, - }, - }); - }); - - test('treats PLAN_DRAIN_BATCH_SIZE=0 as planned siphon disabled', async () => { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL) => { - const url = new URL(String(input)); - if (url.pathname === '/repos/themixednuts/codeview') { - return new Response( - JSON.stringify({ - full_name: 'themixednuts/codeview', - private: false, - owner: { login: 'themixednuts', type: 'User' }, - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ); - } - if (url.pathname === '/repos/themixednuts/codeview/actions/workflows/parse.yml/runs') { - return new Response(JSON.stringify({ workflow_runs: [], total_count: 0 }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }); - } - return new Response('{}', { status: 404 }); - }), - ); - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(new Map()), - GITHUB_REPO: 'themixednuts/codeview', - GITHUB_WORKFLOW_FILE: 'parse.yml', - GITHUB_TOKEN: 'token', - PLAN_DRAIN_ACTIVE_TARGET: '4', - PLAN_DRAIN_BATCH_SIZE: '0', - } as unknown as Env & { CRATE_GRAPHS: R2Bucket }); - - const dashboard = await provider.getAdminDashboard?.(10); - - expect(dashboard?.allowance).toMatchObject({ - activeTarget: 4, - batchSize: 0, - availableSlots: 4, - }); - }); - - test('enqueues hosted parse requests', async () => { - const objects = new Map(); - const sent: unknown[] = []; - const registrations: unknown[] = []; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - PARSE_REQUESTS: fakeQueue(sent), - PARSE_STATUS: fakeParseStatusNamespace(null, registrations), - RATE_LIMIT_PARSE_ANON: fakeRateLimit(), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const result = await provider.triggerParse('serde', '1.0.228'); - if (result.isErr()) throw result.error; - expect(sent).toHaveLength(1); - expect(sent[0]).toMatchObject({ - schemaVersion: 1, - ecosystem: 'rust', - kind: 'crate', - name: 'serde', - version: '1.0.228', - force: false, - source: 'ui', - }); - expect(registrations).toHaveLength(1); - expect(registrations[0]).toMatchObject({ - kind: 'crate', - name: 'serde', - version: '1.0.228', - }); - - await expect(provider.getCrateStatus('serde', '1.0.228')).resolves.toEqual({ - status: 'processing', - step: 'queued', - error: undefined, - action: undefined, - installedVersion: undefined, - }); - await expect(provider.getProcessingCrates(5)).resolves.toEqual([ - { - id: 'serde', - name: 'serde', - version: '1.0.228', - description: 'queued', - }, - ]); - }); - - test('fails closed when hosted parse rate limiting is missing', async () => { - const sent: unknown[] = []; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(new Map()), - PARSE_REQUESTS: fakeQueue(sent), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const result = await provider.triggerParse('serde', '1.0.228'); - expect(result.isErr()).toBe(true); - if (!result.isErr()) throw new Error('expected parse request to fail'); - expect(result.error._tag).toBe('NotAvailableError'); - expect(result.error.message).toBe('Hosted parse rate limiting is not configured'); - expect(sent).toHaveLength(0); - }); - - test('requires admin auth for forced hosted parses', async () => { - const sent: unknown[] = []; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(new Map()), - PARSE_REQUESTS: fakeQueue(sent), - RATE_LIMIT_PARSE_ANON: fakeRateLimit(), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const result = await provider.triggerParse('serde', '1.0.228', true); - expect(result.isErr()).toBe(true); - if (!result.isErr()) throw new Error('expected force parse request to fail'); - expect(result.error._tag).toBe('NotAvailableError'); - expect(result.error.message).toBe('Force parse requires admin access'); - expect(sent).toHaveLength(0); - }); - - test('lets admin force parses bypass parse rate limiting', async () => { - const sent: unknown[] = []; - mockAuthState.value = { - user: { - id: 'github-user-1', - name: 'Admin', - email: 'admin@example.com', - emailVerified: true, - githubLogin: 'themixednuts', - image: 'https://example.com/avatar.png', - }, - session: { - id: 'session-1', - userId: 'github-user-1', - expiresAt: new Date('2030-01-01T00:00:00Z'), - }, - isAdmin: true, - authConfigured: true, - adminAllowlistConfigured: true, - }; - const provider = createCloudflareProvider( - { - CRATE_GRAPHS: fakeBucket(new Map()), - PARSE_REQUESTS: fakeQueue(sent), - } as Env & { CRATE_GRAPHS: R2Bucket }, - new Request('https://codeview.codes/admin'), - ); - - const result = await provider.triggerParse('serde', '1.0.228', true); - if (result.isErr()) throw result.error; - expect(sent).toHaveLength(1); - expect(sent[0]).toMatchObject({ - schemaVersion: 1, - ecosystem: 'rust', - kind: 'crate', - name: 'serde', - version: '1.0.228', - force: true, - source: 'ui', - requestedBy: { - provider: 'github', - id: 'github-user-1', - login: 'themixednuts', - avatarUrl: 'https://example.com/avatar.png', - }, - }); - }); - - test('enqueues hosted sysroot parse requests for std crates', async () => { - const objects = new Map(); - const sent: unknown[] = []; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - PARSE_REQUESTS: fakeQueue(sent), - RATE_LIMIT_PARSE_ANON: fakeRateLimit(), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const result = await provider.triggerParse('std', 'nightly'); - if (result.isErr()) throw result.error; - expect(sent).toHaveLength(1); - expect(sent[0]).toMatchObject({ - schemaVersion: 1, - ecosystem: 'rust', - kind: 'sysroot', - name: 'std', - version: 'nightly', - force: false, - source: 'ui', - }); - }); - - test('queues std latest as stable hosted parse request', async () => { - const objects = new Map(); - const sent: unknown[] = []; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - PARSE_REQUESTS: fakeQueue(sent), - RATE_LIMIT_PARSE_ANON: fakeRateLimit(), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const result = await provider.triggerParse('std', 'latest'); - if (result.isErr()) throw result.error; - expect(sent).toHaveLength(1); - expect(sent[0]).toMatchObject({ - schemaVersion: 1, - ecosystem: 'rust', - kind: 'sysroot', - name: 'std', - version: 'stable', - force: false, - source: 'ui', - }); - }); - - test.each(['stable', 'beta'])('queues the %s hosted sysroot channel', async (channel) => { - const objects = new Map(); - const sent: unknown[] = []; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - PARSE_REQUESTS: fakeQueue(sent), - RATE_LIMIT_PARSE_ANON: fakeRateLimit(), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const result = await provider.triggerParse('std', channel); - if (result.isErr()) throw result.error; - expect(sent).toHaveLength(1); - expect(sent[0]).toMatchObject({ kind: 'sysroot', name: 'std', version: channel }); - }); - - test('rejects concrete versions for hosted sysroot parse requests', async () => { - const sent: unknown[] = []; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(new Map()), - PARSE_REQUESTS: fakeQueue(sent), - RATE_LIMIT_PARSE_ANON: fakeRateLimit(), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const result = await provider.triggerParse('std', '1.96.0'); - expect(result.isErr()).toBe(true); - if (!result.isErr()) throw new Error('expected concrete sysroot request to fail'); - expect(result.error._tag).toBe('NotAvailableError'); - expect(result.error.message).toContain('stable, beta, or nightly'); - expect(sent).toHaveLength(0); - }); - - test('queues hyphenated proc macro route as hosted std-library parse request', async () => { - const objects = new Map(); - const sent: unknown[] = []; - const provider = createCloudflareProvider({ - CRATE_GRAPHS: fakeBucket(objects), - PARSE_REQUESTS: fakeQueue(sent), - RATE_LIMIT_PARSE_ANON: fakeRateLimit(), - } as Env & { CRATE_GRAPHS: R2Bucket }); - - const result = await provider.triggerParse('proc-macro', 'nightly'); - if (result.isErr()) throw result.error; - expect(sent).toHaveLength(1); - expect(sent[0]).toMatchObject({ - schemaVersion: 1, - ecosystem: 'rust', - kind: 'sysroot', - name: 'proc-macro', - version: 'nightly', - force: false, - source: 'ui', - }); - }); +describe("createCloudflareProvider", () => { + afterEach(() => { + mockAuthState.value = null; + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + test("resolves published crates through canonical refs", async () => { + const objects = new Map([ + [ + "rust/_refs/proc_macro.json", + { + schemaVersion: 1, + storageName: "proc_macro", + displayName: "proc_macro", + aliases: { + latest: { + version: "1.98.0-nightly", + graphHash: "hash", + }, + }, + versions: [ + { + version: "1.98.0-nightly", + graphHash: "hash", + }, + ], + }, + ], + [ + "rust/proc_macro/1.98.0-nightly/site/meta.json", + hostedMeta(128, "1.98.0-nightly", {}, "proc_macro"), + ], + ]); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + } as unknown as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect(provider.getCrateStatus("proc-macro", "1.98.0-nightly")).resolves.toEqual({ + status: "ready", + }); + }); + + test("rejects stale ready status when no current artifact is published", async () => { + const objects = new Map([ + ["rust/_refs/demo.json", crateRefs()], + [ + "rust/demo/1.0.0/site/meta.json", + { + schema_version: 1, + name: "demo", + version: "1.0.0", + }, + ], + ]); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + PARSE_STATUS: fakeParseStatusNamespace({ + ecosystem: "rust", + kind: "crate", + name: "demo", + version: "1.0.0", + status: "ready", + createdAt: "2026-07-09T00:00:00.000Z", + updatedAt: "2026-07-09T00:00:00.000Z", + sequence: 1, + }), + } as unknown as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect(provider.getCrateStatus("demo", "1.0.0")).resolves.toEqual({ + status: "failed", + error: "No static graph is published for demo@1.0.0.", + action: "docs_unavailable", + }); + }); + + test("refreshes exact-version refs after a hosted artifact is replaced", async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-07-09T00:00:00.000Z")); + const name = "mutable-ref-demo"; + const version = "1.0.0"; + const refsKey = `rust/_refs/${name}.json`; + const metaKey = `rust/${name}/${version}/site/meta.json`; + const refs = (graphHash: string) => ({ + schemaVersion: 1, + storageName: name, + displayName: name, + aliases: { latest: { version, graphHash } }, + versions: [{ version, graphHash }], + }); + const objects = new Map([ + [refsKey, refs("old-hash")], + [metaKey, { schema_version: 1, name, version }], + ]); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect(provider.getCrateStatus(name, version)).resolves.toMatchObject({ + status: "failed", + }); + + objects.set(refsKey, refs("new-hash")); + objects.set(metaKey, hostedMeta(128, version, {}, name)); + vi.advanceTimersByTime(5_001); + + await expect(provider.getCrateStatus(name, version)).resolves.toEqual({ status: "ready" }); + }); + + test("does not assemble node views from base shards", async () => { + const prefix = "rust/demo/1.0.0"; + const nodeId = "demo"; + const objects = new Map([ + ["rust/_refs/demo.json", crateRefs()], + [`${prefix}/site/meta.json`, hostedMeta(128)], + ]); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + } as Env & { CRATE_GRAPHS: R2Bucket }); + const loadNodeViewDirect = provider.loadNodeViewDirect; + expect(loadNodeViewDirect).toBeDefined(); + if (!loadNodeViewDirect) throw new Error("loadNodeViewDirect missing"); + + await expect(loadNodeViewDirect("demo", "1.0.0", nodeId)).resolves.toBeNull(); + }); + + test("loads the complete materialized node view", async () => { + const version = "1.0.1"; + const prefix = `rust/demo/${version}`; + const nodeId = "demo"; + const objects = new Map([ + ["rust/_refs/demo.json", crateRefs(version)], + [`${prefix}/site/meta.json`, hostedMeta(128, version)], + hostedNodeViewArtifact(prefix, nodeId, version), + ]); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + } as Env & { CRATE_GRAPHS: R2Bucket }); + const loadNodeViewDirect = provider.loadNodeViewDirect; + expect(loadNodeViewDirect).toBeDefined(); + if (!loadNodeViewDirect) throw new Error("loadNodeViewDirect missing"); + + await expect(loadNodeViewDirect("demo", version, nodeId)).resolves.toMatchObject({ + detail: { + node: { + id: nodeId, + }, + edges: [], + relatedNodes: [], + }, + ancestors: [], + }); + }); + + test("filters hosted nodes by kind from hosted kind index", async () => { + const crateName = "kinddemo"; + const version = "1.0.0"; + const prefix = `rust/${crateName}/${version}`; + const nestedNodeId = `${crateName}::hidden::Widget`; + const objects = new Map([ + [`rust/_refs/${crateName}.json`, crateRefs(version, crateName)], + [`${prefix}/site/meta.json`, hostedMeta(128, version, { kindIndex: true }, crateName)], + [ + `${prefix}/site/kinds/Struct.json`, + { + schema_version: 2, + name: crateName, + version, + kind: "Struct", + entries: [ + { + id: nestedNodeId, + name: "Widget", + kind: "Struct", + visibility: { kind: "Public" }, + }, + ], + }, + ], + ]); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect( + provider.searchNodesDirect?.(crateName, version, "", 10, ["Struct"]), + ).resolves.toEqual([ + { + id: nestedNodeId, + name: "Widget", + kind: "Struct", + visibility: { kind: "Public" }, + }, + ]); + await expect( + provider.searchNodesDirect?.(crateName, version, "", 10, ["Impl"]), + ).resolves.toEqual([]); + }); + + test("uses live crates.io metadata for top crates", async () => { + vi.stubGlobal( + "fetch", + vi.fn( + async () => + new Response( + JSON.stringify({ + crates: [ + { + id: "rand_core", + name: "rand_core", + description: "Core random number generator traits", + repository: "https://github.com/rust-random/rand", + max_version: "0.9.3", + }, + ], + }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ), + ); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(new Map()), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect(provider.getTopCrates(1)).resolves.toEqual([ + { + id: "rand-core", + name: "rand_core", + version: "0.9.3", + description: "Core random number generator traits", + }, + ]); + }); + + test("uses live crates.io versions beyond parsed artifact refs", async () => { + const fetchMock = vi.fn(async (input: RequestInfo | URL) => { + expect(String(input)).toBe("https://index.crates.io/ha/sh/hashbrown"); + return new Response( + [ + JSON.stringify({ name: "hashbrown", vers: "0.16.1", yanked: false }), + JSON.stringify({ name: "hashbrown", vers: "0.17.0", yanked: false }), + JSON.stringify({ name: "hashbrown", vers: "0.17.1", yanked: false }), + "", + ].join("\n"), + { status: 200 }, + ); + }); + vi.stubGlobal("fetch", fetchMock); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket( + new Map([ + [ + "rust/_refs/hashbrown.json", + { + schemaVersion: 1, + storageName: "hashbrown", + displayName: "hashbrown", + aliases: { + latest: { + version: "0.17.1", + graphHash: "hash-0.17.1", + }, + }, + versions: [ + { + version: "0.17.1", + graphHash: "hash-0.17.1", + }, + ], + }, + ], + ]), + ), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect(provider.getCrateVersions("hashbrown", 5)).resolves.toEqual([ + "0.17.1", + "0.17.0", + "0.16.1", + ]); + await expect(provider.resolveVersion("hashbrown", "latest")).resolves.toBe("0.17.1"); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + test("lists toolchain channels before concrete published versions", async () => { + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket( + new Map([ + [ + "rust/_refs/std.json", + { + schemaVersion: 1, + storageName: "std", + displayName: "std", + aliases: { + nightly: { version: "1.98.0-nightly", graphHash: "hash-nightly" }, + }, + versions: [{ version: "1.98.0-nightly", graphHash: "hash-nightly" }], + }, + ], + ]), + ), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect(provider.getCrateVersions("std")).resolves.toEqual([ + "stable", + "beta", + "nightly", + "1.98.0-nightly", + ]); + }); + + test("searches exact toolchain crate channels independently of crates.io", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(JSON.stringify({ crates: [] }), { status: 200 })), + ); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(new Map()), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect(provider.searchRegistry("std@nightly")).resolves.toMatchObject([ + { id: "std", name: "std", version: "nightly" }, + ]); + }); + + test("includes active GitHub parse workflow runs in queue snapshots", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input)); + const status = url.searchParams.get("status"); + return new Response( + JSON.stringify({ + workflow_runs: + status === "in_progress" + ? [ + { + id: 123, + name: "parse", + display_title: "parse hashbrown 0.17.1", + status: "in_progress", + event: "workflow_dispatch", + head_branch: "main", + html_url: "https://github.com/themixednuts/codeview/actions/runs/123", + created_at: "2026-07-07T12:00:00Z", + updated_at: "2026-07-07T12:05:00Z", + }, + ] + : [], + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }), + ); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(new Map()), + GITHUB_REPO: "themixednuts/codeview", + GITHUB_WORKFLOW_FILE: "parse.yml", + } as Env & { CRATE_GRAPHS: R2Bucket }); + + await expect(provider.getParseQueue?.(10)).resolves.toMatchObject({ + active: [], + activeRuns: [ + { + id: "123", + title: "parse hashbrown 0.17.1", + status: "in_progress", + event: "workflow_dispatch", + branch: "main", + url: "https://github.com/themixednuts/codeview/actions/runs/123", + }, + ], + recent: [], + planned: null, + }); + }); + + test("keeps current plan items visible when an older status row has the same crate version", async () => { + const objects = new Map([ + [ + "rust/_runs/run-1/plan.json", + { + run_id: "run-1", + generated_at: "2026-07-28T06:00:00Z", + mode: "daily", + shard_count: 8, + work: [ + { + work_id: "crate:demo:1.0.0:default", + kind: "crate", + name: "demo", + version: "1.0.0", + channel: "default", + priority_tier: "top-download-stale", + reason: "parser old0000 → target123", + download_rank: 1, + }, + ], + }, + ], + [ + "rust/_index/by-version/demo/1.0.0.json", + { + name: "demo", + version: "1.0.0", + parsedAt: "2026-07-28T06:10:00Z", + parserRevision: "target1234567890", + schemaVersion: 1, + }, + ], + ]); + const oldStatus = { + ecosystem: "rust", + kind: "crate", + name: "demo", + version: "1.0.0", + status: "ready", + createdAt: "2026-07-01T00:00:00Z", + updatedAt: "2026-07-01T00:05:00Z", + sequence: 1, + }; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + PARSE_STATUS: fakeParseStatusNamespace(null, [], { + active: [], + recent: [oldStatus], + }), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const snapshot = await provider.getParseQueue?.(100); + + expect(snapshot?.planned).toMatchObject({ + runId: "run-1", + pending: 0, + ready: 1, + items: [ + { + name: "demo", + version: "1.0.0", + state: "ready", + }, + ], + }); + }); + + test("builds admin dashboard allowance from GitHub active runs and billing", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input)); + if (url.pathname === "/repos/themixednuts/codeview") { + return new Response( + JSON.stringify({ + full_name: "themixednuts/codeview", + private: true, + owner: { login: "themixednuts", type: "User" }, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + } + if (url.pathname === "/users/themixednuts/settings/billing/usage/summary") { + expect(url.searchParams.get("product")).toBe("Actions"); + expect(url.searchParams.get("repository")).toBe("themixednuts/codeview"); + return new Response( + JSON.stringify({ + usageItems: [ + { + product: "Actions", + sku: "actions_linux", + unitType: "minutes", + grossQuantity: 125, + netQuantity: 12, + }, + { + product: "Codespaces", + sku: "codespaces_compute", + unitType: "hours", + grossQuantity: 10, + }, + ], + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + } + if (url.pathname === "/repos/themixednuts/codeview/actions/workflows/parse.yml/runs") { + if (url.searchParams.has("created")) { + return new Response( + JSON.stringify({ + workflow_runs: [ + { + id: 321, + status: "completed", + created_at: "2026-07-07T12:00:00Z", + updated_at: "2026-07-07T12:30:00Z", + }, + ], + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + } + return new Response( + JSON.stringify({ + workflow_runs: + url.searchParams.get("status") === "in_progress" + ? [ + { + id: 123, + name: "parse", + display_title: "parse bitflags 2.13.0", + status: "in_progress", + event: "workflow_dispatch", + head_branch: "main", + html_url: "https://github.com/themixednuts/codeview/actions/runs/123", + created_at: "2026-07-07T12:00:00Z", + updated_at: "2026-07-07T12:05:00Z", + }, + ] + : [], + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + } + return new Response("{}", { status: 404 }); + }), + ); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(new Map()), + GITHUB_REPO: "themixednuts/codeview", + GITHUB_WORKFLOW_FILE: "parse.yml", + GITHUB_TOKEN: "token", + PLAN_DRAIN_ACTIVE_TARGET: "4", + PLAN_DRAIN_BATCH_SIZE: "2", + GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT: "35", + } as unknown as Env & { CRATE_GRAPHS: R2Bucket }); + + const dashboard = await provider.getAdminDashboard?.(10); + + expect(dashboard?.allowance).toMatchObject({ + repo: "themixednuts/codeview", + activeTarget: 4, + batchSize: 2, + trackedActiveCount: 0, + githubActiveRunCount: 1, + actionsInUse: 1, + availableSlots: 3, + repoUsageTargetPercent: 35, + repoPrivate: true, + standardRunnerMinutesMetered: true, + estimatedRepoMinutesThisMonth: 30, + billing: { + available: true, + totalMinutesUsed: 125, + totalPaidMinutesUsed: 12, + }, + }); + }); + + test("treats PLAN_DRAIN_BATCH_SIZE=0 as planned siphon disabled", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input)); + if (url.pathname === "/repos/themixednuts/codeview") { + return new Response( + JSON.stringify({ + full_name: "themixednuts/codeview", + private: false, + owner: { login: "themixednuts", type: "User" }, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + } + if (url.pathname === "/repos/themixednuts/codeview/actions/workflows/parse.yml/runs") { + return new Response(JSON.stringify({ workflow_runs: [], total_count: 0 }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + } + return new Response("{}", { status: 404 }); + }), + ); + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(new Map()), + GITHUB_REPO: "themixednuts/codeview", + GITHUB_WORKFLOW_FILE: "parse.yml", + GITHUB_TOKEN: "token", + PLAN_DRAIN_ACTIVE_TARGET: "4", + PLAN_DRAIN_BATCH_SIZE: "0", + } as unknown as Env & { CRATE_GRAPHS: R2Bucket }); + + const dashboard = await provider.getAdminDashboard?.(10); + + expect(dashboard?.allowance).toMatchObject({ + activeTarget: 4, + batchSize: 0, + availableSlots: 4, + }); + }); + + test("enqueues hosted parse requests", async () => { + const objects = new Map(); + const sent: unknown[] = []; + const registrations: unknown[] = []; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + PARSE_REQUESTS: fakeQueue(sent), + PARSE_STATUS: fakeParseStatusNamespace(null, registrations), + RATE_LIMIT_PARSE_ANON: fakeRateLimit(), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const result = await provider.triggerParse("serde", "1.0.228"); + if (result.isErr()) throw result.error; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + schemaVersion: 1, + ecosystem: "rust", + kind: "crate", + name: "serde", + version: "1.0.228", + force: false, + source: "ui", + }); + expect(registrations).toHaveLength(1); + expect(registrations[0]).toMatchObject({ + kind: "crate", + name: "serde", + version: "1.0.228", + }); + + await expect(provider.getCrateStatus("serde", "1.0.228")).resolves.toEqual({ + status: "processing", + step: "queued", + error: undefined, + action: undefined, + installedVersion: undefined, + }); + await expect(provider.getProcessingCrates(5)).resolves.toEqual([ + { + id: "serde", + name: "serde", + version: "1.0.228", + description: "queued", + }, + ]); + }); + + test("fails closed when hosted parse rate limiting is missing", async () => { + const sent: unknown[] = []; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(new Map()), + PARSE_REQUESTS: fakeQueue(sent), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const result = await provider.triggerParse("serde", "1.0.228"); + expect(result.isErr()).toBe(true); + if (!result.isErr()) throw new Error("expected parse request to fail"); + expect(result.error._tag).toBe("NotAvailableError"); + expect(result.error.message).toBe("Hosted parse rate limiting is not configured"); + expect(sent).toHaveLength(0); + }); + + test("requires admin auth for forced hosted parses", async () => { + const sent: unknown[] = []; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(new Map()), + PARSE_REQUESTS: fakeQueue(sent), + RATE_LIMIT_PARSE_ANON: fakeRateLimit(), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const result = await provider.triggerParse("serde", "1.0.228", true); + expect(result.isErr()).toBe(true); + if (!result.isErr()) throw new Error("expected force parse request to fail"); + expect(result.error._tag).toBe("NotAvailableError"); + expect(result.error.message).toBe("Force parse requires admin access"); + expect(sent).toHaveLength(0); + }); + + test("lets admin force parses bypass parse rate limiting", async () => { + const sent: unknown[] = []; + mockAuthState.value = { + user: { + id: "github-user-1", + name: "Admin", + email: "admin@example.com", + emailVerified: true, + githubLogin: "themixednuts", + image: "https://example.com/avatar.png", + }, + session: { + id: "session-1", + userId: "github-user-1", + expiresAt: new Date("2030-01-01T00:00:00Z"), + }, + isAdmin: true, + authConfigured: true, + adminAllowlistConfigured: true, + }; + const provider = createCloudflareProvider( + { + CRATE_GRAPHS: fakeBucket(new Map()), + PARSE_REQUESTS: fakeQueue(sent), + } as Env & { CRATE_GRAPHS: R2Bucket }, + new Request("https://codeview.codes/admin"), + ); + + const result = await provider.triggerParse("serde", "1.0.228", true); + if (result.isErr()) throw result.error; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + schemaVersion: 1, + ecosystem: "rust", + kind: "crate", + name: "serde", + version: "1.0.228", + force: true, + source: "ui", + requestedBy: { + provider: "github", + id: "github-user-1", + login: "themixednuts", + avatarUrl: "https://example.com/avatar.png", + }, + }); + }); + + test("enqueues hosted sysroot parse requests for std crates", async () => { + const objects = new Map(); + const sent: unknown[] = []; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + PARSE_REQUESTS: fakeQueue(sent), + RATE_LIMIT_PARSE_ANON: fakeRateLimit(), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const result = await provider.triggerParse("std", "nightly"); + if (result.isErr()) throw result.error; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + schemaVersion: 1, + ecosystem: "rust", + kind: "sysroot", + name: "std", + version: "nightly", + force: false, + source: "ui", + }); + }); + + test("queues std latest as stable hosted parse request", async () => { + const objects = new Map(); + const sent: unknown[] = []; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + PARSE_REQUESTS: fakeQueue(sent), + RATE_LIMIT_PARSE_ANON: fakeRateLimit(), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const result = await provider.triggerParse("std", "latest"); + if (result.isErr()) throw result.error; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + schemaVersion: 1, + ecosystem: "rust", + kind: "sysroot", + name: "std", + version: "stable", + force: false, + source: "ui", + }); + }); + + test.each(["stable", "beta"])("queues the %s hosted sysroot channel", async (channel) => { + const objects = new Map(); + const sent: unknown[] = []; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + PARSE_REQUESTS: fakeQueue(sent), + RATE_LIMIT_PARSE_ANON: fakeRateLimit(), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const result = await provider.triggerParse("std", channel); + if (result.isErr()) throw result.error; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ kind: "sysroot", name: "std", version: channel }); + }); + + test("rejects concrete versions for hosted sysroot parse requests", async () => { + const sent: unknown[] = []; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(new Map()), + PARSE_REQUESTS: fakeQueue(sent), + RATE_LIMIT_PARSE_ANON: fakeRateLimit(), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const result = await provider.triggerParse("std", "1.96.0"); + expect(result.isErr()).toBe(true); + if (!result.isErr()) throw new Error("expected concrete sysroot request to fail"); + expect(result.error._tag).toBe("NotAvailableError"); + expect(result.error.message).toContain("stable, beta, or nightly"); + expect(sent).toHaveLength(0); + }); + + test("queues hyphenated proc macro route as hosted std-library parse request", async () => { + const objects = new Map(); + const sent: unknown[] = []; + const provider = createCloudflareProvider({ + CRATE_GRAPHS: fakeBucket(objects), + PARSE_REQUESTS: fakeQueue(sent), + RATE_LIMIT_PARSE_ANON: fakeRateLimit(), + } as Env & { CRATE_GRAPHS: R2Bucket }); + + const result = await provider.triggerParse("proc-macro", "nightly"); + if (result.isErr()) throw result.error; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + schemaVersion: 1, + ecosystem: "rust", + kind: "sysroot", + name: "proc-macro", + version: "nightly", + force: false, + source: "ui", + }); + }); }); diff --git a/codeview-ui/src/lib/server/cloudflare/provider.ts b/codeview-ui/src/lib/server/cloudflare/provider.ts index f937589..e3655ba 100644 --- a/codeview-ui/src/lib/server/cloudflare/provider.ts +++ b/codeview-ui/src/lib/server/cloudflare/provider.ts @@ -1,270 +1,270 @@ -import { Result } from 'better-result'; -import * as Cache from 'effect/Cache'; -import * as Duration from 'effect/Duration'; -import * as Effect from 'effect/Effect'; -import * as Exit from 'effect/Exit'; -import * as Schema from 'effect/Schema'; -import type { RequestEvent } from '@sveltejs/kit'; -import type { CrateGraph, Edge, Node, NodeKind } from '#lib/graph'; +import { Result } from "better-result"; +import * as Cache from "effect/Cache"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Schema from "effect/Schema"; +import type { RequestEvent } from "@sveltejs/kit"; +import type { CrateGraph, Edge, Node, NodeKind } from "#lib/graph"; import type { - CrateIndex, - CrateTree, - NodeDetail, - NodeSummary, - NodeViewBase, - StaticCrateCatalog, - StaticSearchManifest, - StaticSearchShard, - TreeNodeDTO, -} from '#lib/schema'; -import { STATIC_ARTIFACT_SCHEMA_VERSION } from '#lib/schema'; + CrateIndex, + CrateTree, + NodeDetail, + NodeSummary, + NodeViewBase, + StaticCrateCatalog, + StaticSearchManifest, + StaticSearchShard, + TreeNodeDTO, +} from "#lib/schema"; +import { STATIC_ARTIFACT_SCHEMA_VERSION } from "#lib/schema"; import { - HOSTED_ARTIFACT_CACHE_NAMESPACE, - isCurrentHostedArtifactMetadata, -} from '#lib/hosted-contract'; -import type { CrateMapData, CrateMapOptions } from '#lib/graph/crate-map'; + HOSTED_ARTIFACT_CACHE_NAMESPACE, + isCurrentHostedArtifactMetadata, +} from "#lib/hosted-contract"; +import type { CrateMapData, CrateMapOptions } from "#lib/graph/crate-map"; import { - DEFAULT_RUST_CHANNEL, - RUST_CHANNEL_ORDER, - isRustChannel, - isStdCrate, - isStdJsonCrate, - searchToolchainCrates, -} from '#lib/std'; + DEFAULT_RUST_CHANNEL, + RUST_CHANNEL_ORDER, + isRustChannel, + isStdCrate, + isStdJsonCrate, + searchToolchainCrates, +} from "#lib/std"; import type { - CrateSummaryResult, - CrossEdgeData, - DataProvider, - AdminDashboardData, - ActiveParseRun, - GitHubActionsBillingSummary, - ParseQueueAllowance, - ParseQueueEntry, - ParseQueueSnapshot, - PlannedParseItem, - PlannedParseRun, -} from '../provider'; -import { getRegistry } from '../registry/index'; -import { fetchSourceFileFromArchive } from '../parser/archive'; -import { getSourceAdapter } from '../sources/index'; -import { fetchSourcesWithProviders } from '../sources/runner'; -import { NotAvailableError, RateLimitError, ValidationError } from '../errors'; + CrateSummaryResult, + CrossEdgeData, + DataProvider, + AdminDashboardData, + ActiveParseRun, + GitHubActionsBillingSummary, + ParseQueueAllowance, + ParseQueueEntry, + ParseQueueSnapshot, + PlannedParseItem, + PlannedParseRun, +} from "../provider"; +import { getRegistry } from "../registry/index"; +import { fetchSourceFileFromArchive } from "../parser/archive"; +import { getSourceAdapter } from "../sources/index"; +import { fetchSourcesWithProviders } from "../sources/runner"; +import { NotAvailableError, RateLimitError, ValidationError } from "../errors"; import { - crateNameVariants, - hyphenateCrateName, - isValidCrateName, - isValidVersion, - normalizeCrateName, -} from '../validation'; -import { getLogger } from '#lib/log'; -import { actorFromUser, getAuthStateFromRequest } from '../auth'; + crateNameVariants, + hyphenateCrateName, + isValidCrateName, + isValidVersion, + normalizeCrateName, +} from "../validation"; +import { getLogger } from "#lib/log"; +import { actorFromUser, getAuthStateFromRequest } from "../auth"; import { - makeParseRequest, - parseStatusObject, - parseWorkflowId, - registerQueuedParseRequest, - type ParseRequestMessage, - type ParseStatusEvent, - type ParseQueueSnapshot as StoredParseQueueSnapshot, - type StoredParseStatus, -} from './parse-contract'; + makeParseRequest, + parseStatusObject, + parseWorkflowId, + registerQueuedParseRequest, + type ParseRequestMessage, + type ParseStatusEvent, + type ParseQueueSnapshot as StoredParseQueueSnapshot, + type StoredParseStatus, +} from "./parse-contract"; import { - USER_AGENT, - SOURCE_MAX_BYTES, - source, - fetchStdSourceFile, - type SourceProviderMode, -} from '../provider-utils'; -import type { PackageMetadata } from '../registry/types'; -import { orderCatalogSummaries } from './catalog'; -import { mergeTraitMemberDocumentation } from '#lib/trait-member-hydration'; - -const log = getLogger('cloudflare'); + USER_AGENT, + SOURCE_MAX_BYTES, + source, + fetchStdSourceFile, + type SourceProviderMode, +} from "../provider-utils"; +import type { PackageMetadata } from "../registry/types"; +import { orderCatalogSummaries } from "./catalog"; +import { mergeTraitMemberDocumentation } from "#lib/trait-member-hydration"; + +const log = getLogger("cloudflare"); type AppEnv = Env & { - CRATE_GRAPHS: R2Bucket; - PARSE_REQUESTS?: Queue; - PARSE_STATUS?: DurableObjectNamespace; - RATE_LIMIT_API?: RateLimit; - RATE_LIMIT_API_ANON?: RateLimit; - RATE_LIMIT_API_AUTH?: RateLimit; - RATE_LIMIT_PARSE_ANON?: RateLimit; - RATE_LIMIT_PARSE_AUTH?: RateLimit; - AUTH_DB?: D1Database; - BETTER_AUTH_SECRET?: string; - BETTER_AUTH_URL?: string; - GITHUB_OAUTH_CLIENT_ID?: string; - GITHUB_OAUTH_CLIENT_SECRET?: string; - GITHUB_ADMIN_LOGINS?: string; - GITHUB_REPO?: string; - GITHUB_REF?: string; - GITHUB_WORKFLOW_FILE?: string; - GITHUB_TOKEN?: string; - PLAN_DRAIN_ACTIVE_TARGET?: string; - PLAN_DRAIN_BATCH_SIZE?: string; - GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT?: string; + CRATE_GRAPHS: R2Bucket; + PARSE_REQUESTS?: Queue; + PARSE_STATUS?: DurableObjectNamespace; + RATE_LIMIT_API?: RateLimit; + RATE_LIMIT_API_ANON?: RateLimit; + RATE_LIMIT_API_AUTH?: RateLimit; + RATE_LIMIT_PARSE_ANON?: RateLimit; + RATE_LIMIT_PARSE_AUTH?: RateLimit; + AUTH_DB?: D1Database; + BETTER_AUTH_SECRET?: string; + BETTER_AUTH_URL?: string; + GITHUB_OAUTH_CLIENT_ID?: string; + GITHUB_OAUTH_CLIENT_SECRET?: string; + GITHUB_ADMIN_LOGINS?: string; + GITHUB_REPO?: string; + GITHUB_REF?: string; + GITHUB_WORKFLOW_FILE?: string; + GITHUB_TOKEN?: string; + PLAN_DRAIN_ACTIVE_TARGET?: string; + PLAN_DRAIN_BATCH_SIZE?: string; + GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT?: string; }; type SearchEntry = NodeSummary & { score?: number }; -const DEFAULT_GITHUB_WORKFLOW_FILE = 'parse.yml'; +const DEFAULT_GITHUB_WORKFLOW_FILE = "parse.yml"; const DEFAULT_PLAN_DRAIN_ACTIVE_TARGET = 4; /** 0 = planned siphon disabled; shards own daily plan work. */ const DEFAULT_PLAN_DRAIN_BATCH_SIZE = 0; const DEFAULT_GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT = 35; -const GITHUB_API_VERSION = '2026-03-10'; +const GITHUB_API_VERSION = "2026-03-10"; const ACTIVE_GITHUB_RUN_STATUSES = [ - 'queued', - 'pending', - 'in_progress', - 'waiting', - 'requested', + "queued", + "pending", + "in_progress", + "waiting", + "requested", ] as const; type GitHubWorkflowRun = { - id?: number; - name?: string; - display_title?: string; - status?: string; - event?: string; - head_branch?: string; - html_url?: string; - created_at?: string; - updated_at?: string; + id?: number; + name?: string; + display_title?: string; + status?: string; + event?: string; + head_branch?: string; + html_url?: string; + created_at?: string; + updated_at?: string; }; type GitHubWorkflowRunsResponse = { - workflow_runs?: GitHubWorkflowRun[]; + workflow_runs?: GitHubWorkflowRun[]; }; type GitHubRepositoryResponse = { - full_name?: string; - private?: boolean; - owner?: { - login?: string; - type?: string; - }; + full_name?: string; + private?: boolean; + owner?: { + login?: string; + type?: string; + }; }; type GitHubBillingUsageItem = { - product?: string; - sku?: string; - unitType?: string; - grossQuantity?: number; - discountQuantity?: number; - quantity?: number; - netQuantity?: number; - grossAmount?: number; - discountAmount?: number; - netAmount?: number; + product?: string; + sku?: string; + unitType?: string; + grossQuantity?: number; + discountQuantity?: number; + quantity?: number; + netQuantity?: number; + grossAmount?: number; + discountAmount?: number; + netAmount?: number; }; type GitHubBillingUsageSummaryResponse = { - usageItems?: GitHubBillingUsageItem[]; + usageItems?: GitHubBillingUsageItem[]; }; function parsePositiveInteger(value: string | undefined, fallback: number): number { - if (value === undefined || value.trim() === '') return fallback; - const parsed = Number(value); - return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback; + if (value === undefined || value.trim() === "") return fallback; + const parsed = Number(value); + return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback; } /** Allows 0 so planned siphon can be disabled via PLAN_DRAIN_BATCH_SIZE=0. */ function parseNonNegativeInteger(value: string | undefined, fallback: number): number { - if (value === undefined || value.trim() === '') return fallback; - const parsed = Number(value); - return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : fallback; + if (value === undefined || value.trim() === "") return fallback; + const parsed = Number(value); + return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : fallback; } function parsePositiveNumber(value: string | undefined, fallback: number): number { - if (value === undefined || value.trim() === '') return fallback; - const parsed = Number(value); - return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; + if (value === undefined || value.trim() === "") return fallback; + const parsed = Number(value); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; } function monthStartIso(now = new Date()): string { - return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(); + return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(); } function finiteNumber(value: unknown): number | null { - return typeof value === 'number' && Number.isFinite(value) ? value : null; + return typeof value === "number" && Number.isFinite(value) ? value : null; } function githubGrossUsageQuantity(item: GitHubBillingUsageItem): number { - return finiteNumber(item.grossQuantity) ?? finiteNumber(item.quantity) ?? 0; + return finiteNumber(item.grossQuantity) ?? finiteNumber(item.quantity) ?? 0; } function githubNetUsageQuantity(item: GitHubBillingUsageItem): number { - return finiteNumber(item.netQuantity) ?? 0; + return finiteNumber(item.netQuantity) ?? 0; } function isActionsMinuteUsage(item: GitHubBillingUsageItem): boolean { - const product = (item.product ?? '').toLowerCase(); - const sku = (item.sku ?? '').toLowerCase(); - const unitType = (item.unitType ?? '').toLowerCase(); - return (product.includes('actions') || sku.includes('actions')) && unitType.includes('minute'); + const product = (item.product ?? "").toLowerCase(); + const sku = (item.sku ?? "").toLowerCase(); + const unitType = (item.unitType ?? "").toLowerCase(); + return (product.includes("actions") || sku.includes("actions")) && unitType.includes("minute"); } function totalGrossActionsMinutes(body: GitHubBillingUsageSummaryResponse): number { - return (body.usageItems ?? []) - .filter(isActionsMinuteUsage) - .reduce((total, item) => total + githubGrossUsageQuantity(item), 0); + return (body.usageItems ?? []) + .filter(isActionsMinuteUsage) + .reduce((total, item) => total + githubGrossUsageQuantity(item), 0); } function totalBillableActionsMinutes(body: GitHubBillingUsageSummaryResponse): number { - return (body.usageItems ?? []) - .filter(isActionsMinuteUsage) - .reduce((total, item) => total + githubNetUsageQuantity(item), 0); + return (body.usageItems ?? []) + .filter(isActionsMinuteUsage) + .reduce((total, item) => total + githubNetUsageQuantity(item), 0); } function registrySummary(result: PackageMetadata): CrateSummaryResult { - return { - id: hyphenateCrateName(result.name), - name: result.name, - version: result.version, - description: result.description, - }; + return { + id: hyphenateCrateName(result.name), + name: result.name, + version: result.version, + description: result.description, + }; } -class R2ReadError extends Schema.TaggedErrorClass()('R2ReadError', { - key: Schema.String, - cause: Schema.Defect(), - message: Schema.String, +class R2ReadError extends Schema.TaggedError()("R2ReadError", { + key: Schema.String, + cause: Schema.Defect(), + message: Schema.String, }) {} -class R2DecodeError extends Schema.TaggedErrorClass()('R2DecodeError', { - key: Schema.String, - cause: Schema.Defect(), - message: Schema.String, +class R2DecodeError extends Schema.TaggedError()("R2DecodeError", { + key: Schema.String, + cause: Schema.Defect(), + message: Schema.String, }) {} -class R2ParseError extends Schema.TaggedErrorClass()('R2ParseError', { - key: Schema.String, - cause: Schema.Defect(), - message: Schema.String, +class R2ParseError extends Schema.TaggedError()("R2ParseError", { + key: Schema.String, + cause: Schema.Defect(), + message: Schema.String, }) {} type R2JsonError = R2ReadError | R2DecodeError | R2ParseError; function errorMessage(cause: unknown): string { - return cause instanceof Error ? cause.message : String(cause); + return cause instanceof Error ? cause.message : String(cause); } /** Build a GitHub file URL from package metadata, or null if repo info unavailable. */ function buildGitHubFileUrl(metadata: PackageMetadata, filePath: string): string | null { - const repoUrl = metadata.repositoryUrl; - if (!repoUrl) return null; - try { - const url = new URL(repoUrl); - if (!url.hostname.includes('github.com')) return null; - const path = url.pathname.replace(/\.git$/, '').replace(/\/+$/, ''); - const normalizedFile = filePath.replace(/\\/g, '/').replace(/^\.\//, ''); - return `https://github.com${path}/blob/v${metadata.version}/${normalizedFile}`; - } catch { - return null; - } + const repoUrl = metadata.repositoryUrl; + if (!repoUrl) return null; + try { + const url = new URL(repoUrl); + if (!url.hostname.includes("github.com")) return null; + const path = url.pathname.replace(/\.git$/, "").replace(/\/+$/, ""); + const normalizedFile = filePath.replace(/\\/g, "/").replace(/^\.\//, ""); + return `https://github.com${path}/blob/v${metadata.version}/${normalizedFile}`; + } catch { + return null; + } } -const VERSION_ALIAS_VALUES = ['latest', 'stable', 'beta', 'nightly'] as const; +const VERSION_ALIAS_VALUES = ["latest", "stable", "beta", "nightly"] as const; type VersionAlias = (typeof VERSION_ALIAS_VALUES)[number]; const VERSION_ALIASES = new Set(VERSION_ALIAS_VALUES); const REF_TTL_MS = 5_000; @@ -272,200 +272,200 @@ const MUTABLE_JSON_TTL_MS = 30_000; const REF_CACHE_MAX = 512; const JSON_CACHE_MAX = 128; const ARTIFACT_JSON_CACHE_MAX = 256; -const IMMUTABLE_ARTIFACT_CACHE_CONTROL = 'public, max-age=31536000, immutable'; +const IMMUTABLE_ARTIFACT_CACHE_CONTROL = "public, max-age=31536000, immutable"; const HOSTED_SYSROOT_UNAVAILABLE_MESSAGE = - 'Choose stable, beta, or nightly for std/core/alloc/proc_macro/test.'; + "Choose stable, beta, or nightly for std/core/alloc/proc_macro/test."; function uniqueCrateNameVariants(name: string): string[] { - return [...new Set(crateNameVariants(name))]; + return [...new Set(crateNameVariants(name))]; } type ArtifactRef = { - storageName: string; - version: string; - graphHash?: string; + storageName: string; + version: string; + graphHash?: string; }; type CrateRefTarget = { - version: string; - graphHash: string; + version: string; + graphHash: string; }; type CrateRefVersion = CrateRefTarget & { - parsedAt?: string; - nodes?: number; - edges?: number; + parsedAt?: string; + nodes?: number; + edges?: number; }; type CrateRefFile = { - schemaVersion?: number; - storageName: string; - displayName?: string; - aliases: Partial>; - versions: CrateRefVersion[]; + schemaVersion?: number; + storageName: string; + displayName?: string; + aliases: Partial>; + versions: CrateRefVersion[]; }; type WorkPlanArtifact = { - run_id?: string; - runId?: string; - generated_at?: string; - generatedAt?: string; - mode?: string; - shard_count?: number; - shardCount?: number; - work?: Array<{ - work_id?: string; - workId?: string; - kind?: string; - name?: string; - version?: string; - channel?: string; - priority_tier?: string; - priorityTier?: string; - download_rank?: number; - downloadRank?: number; - reason?: string; - }>; + run_id?: string; + runId?: string; + generated_at?: string; + generatedAt?: string; + mode?: string; + shard_count?: number; + shardCount?: number; + work?: Array<{ + work_id?: string; + workId?: string; + kind?: string; + name?: string; + version?: string; + channel?: string; + priority_tier?: string; + priorityTier?: string; + download_rank?: number; + downloadRank?: number; + reason?: string; + }>; }; type FreshnessEntry = { - version?: string; - parsedAt?: string; - parserRevision?: string; - schemaVersion?: number; + version?: string; + parsedAt?: string; + parserRevision?: string; + schemaVersion?: number; }; type PlanKeyCandidate = { - key: string; - uploaded?: string; + key: string; + uploaded?: string; }; type ResolvedRefCacheEntry = { - value: Promise; - expiresAt: number | null; + value: Promise; + expiresAt: number | null; }; const resolvedRefCache = new Map(); function artifactPrefix(name: string, version: string): string { - return `rust/${name}/${version}`; + return `rust/${name}/${version}`; } function refsKey(storageName: string): string { - return `rust/_refs/${storageName}.json`; + return `rust/_refs/${storageName}.json`; } function isObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); + return typeof value === "object" && value !== null && !Array.isArray(value); } function parseCrateRefTarget(value: unknown): CrateRefTarget | null { - if (!isObject(value)) return null; - const { version, graphHash } = value; - if (typeof version !== 'string' || version.length === 0) return null; - if (typeof graphHash !== 'string' || graphHash.length === 0) return null; - return { version, graphHash }; + if (!isObject(value)) return null; + const { version, graphHash } = value; + if (typeof version !== "string" || version.length === 0) return null; + if (typeof graphHash !== "string" || graphHash.length === 0) return null; + return { version, graphHash }; } function parseCrateRefs(value: unknown): CrateRefFile | null { - if (!isObject(value)) return null; - const storageName = value.storageName; - const aliases = value.aliases; - const versions = value.versions; - if (typeof storageName !== 'string' || storageName.length === 0) return null; - if (!isObject(aliases) || !Array.isArray(versions)) return null; - - const parsedAliases: CrateRefFile['aliases'] = {}; - for (const alias of VERSION_ALIAS_VALUES) { - const target = parseCrateRefTarget(aliases[alias]); - if (target) parsedAliases[alias] = target; - } - - const parsedVersions = versions - .map((entry): CrateRefVersion | null => { - const target = parseCrateRefTarget(entry); - if (!target) return null; - return isObject(entry) - ? { - ...target, - parsedAt: typeof entry.parsedAt === 'string' ? entry.parsedAt : undefined, - nodes: typeof entry.nodes === 'number' ? entry.nodes : undefined, - edges: typeof entry.edges === 'number' ? entry.edges : undefined, - } - : target; - }) - .filter((entry): entry is CrateRefVersion => entry !== null); - - if (parsedVersions.length === 0) return null; - return { - schemaVersion: typeof value.schemaVersion === 'number' ? value.schemaVersion : undefined, - storageName, - displayName: typeof value.displayName === 'string' ? value.displayName : undefined, - aliases: parsedAliases, - versions: parsedVersions, - }; + if (!isObject(value)) return null; + const storageName = value.storageName; + const aliases = value.aliases; + const versions = value.versions; + if (typeof storageName !== "string" || storageName.length === 0) return null; + if (!isObject(aliases) || !Array.isArray(versions)) return null; + + const parsedAliases: CrateRefFile["aliases"] = {}; + for (const alias of VERSION_ALIAS_VALUES) { + const target = parseCrateRefTarget(aliases[alias]); + if (target) parsedAliases[alias] = target; + } + + const parsedVersions = versions + .map((entry): CrateRefVersion | null => { + const target = parseCrateRefTarget(entry); + if (!target) return null; + return isObject(entry) + ? { + ...target, + parsedAt: typeof entry.parsedAt === "string" ? entry.parsedAt : undefined, + nodes: typeof entry.nodes === "number" ? entry.nodes : undefined, + edges: typeof entry.edges === "number" ? entry.edges : undefined, + } + : target; + }) + .filter((entry): entry is CrateRefVersion => entry !== null); + + if (parsedVersions.length === 0) return null; + return { + schemaVersion: typeof value.schemaVersion === "number" ? value.schemaVersion : undefined, + storageName, + displayName: typeof value.displayName === "string" ? value.displayName : undefined, + aliases: parsedAliases, + versions: parsedVersions, + }; } function resolveRefFromRefs(refs: CrateRefFile, versionOrAlias: string): ArtifactRef | null { - const target = VERSION_ALIASES.has(versionOrAlias) - ? refs.aliases[versionOrAlias as VersionAlias] - : refs.versions.find((entry) => entry.version === versionOrAlias); - if (!target) return null; - return { - storageName: refs.storageName, - version: target.version, - graphHash: target.graphHash, - }; + const target = VERSION_ALIASES.has(versionOrAlias) + ? refs.aliases[versionOrAlias as VersionAlias] + : refs.versions.find((entry) => entry.version === versionOrAlias); + if (!target) return null; + return { + storageName: refs.storageName, + version: target.version, + graphHash: target.graphHash, + }; } function resolvedRefCacheKey(name: string, version: string): string { - return `${normalizeCrateName(name)}@${version}`; + return `${normalizeCrateName(name)}@${version}`; } function getCachedResolvedRef(key: string): Promise | null { - const cached = resolvedRefCache.get(key); - if (!cached) return null; - if (cached.expiresAt !== null && cached.expiresAt <= Date.now()) { - resolvedRefCache.delete(key); - return null; - } - resolvedRefCache.delete(key); - resolvedRefCache.set(key, cached); - return cached.value; + const cached = resolvedRefCache.get(key); + if (!cached) return null; + if (cached.expiresAt !== null && cached.expiresAt <= Date.now()) { + resolvedRefCache.delete(key); + return null; + } + resolvedRefCache.delete(key); + resolvedRefCache.set(key, cached); + return cached.value; } function setCachedResolvedRef( - key: string, - value: Promise, - expiresAt: number | null, + key: string, + value: Promise, + expiresAt: number | null, ): void { - resolvedRefCache.set(key, { value, expiresAt }); - while (resolvedRefCache.size > REF_CACHE_MAX) { - const oldestKey = resolvedRefCache.keys().next().value; - if (oldestKey === undefined) break; - resolvedRefCache.delete(oldestKey); - } + resolvedRefCache.set(key, { value, expiresAt }); + while (resolvedRefCache.size > REF_CACHE_MAX) { + const oldestKey = resolvedRefCache.keys().next().value; + if (oldestKey === undefined) break; + resolvedRefCache.delete(oldestKey); + } } function fnv1a32(value: string): number { - let hash = 0x811c9dc5; - for (let i = 0; i < value.length; i += 1) { - hash ^= value.charCodeAt(i); - hash = Math.imul(hash, 0x01000193) >>> 0; - } - return hash >>> 0; + let hash = 0x811c9dc5; + for (let i = 0; i < value.length; i += 1) { + hash ^= value.charCodeAt(i); + hash = Math.imul(hash, 0x01000193) >>> 0; + } + return hash >>> 0; } function nodeViewBucket(nodeId: string, bucketCount: number): string { - const bucket = fnv1a32(nodeId) % bucketCount; - const width = Math.max(3, (bucketCount - 1).toString(16).length); - return bucket.toString(16).padStart(width, '0'); + const bucket = fnv1a32(nodeId) % bucketCount; + const width = Math.max(3, (bucketCount - 1).toString(16).length); + return bucket.toString(16).padStart(width, "0"); } function treeChildrenBucket(parentId: string, bucketCount: number): string { - const bucket = fnv1a32(parentId) % bucketCount; - const width = Math.max(3, (bucketCount - 1).toString(16).length); - return bucket.toString(16).padStart(width, '0'); + const bucket = fnv1a32(parentId) % bucketCount; + const width = Math.max(3, (bucketCount - 1).toString(16).length); + return bucket.toString(16).padStart(width, "0"); } /** @@ -477,182 +477,182 @@ function treeChildrenBucket(parentId: string, bucketCount: number): string { * to fan out across all shards starting with that letter. */ function searchPrefix(value: string): string { - const normalized = value - .trim() - .toLowerCase() - .replace(/[^a-z0-9_]/g, '_'); - if (normalized.length === 0) return '__'; - if (normalized.length === 1) return normalized; - return normalized.slice(0, 2); + const normalized = value + .trim() + .toLowerCase() + .replace(/[^a-z0-9_]/g, "_"); + if (normalized.length === 0) return "__"; + if (normalized.length === 1) return normalized; + return normalized.slice(0, 2); } function searchSummaries( - entries: NodeSummary[], - queryText: string, - limit: number, - kinds: Set = new Set(), + entries: NodeSummary[], + queryText: string, + limit: number, + kinds: Set = new Set(), ): NodeSummary[] { - const needle = queryText.trim().toLowerCase(); - if (!needle) return []; - return entries - .filter((entry) => entry.kind !== 'Impl' && (kinds.size === 0 || kinds.has(entry.kind))) - .map((entry): SearchEntry | null => { - const name = entry.name.toLowerCase(); - const id = entry.id.toLowerCase(); - if (name === needle) return { ...entry, score: 0 }; - if (name.startsWith(needle)) return { ...entry, score: 1 }; - if (id.endsWith(`::${needle}`)) return { ...entry, score: 2 }; - if (name.includes(needle)) return { ...entry, score: 3 }; - if (id.includes(needle)) return { ...entry, score: 4 }; - return null; - }) - .filter((entry): entry is SearchEntry => entry !== null) - .sort((a, b) => (a.score ?? 9) - (b.score ?? 9) || a.id.localeCompare(b.id)) - .slice(0, limit) - .map(({ score: _score, ...entry }) => entry); + const needle = queryText.trim().toLowerCase(); + if (!needle) return []; + return entries + .filter((entry) => entry.kind !== "Impl" && (kinds.size === 0 || kinds.has(entry.kind))) + .map((entry): SearchEntry | null => { + const name = entry.name.toLowerCase(); + const id = entry.id.toLowerCase(); + if (name === needle) return { ...entry, score: 0 }; + if (name.startsWith(needle)) return { ...entry, score: 1 }; + if (id.endsWith(`::${needle}`)) return { ...entry, score: 2 }; + if (name.includes(needle)) return { ...entry, score: 3 }; + if (id.includes(needle)) return { ...entry, score: 4 }; + return null; + }) + .filter((entry): entry is SearchEntry => entry !== null) + .sort((a, b) => (a.score ?? 9) - (b.score ?? 9) || a.id.localeCompare(b.id)) + .slice(0, limit) + .map(({ score: _score, ...entry }) => entry); } type HostedArtifactInfo = { - nodeViewBucketCount: number; - treeChildrenBucketCount: number; - aliasBucketCount: number; - targetRawShardBytes: number; - searchPrefixLength: number; - kindIndex: boolean; + nodeViewBucketCount: number; + treeChildrenBucketCount: number; + aliasBucketCount: number; + targetRawShardBytes: number; + searchPrefixLength: number; + kindIndex: boolean; }; type HostedMetaArtifact = { - schema_version: number; - name: string; - version: string; - index: CrateIndex; - nodeCount: number; - edgeCount: number; - kindCounts: Record; - roots: TreeNodeDTO[]; - rootChildren: Record; - artifacts: HostedArtifactInfo; + schema_version: number; + name: string; + version: string; + index: CrateIndex; + nodeCount: number; + edgeCount: number; + kindCounts: Record; + roots: TreeNodeDTO[]; + rootChildren: Record; + artifacts: HostedArtifactInfo; }; function isCurrentHostedMeta( - meta: HostedMetaArtifact | null, - ref?: ArtifactRef, + meta: HostedMetaArtifact | null, + ref?: ArtifactRef, ): meta is HostedMetaArtifact { - return isCurrentHostedArtifactMetadata( - meta, - ref ? { name: ref.storageName, version: ref.version } : undefined, - ); + return isCurrentHostedArtifactMetadata( + meta, + ref ? { name: ref.storageName, version: ref.version } : undefined, + ); } function isCurrentHostedArtifact( - artifact: { schema_version: number; name: string; version: string } | null, - ref: ArtifactRef, + artifact: { schema_version: number; name: string; version: string } | null, + ref: ArtifactRef, ): boolean { - return Boolean( - artifact?.schema_version === STATIC_ARTIFACT_SCHEMA_VERSION && - artifact.name === ref.storageName && - artifact.version === ref.version, - ); + return Boolean( + artifact?.schema_version === STATIC_ARTIFACT_SCHEMA_VERSION && + artifact.name === ref.storageName && + artifact.version === ref.version, + ); } type HostedNodeViewEntry = { - detail: NodeDetail; - ancestors: NodeSummary[]; + detail: NodeDetail; + ancestors: NodeSummary[]; }; type HostedNodeViewShard = { - schema_version: number; - name: string; - version: string; - bucket: string; - bucketCount: number; - entries: Record; + schema_version: number; + name: string; + version: string; + bucket: string; + bucketCount: number; + entries: Record; }; type HostedTreeChildrenShard = { - schema_version: number; - name: string; - version: string; - bucket: string; - bucketCount: number; - parents: Record< - string, - { - parent: NodeSummary; - children: TreeNodeDTO[]; - } - >; + schema_version: number; + name: string; + version: string; + bucket: string; + bucketCount: number; + parents: Record< + string, + { + parent: NodeSummary; + children: TreeNodeDTO[]; + } + >; }; type HostedSearchManifest = StaticSearchManifest; type HostedSearchShard = StaticSearchShard; type HostedKindShard = { - schema_version: number; - name: string; - version: string; - kind: NodeKind; - entries: NodeSummary[]; + schema_version: number; + name: string; + version: string; + kind: NodeKind; + entries: NodeSummary[]; }; type HostedAliasShard = { - schema_version: number; - name: string; - version: string; - bucket: string; - bucketCount: number; - aliases: Record; + schema_version: number; + name: string; + version: string; + bucket: string; + bucketCount: number; + aliases: Record; }; -const readR2JsonEffect = Effect.fn('CloudflareProvider.readR2Json')(function* ( - r2: R2Bucket, - key: string, +const readR2JsonEffect = Effect.fn("CloudflareProvider.readR2Json")(function* ( + r2: R2Bucket, + key: string, ) { - const obj = yield* Effect.tryPromise({ - try: () => r2.get(key), - catch: (cause) => - new R2ReadError({ - key, - cause, - message: `R2 read failed for ${key}: ${errorMessage(cause)}`, - }), - }); - if (!obj) return null as T | null; - - const bytes = yield* Effect.tryPromise({ - try: async () => new Uint8Array(await obj.arrayBuffer()), - catch: (cause) => - new R2DecodeError({ - key, - cause, - message: `R2 body decode failed for ${key}: ${errorMessage(cause)}`, - }), - }); - - if (bytes[0] === 0x1f && bytes[1] === 0x8b) { - return yield* Effect.tryPromise({ - try: async () => { - const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip')); - return (await new Response(stream).json()) as T; - }, - catch: (cause) => - new R2ParseError({ - key, - cause, - message: `R2 gzip JSON parse failed for ${key}: ${errorMessage(cause)}`, - }), - }); - } - - return yield* Effect.try({ - try: () => JSON.parse(new TextDecoder().decode(bytes)) as T, - catch: (cause) => - new R2ParseError({ - key, - cause, - message: `R2 JSON parse failed for ${key}: ${errorMessage(cause)}`, - }), - }); + const obj = yield* Effect.tryPromise({ + try: () => r2.get(key), + catch: (cause) => + new R2ReadError({ + key, + cause, + message: `R2 read failed for ${key}: ${errorMessage(cause)}`, + }), + }); + if (!obj) return null as T | null; + + const bytes = yield* Effect.tryPromise({ + try: async () => new Uint8Array(await obj.arrayBuffer()), + catch: (cause) => + new R2DecodeError({ + key, + cause, + message: `R2 body decode failed for ${key}: ${errorMessage(cause)}`, + }), + }); + + if (bytes[0] === 0x1f && bytes[1] === 0x8b) { + return yield* Effect.tryPromise({ + try: async () => { + const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")); + return (await new Response(stream).json()) as T; + }, + catch: (cause) => + new R2ParseError({ + key, + cause, + message: `R2 gzip JSON parse failed for ${key}: ${errorMessage(cause)}`, + }), + }); + } + + return yield* Effect.try({ + try: () => JSON.parse(new TextDecoder().decode(bytes)) as T, + catch: (cause) => + new R2ParseError({ + key, + cause, + message: `R2 JSON parse failed for ${key}: ${errorMessage(cause)}`, + }), + }); }); const artifactJsonCache = new Map>(); @@ -661,1525 +661,1525 @@ const sourceFileCache = new Map(); const SOURCE_FILE_CACHE_MAX = 512; function artifactR2Key(ref: ArtifactRef, path: string): string { - return `${artifactPrefix(ref.storageName, ref.version)}/${path}`; + return `${artifactPrefix(ref.storageName, ref.version)}/${path}`; } function encodePath(path: string): string { - return path.split('/').map(encodeURIComponent).join('/'); + return path.split("/").map(encodeURIComponent).join("/"); } function artifactCacheUrl(ref: ArtifactRef, path: string): string | null { - if (!ref.graphHash) return null; - return `https://codeview.internal/artifacts/${encodeURIComponent(ref.storageName)}/${encodeURIComponent( - ref.version, - )}/${encodeURIComponent(ref.graphHash)}/${HOSTED_ARTIFACT_CACHE_NAMESPACE}/${encodePath(path)}`; + if (!ref.graphHash) return null; + return `https://codeview.internal/artifacts/${encodeURIComponent(ref.storageName)}/${encodeURIComponent( + ref.version, + )}/${encodeURIComponent(ref.graphHash)}/${HOSTED_ARTIFACT_CACHE_NAMESPACE}/${encodePath(path)}`; } function getDefaultWorkerCache(): Cache | null { - if (typeof caches === 'undefined') return null; - return (caches as CacheStorage & { default?: Cache }).default ?? null; + if (typeof caches === "undefined") return null; + return (caches as CacheStorage & { default?: Cache }).default ?? null; } async function decodeR2ObjectText(_key: string, obj: R2ObjectBody): Promise { - const bytes = new Uint8Array(await obj.arrayBuffer()); - if (bytes[0] === 0x1f && bytes[1] === 0x8b) { - const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip')); - return new Response(stream).text(); - } - return new TextDecoder().decode(bytes); + const bytes = new Uint8Array(await obj.arrayBuffer()); + if (bytes[0] === 0x1f && bytes[1] === 0x8b) { + const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")); + return new Response(stream).text(); + } + return new TextDecoder().decode(bytes); } function setArtifactJsonCache(key: string, value: Promise): void { - artifactJsonCache.set(key, value); - while (artifactJsonCache.size > ARTIFACT_JSON_CACHE_MAX) { - const oldestKey = artifactJsonCache.keys().next().value; - if (oldestKey === undefined) break; - artifactJsonCache.delete(oldestKey); - } + artifactJsonCache.set(key, value); + while (artifactJsonCache.size > ARTIFACT_JSON_CACHE_MAX) { + const oldestKey = artifactJsonCache.keys().next().value; + if (oldestKey === undefined) break; + artifactJsonCache.delete(oldestKey); + } } async function readArtifactJsonWithCache( - r2: R2Bucket, - r2Key: string, - cacheUrl: string, + r2: R2Bucket, + r2Key: string, + cacheUrl: string, ): Promise { - const request = new Request(cacheUrl, { method: 'GET' }); - const cache = getDefaultWorkerCache(); - if (cache) { - try { - const cached = await cache.match(request); - if (cached) return (await cached.json()) as T; - } catch (err) { - log.warn`Cache API match failed for ${cacheUrl}: ${String(err)}`; - } - } - - let inflight = artifactJsonInflight.get(cacheUrl); - if (!inflight) { - inflight = (async (): Promise => { - const obj = await r2.get(r2Key); - if (!obj) return null; - const text = await decodeR2ObjectText(r2Key, obj); - if (cache) { - const response = new Response(text, { - headers: { - 'Content-Type': 'application/json; charset=utf-8', - 'Cache-Control': IMMUTABLE_ARTIFACT_CACHE_CONTROL, - }, - }); - try { - await cache.put(request, response.clone()); - } catch (err) { - log.warn`Cache API put failed for ${cacheUrl}: ${String(err)}`; - } - } - return JSON.parse(text) as T; - })().finally(() => { - artifactJsonInflight.delete(cacheUrl); - }); - artifactJsonInflight.set(cacheUrl, inflight); - } - return (await inflight) as T | null; + const request = new Request(cacheUrl, { method: "GET" }); + const cache = getDefaultWorkerCache(); + if (cache) { + try { + const cached = await cache.match(request); + if (cached) return (await cached.json()) as T; + } catch (err) { + log.warn`Cache API match failed for ${cacheUrl}: ${String(err)}`; + } + } + + let inflight = artifactJsonInflight.get(cacheUrl); + if (!inflight) { + inflight = (async (): Promise => { + const obj = await r2.get(r2Key); + if (!obj) return null; + const text = await decodeR2ObjectText(r2Key, obj); + if (cache) { + const response = new Response(text, { + headers: { + "Content-Type": "application/json; charset=utf-8", + "Cache-Control": IMMUTABLE_ARTIFACT_CACHE_CONTROL, + }, + }); + try { + await cache.put(request, response.clone()); + } catch (err) { + log.warn`Cache API put failed for ${cacheUrl}: ${String(err)}`; + } + } + return JSON.parse(text) as T; + })().finally(() => { + artifactJsonInflight.delete(cacheUrl); + }); + artifactJsonInflight.set(cacheUrl, inflight); + } + return (await inflight) as T | null; } export function createCloudflareProvider(env: AppEnv, request?: Request): DataProvider { - const mutableJsonCache = Effect.runSync( - Cache.makeWith( - (key: string) => - readR2JsonEffect(env.CRATE_GRAPHS, key).pipe( - Effect.catch((err: R2JsonError) => - Effect.sync(() => { - log.warn`${err.message}`; - return null; - }), - ), - ), - { - capacity: JSON_CACHE_MAX, - timeToLive: (exit, key) => { - if (!Exit.isSuccess(exit) || exit.value === null) return Duration.zero; - return key.includes('/_refs/') - ? Duration.millis(REF_TTL_MS) - : Duration.millis(MUTABLE_JSON_TTL_MS); - }, - }, - ), - ); - - function sourceCacheKey( - crateName: string, - crateVersion: string, - file: string, - sourceProvider: SourceProviderMode, - ): string { - return `${crateName}|${crateVersion}|${sourceProvider}|${file}`; - } - - function getCachedSourceFile(key: string): string | null { - const value = sourceFileCache.get(key); - if (value === undefined) return null; - sourceFileCache.delete(key); - sourceFileCache.set(key, value); - return value; - } - - function setCachedSourceFile(key: string, content: string): void { - if (sourceFileCache.has(key)) sourceFileCache.delete(key); - sourceFileCache.set(key, content); - while (sourceFileCache.size > SOURCE_FILE_CACHE_MAX) { - const oldestKey = sourceFileCache.keys().next().value; - if (oldestKey === undefined) break; - sourceFileCache.delete(oldestKey); - } - } - - function anonymousParseRateLimitKey(): string { - const ip = - request?.headers.get('cf-connecting-ip') ?? - request?.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? - 'anonymous'; - return `parse:anon:${ip}`; - } - - async function resolveParseRequestContext({ rateLimit }: { rateLimit: boolean }) { - const auth = request ? await getAuthStateFromRequest(request, env) : null; - const actor = actorFromUser(auth?.user ?? null); - if (!rateLimit) return { auth, actor, rateLimitError: null, configError: null }; - - const limiter = actor - ? (env.RATE_LIMIT_PARSE_AUTH ?? env.RATE_LIMIT_API_AUTH ?? env.RATE_LIMIT_API) - : (env.RATE_LIMIT_PARSE_ANON ?? env.RATE_LIMIT_API_ANON ?? env.RATE_LIMIT_API); - if (!limiter) { - return { - auth, - actor, - rateLimitError: null, - configError: new NotAvailableError({ - message: 'Hosted parse rate limiting is not configured', - }), - }; - } - - const key = actor ? `parse:user:${actor.id}` : anonymousParseRateLimitKey(); - const outcome = await limiter.limit({ key }); - if (outcome.success) return { auth, actor, rateLimitError: null, configError: null }; - return { - auth, - actor, - configError: null, - rateLimitError: new RateLimitError({ - message: actor - ? 'Too many signed-in parse requests. Try again shortly.' - : 'Too many anonymous parse requests. Sign in for a higher limit or try again shortly.', - }), - }; - } - - function readJson(key: string, _ttlMs = MUTABLE_JSON_TTL_MS): Promise { - return Effect.runPromise(Cache.get(mutableJsonCache, key)) as Promise; - } - - async function readArtifactJson(ref: ArtifactRef, path: string): Promise { - const r2Key = artifactR2Key(ref, path); - const cacheUrl = artifactCacheUrl(ref, path); - if (!cacheUrl) return readJson(r2Key); - - let cached = artifactJsonCache.get(cacheUrl); - if (!cached) { - cached = readArtifactJsonWithCache(env.CRATE_GRAPHS, r2Key, cacheUrl).catch((err) => { - artifactJsonCache.delete(cacheUrl); - log.warn`R2 artifact read failed for ${r2Key}: ${String(err)}`; - return null; - }); - setArtifactJsonCache(cacheUrl, cached); - } - return cached as Promise; - } - - async function readCrateRefs(storageName: string): Promise { - const raw = await readJson(refsKey(storageName), REF_TTL_MS); - if (!raw) return null; - const refs = parseCrateRefs(raw); - if (!refs) { - log.warn`Invalid crate refs at ${refsKey(storageName)}`; - return null; - } - return refs; - } - - async function resolveRefForArtifactUncached( - name: string, - version: string, - ): Promise { - for (const variant of uniqueCrateNameVariants(name)) { - const refs = await readCrateRefs(variant); - if (!refs) continue; - const ref = resolveRefFromRefs(refs, version); - if (!ref) continue; - const meta = await readArtifactJson(ref, 'site/meta.json'); - if (!isCurrentHostedMeta(meta, ref)) continue; - return ref; - } - - return null; - } - - async function resolveRefForArtifact(name: string, version: string): Promise { - const key = resolvedRefCacheKey(name, version); - const cached = getCachedResolvedRef(key); - if (cached) return cached; - - const pending = resolveRefForArtifactUncached(name, version) - .then((ref) => { - setCachedResolvedRef(key, Promise.resolve(ref), Date.now() + REF_TTL_MS); - return ref; - }) - .catch((err) => { - resolvedRefCache.delete(key); - throw err; - }); - setCachedResolvedRef(key, pending, Date.now() + REF_TTL_MS); - return pending; - } - - async function listPublishedVersionsFromRefs( - name: string, - limit: number, - ): Promise { - for (const variant of uniqueCrateNameVariants(name)) { - const refs = await readCrateRefs(variant); - if (!refs) continue; - return refs.versions.map((entry) => entry.version).slice(0, limit); - } - return null; - } - - async function listRegistryVersions(name: string, limit: number): Promise { - if (isStdCrate(normalizeCrateName(name))) return []; - const registryResult = getRegistry('rust'); - if (registryResult.isErr()) return []; - for (const variant of uniqueCrateNameVariants(name)) { - const versions = await registryResult.value.listVersions(variant, limit); - if (versions.length > 0) return versions; - } - return []; - } - - function mergeVersions(primary: string[], secondary: string[] | null, limit: number): string[] { - const versions: string[] = []; - const seen = new Set(); - for (const version of [...primary, ...(secondary ?? [])]) { - if (seen.has(version)) continue; - seen.add(version); - versions.push(version); - if (versions.length >= limit) break; - } - return versions; - } - - async function loadHostedContext( - name: string, - version: string, - ): Promise<{ ref: ArtifactRef; meta: HostedMetaArtifact } | null> { - const ref = await resolveRefForArtifact(name, version); - if (!ref) return null; - const meta = await readArtifactJson(ref, 'site/meta.json'); - return isCurrentHostedMeta(meta, ref) ? { ref, meta } : null; - } - - async function loadHostedMetaArtifact( - name: string, - version: string, - ): Promise { - return (await loadHostedContext(name, version))?.meta ?? null; - } - - async function loadHostedKindShardFromRef( - ref: ArtifactRef, - kind: NodeKind, - ): Promise { - const shard = await readArtifactJson(ref, `site/kinds/${kind}.json`); - return isCurrentHostedArtifact(shard, ref) && shard?.kind === kind ? shard : null; - } - - async function filterNodesFromKindIndex( - ref: ArtifactRef, - kinds: Set, - limit: number, - ): Promise { - const pageKinds = Array.from(kinds).filter((kind) => kind !== 'Impl'); - if (pageKinds.length === 0) return []; - const shards = await Promise.all( - pageKinds.sort().map((kind) => loadHostedKindShardFromRef(ref, kind)), - ); - const completeShards = shards.filter((shard): shard is HostedKindShard => shard !== null); - if (completeShards.length !== shards.length) { - log.error`Incomplete kind index for ${ref.storageName}@${ref.version}`; - return []; - } - const entries = completeShards - .flatMap((shard) => shard.entries) - .filter((entry) => entry.kind !== 'Impl'); - if (shards.length <= 1) return entries.slice(0, limit); - return entries.sort((a, b) => a.id.localeCompare(b.id)).slice(0, limit); - } - - async function loadHostedAlias( - ref: ArtifactRef, - meta: HostedMetaArtifact, - nodeId: string, - ): Promise { - const bucket = nodeViewBucket(nodeId, meta.artifacts.aliasBucketCount); - const shard = await readArtifactJson(ref, `site/aliases/${bucket}.json`); - if ( - !isCurrentHostedArtifact(shard, ref) || - shard?.bucketCount !== meta.artifacts.aliasBucketCount - ) { - return null; - } - return shard.aliases[nodeId]?.canonicalId ?? null; - } - - async function loadMaterializedNodeView( - hostedRef: ArtifactRef, - hostedMeta: HostedMetaArtifact, - nodeId: string, - ): Promise { - async function loadEntry(id: string): Promise { - const bucketCount = hostedMeta.artifacts.nodeViewBucketCount; - const bucket = nodeViewBucket(id, bucketCount); - const shard = await readArtifactJson( - hostedRef, - `site/node-views/${bucket}.json`, - ); - if (!isCurrentHostedArtifact(shard, hostedRef) || shard?.bucketCount !== bucketCount) { - return null; - } - return shard.entries[id] ?? null; - } - - let resolvedId = nodeId; - let entry = await loadEntry(resolvedId); - if (!entry) { - const canonical = await loadHostedAlias(hostedRef, hostedMeta, nodeId); - if (canonical && canonical !== nodeId) { - resolvedId = canonical; - entry = await loadEntry(resolvedId); - } - } - return entry - ? { - detail: entry.detail, - ancestors: entry.ancestors, - } - : null; - } - - async function loadNodeView( - name: string, - version: string, - nodeId: string, - ): Promise { - const context = await loadHostedContext(name, version); - if (!context) return null; - const view = await loadMaterializedNodeView(context.ref, context.meta, nodeId); - if (!view) return null; - - const traitIds = Array.from( - new Set( - view.detail.relatedNodes - .filter( - (node) => - node.kind === 'Impl' && node.impl_category === 'Trait' && Boolean(node.impl_trait), - ) - .map((node) => node.impl_trait as string), - ), - ); - if (traitIds.length === 0) return view; - - const traitEntries = await Promise.all( - traitIds.map(async (traitId): Promise<[string, NodeViewBase] | null> => { - const traitCrate = traitId.split('::')[0]; - if (!traitCrate) return null; - let traitContext = context; - if (normalizeCrateName(traitCrate) !== normalizeCrateName(name)) { - if (!isStdCrate(traitCrate)) return null; - const externalContext = await loadHostedContext(traitCrate, 'latest'); - if (!externalContext) return null; - traitContext = externalContext; - } - const traitView = await loadMaterializedNodeView( - traitContext.ref, - traitContext.meta, - traitId, - ); - return traitView ? [traitId, traitView] : null; - }), - ); - return mergeTraitMemberDocumentation( - view, - new Map(traitEntries.filter((entry): entry is [string, NodeViewBase] => entry !== null)), - ); - } - - async function loadHostedSearchManifestFromRef( - ref: ArtifactRef, - ): Promise { - const manifest = await readArtifactJson(ref, 'site/search-manifest.json'); - return isCurrentHostedArtifact(manifest, ref) ? manifest : null; - } - - async function loadHostedSearchShardFromRef( - ref: ArtifactRef, - prefix: string, - ): Promise { - const shard = await readArtifactJson(ref, `site/search/${prefix}.json`); - return isCurrentHostedArtifact(shard, ref) && shard?.prefix === prefix ? shard : null; - } - - async function loadHostedTreeChildrenFromContext( - context: { ref: ArtifactRef; meta: HostedMetaArtifact }, - parentId: string, - ): Promise { - const bucket = treeChildrenBucket(parentId, context.meta.artifacts.treeChildrenBucketCount); - const shard = await readArtifactJson( - context.ref, - `site/tree-children/${bucket}.json`, - ); - if ( - !isCurrentHostedArtifact(shard, context.ref) || - shard?.bucketCount !== context.meta.artifacts.treeChildrenBucketCount - ) { - return null; - } - return shard.parents[parentId]?.children ?? null; - } - - async function loadCatalogArtifact(): Promise { - const catalog = await readJson('rust/catalog.json'); - if ( - catalog?.schema_version !== STATIC_ARTIFACT_SCHEMA_VERSION || - !Array.isArray(catalog.crates) - ) { - return null; - } - return catalog; - } - - async function listPublishedVersions( - name: string, - limit = Number.POSITIVE_INFINITY, - ): Promise { - const [refsVersions, registryVersions] = await Promise.all([ - listPublishedVersionsFromRefs(name, limit), - listRegistryVersions(name, limit), - ]); - if (isStdCrate(normalizeCrateName(name))) { - return mergeVersions([...RUST_CHANNEL_ORDER], refsVersions, limit); - } - if (registryVersions.length > 0) return mergeVersions(registryVersions, refsVersions, limit); - return refsVersions ?? []; - } - - async function firstPublishedVersion(name: string): Promise { - return (await listPublishedVersions(name, 1))[0] ?? null; - } - - function storedStatusToCrateStatus(stored: StoredParseStatus) { - return { - status: stored.status, - error: stored.error, - step: stored.step, - action: stored.action, - installedVersion: stored.installedVersion, - }; - } - - async function readHostedParseStatus( - name: string, - version: string, - ): Promise { - if (!env.PARSE_STATUS) return null; - const url = new URL('https://status/status'); - url.searchParams.set('name', name); - url.searchParams.set('version', version); - const response = await parseStatusObject(env.PARSE_STATUS).fetch(url); - if (!response.ok) return null; - return (await response.json()) as StoredParseStatus | null; - } - - async function listHostedProcessing(limit: number): Promise { - if (!env.PARSE_STATUS) return []; - const url = new URL('https://status/processing'); - url.searchParams.set('limit', String(limit)); - const response = await parseStatusObject(env.PARSE_STATUS).fetch(url); - if (!response.ok) return []; - return (await response.json()) as StoredParseStatus[]; - } - - async function readHostedQueue(limit: number): Promise { - if (!env.PARSE_STATUS) return { active: [], recent: [] }; - const url = new URL('https://status/queue'); - url.searchParams.set('limit', String(limit)); - const response = await parseStatusObject(env.PARSE_STATUS).fetch(url); - if (!response.ok) return { active: [], recent: [] }; - return (await response.json()) as StoredParseQueueSnapshot; - } - - function githubHeaders(): HeadersInit { - const headers: Record = { - accept: 'application/vnd.github+json', - 'user-agent': USER_AGENT, - 'x-github-api-version': GITHUB_API_VERSION, - }; - if (env.GITHUB_TOKEN) headers.authorization = `Bearer ${env.GITHUB_TOKEN}`; - return headers; - } - - function workflowRunToActiveRun(run: GitHubWorkflowRun): ActiveParseRun | null { - if (!run.id || !run.html_url || !run.created_at || !run.updated_at) return null; - return { - id: String(run.id), - title: run.display_title || run.name || 'parse', - status: run.status ?? 'unknown', - event: run.event ?? 'workflow', - branch: run.head_branch, - url: run.html_url, - createdAt: run.created_at, - updatedAt: run.updated_at, - }; - } - - async function listActiveGitHubParseRuns(limit: number): Promise { - const repo = env.GITHUB_REPO; - if (!repo) return []; - const workflowFile = env.GITHUB_WORKFLOW_FILE ?? DEFAULT_GITHUB_WORKFLOW_FILE; - const runs = await Promise.all( - ACTIVE_GITHUB_RUN_STATUSES.map(async (status) => { - const url = new URL( - `https://api.github.com/repos/${repo}/actions/workflows/${workflowFile}/runs`, - ); - url.searchParams.set('status', status); - url.searchParams.set('per_page', String(Math.max(1, Math.min(limit, 20)))); - const response = await fetch(url, { headers: githubHeaders() }); - if (!response.ok) { - log.warn`GitHub workflow run lookup failed status=${status} code=${String(response.status)}`; - return []; - } - const body = (await response.json()) as GitHubWorkflowRunsResponse; - return (body.workflow_runs ?? []) - .map(workflowRunToActiveRun) - .filter((run): run is ActiveParseRun => run !== null); - }), - ); - const byId = new Map(); - for (const run of runs.flat()) byId.set(run.id, run); - return [...byId.values()] - .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) - .slice(0, Math.max(1, Math.min(limit, 20))); - } - - async function loadGitHubRepository(): Promise { - const repo = env.GITHUB_REPO; - if (!repo) return null; - const response = await fetch(`https://api.github.com/repos/${repo}`, { - headers: githubHeaders(), - }); - if (!response.ok) { - log.warn`GitHub repository lookup failed code=${String(response.status)}`; - return null; - } - return (await response.json()) as GitHubRepositoryResponse; - } - - function emptyBillingSummary( - owner: string, - accountType: GitHubActionsBillingSummary['accountType'], - error?: string, - ): GitHubActionsBillingSummary { - return { - available: false, - owner, - accountType, - totalMinutesUsed: null, - totalPaidMinutesUsed: null, - error, - }; - } - - function unmeteredBillingSummary( - owner: string, - accountType: GitHubActionsBillingSummary['accountType'], - ): GitHubActionsBillingSummary { - return { - available: true, - owner, - accountType, - totalMinutesUsed: null, - totalPaidMinutesUsed: null, - }; - } - - function actionsBillingUsageUrl( - owner: string, - accountType: GitHubActionsBillingSummary['accountType'], - ): string { - const path = - accountType === 'Organization' - ? `/organizations/${owner}/settings/billing/usage/summary` - : `/users/${owner}/settings/billing/usage/summary`; - const url = new URL(`https://api.github.com${path}`); - url.searchParams.set('product', 'Actions'); - if (env.GITHUB_REPO) url.searchParams.set('repository', env.GITHUB_REPO); - return url.toString(); - } - - async function loadGitHubActionsBilling( - repository: GitHubRepositoryResponse | null, - ): Promise { - const owner = repository?.owner?.login ?? env.GITHUB_REPO?.split('/')[0] ?? ''; - const ownerType = - repository?.owner?.type === 'Organization' - ? 'Organization' - : repository?.owner?.type === 'User' - ? 'User' - : 'unknown'; - if (!owner) return emptyBillingSummary('', 'unknown', 'GITHUB_REPO is not configured'); - if (!env.GITHUB_TOKEN) - return emptyBillingSummary(owner, ownerType, 'GITHUB_TOKEN is not configured'); - - const response = await fetch(actionsBillingUsageUrl(owner, ownerType), { - headers: githubHeaders(), - }); - if (!response.ok) { - return emptyBillingSummary( - owner, - ownerType, - `GitHub billing usage unavailable: ${response.status} ${response.statusText}`, - ); - } - const body = (await response.json()) as GitHubBillingUsageSummaryResponse; - return { - available: true, - owner, - accountType: ownerType, - totalMinutesUsed: totalGrossActionsMinutes(body), - totalPaidMinutesUsed: totalBillableActionsMinutes(body), - }; - } - - function workflowRunDurationMinutes(run: GitHubWorkflowRun, nowMs: number): number { - const start = run.created_at ? Date.parse(run.created_at) : NaN; - if (!Number.isFinite(start)) return 0; - const isActive = run.status - ? (ACTIVE_GITHUB_RUN_STATUSES as readonly string[]).includes(run.status) - : false; - const updated = run.updated_at ? Date.parse(run.updated_at) : NaN; - const end = isActive ? nowMs : Number.isFinite(updated) ? updated : nowMs; - return Math.max(0, (end - start) / 60_000); - } - - async function estimateParseWorkflowMinutesThisMonth(): Promise { - const repo = env.GITHUB_REPO; - if (!repo) return null; - const workflowFile = env.GITHUB_WORKFLOW_FILE ?? DEFAULT_GITHUB_WORKFLOW_FILE; - const startedAt = monthStartIso(); - let total = 0; - let loaded = 0; - const nowMs = Date.now(); - for (let page = 1; page <= 5; page += 1) { - const url = new URL( - `https://api.github.com/repos/${repo}/actions/workflows/${workflowFile}/runs`, - ); - url.searchParams.set('created', `>=${startedAt}`); - url.searchParams.set('per_page', '100'); - url.searchParams.set('page', String(page)); - const response = await fetch(url, { headers: githubHeaders() }); - if (!response.ok) { - log.warn`GitHub monthly workflow usage lookup failed code=${String(response.status)}`; - return null; - } - const body = (await response.json()) as GitHubWorkflowRunsResponse; - const runs = body.workflow_runs ?? []; - loaded += runs.length; - for (const run of runs) total += workflowRunDurationMinutes(run, nowMs); - if (runs.length < 100) break; - } - return loaded > 0 ? total : 0; - } - - async function buildParseQueueSnapshot(limit: number): Promise { - return Effect.runPromise( - Effect.gen(function* () { - const boundedLimit = Math.max(1, Math.min(limit, 100)); - const [queue, activeRuns] = yield* Effect.all( - [ - Effect.tryPromise({ - try: () => readHostedQueue(boundedLimit), - catch: (cause) => new Error(`hosted queue load failed: ${errorMessage(cause)}`), - }).pipe( - Effect.catch((err) => - Effect.sync(() => { - log.warn`${err.message}`; - return { active: [], recent: [] } satisfies StoredParseQueueSnapshot; - }), - ), - ), - Effect.tryPromise({ - try: () => listActiveGitHubParseRuns(boundedLimit), - catch: (cause) => - new Error(`active GitHub parse run load failed: ${errorMessage(cause)}`), - }).pipe( - Effect.catch((err) => - Effect.sync(() => { - log.warn`${err.message}`; - return [] as ActiveParseRun[]; - }), - ), - ), - ], - { concurrency: 2 }, - ); - const recent = yield* Effect.promise(() => removeStaleFailedQueueEntries(queue.recent)); - const planned = yield* Effect.tryPromise({ - try: () => loadLatestPlannedRun(boundedLimit), - catch: (cause) => new Error(`planned parse run load failed: ${errorMessage(cause)}`), - }).pipe( - Effect.catch((err) => - Effect.sync(() => { - log.warn`${err.message}`; - return null; - }), - ), - ); - return { - active: queue.active.map((entry, index) => storedStatusToQueueEntry(entry, index + 1)), - activeRuns, - recent: recent.map((entry) => storedStatusToQueueEntry(entry)), - planned, - } satisfies ParseQueueSnapshot; - }), - ); - } - - async function hasReadyArtifact(name: string, version: string): Promise { - const ref = await resolveRefForArtifact(name, version); - if (!ref) return false; - const meta = await readArtifactJson(ref, 'site/meta.json'); - return isCurrentHostedMeta(meta, ref); - } - - async function removeStaleFailedQueueEntries( - entries: StoredParseStatus[], - ): Promise { - const stale = await Promise.all( - entries.map(async (entry) => { - if (entry.status !== 'failed') return false; - return hasReadyArtifact(entry.name, entry.version).catch(() => false); - }), - ); - return entries.filter((_, index) => !stale[index]); - } - - async function buildParseAllowance(queue: ParseQueueSnapshot): Promise { - const activeTarget = parsePositiveInteger( - env.PLAN_DRAIN_ACTIVE_TARGET, - DEFAULT_PLAN_DRAIN_ACTIVE_TARGET, - ); - const batchSize = parseNonNegativeInteger( - env.PLAN_DRAIN_BATCH_SIZE, - DEFAULT_PLAN_DRAIN_BATCH_SIZE, - ); - const repoUsageTargetPercent = parsePositiveNumber( - env.GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT, - DEFAULT_GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT, - ); - const trackedActiveCount = queue.active.length; - const githubActiveRunCount = queue.activeRuns.length; - const actionsInUse = Math.max(trackedActiveCount, githubActiveRunCount); - const availableSlots = Math.max(0, activeTarget - actionsInUse); - const [repository, estimatedRepoMinutesThisMonth] = await Promise.all([ - loadGitHubRepository().catch(() => null), - estimateParseWorkflowMinutesThisMonth().catch(() => null), - ]); - const repoPrivate = typeof repository?.private === 'boolean' ? repository.private : null; - const standardRunnerMinutesMetered = repoPrivate === null ? null : repoPrivate; - const loadedBilling = await loadGitHubActionsBilling(repository).catch((err) => - emptyBillingSummary( - repository?.owner?.login ?? env.GITHUB_REPO?.split('/')[0] ?? '', - repository?.owner?.type === 'Organization' - ? 'Organization' - : repository?.owner?.type === 'User' - ? 'User' - : 'unknown', - errorMessage(err), - ), - ); - const billing = - standardRunnerMinutesMetered === false && !loadedBilling.available - ? unmeteredBillingSummary( - repository?.owner?.login ?? env.GITHUB_REPO?.split('/')[0] ?? '', - repository?.owner?.type === 'Organization' - ? 'Organization' - : repository?.owner?.type === 'User' - ? 'User' - : 'unknown', - ) - : loadedBilling; - return { - repo: repository?.full_name ?? env.GITHUB_REPO ?? null, - workflowFile: env.GITHUB_WORKFLOW_FILE ?? DEFAULT_GITHUB_WORKFLOW_FILE, - activeTarget, - batchSize, - trackedActiveCount, - githubActiveRunCount, - actionsInUse, - availableSlots, - repoUsageTargetPercent, - repoPrivate, - standardRunnerMinutesMetered, - monthStartedAt: monthStartIso(), - estimatedRepoMinutesThisMonth, - billing, - }; - } - - async function recordHostedParseEvent(event: ParseStatusEvent): Promise { - if (!env.PARSE_STATUS) return; - const response = await parseStatusObject(env.PARSE_STATUS).fetch('https://status/event', { - method: 'POST', - headers: { 'content-type': 'application/json; charset=utf-8' }, - body: JSON.stringify(event), - }); - if (!response.ok) { - throw new Error(`parse status update failed: ${response.status}`); - } - } - - function storedStatusToQueueEntry(stored: StoredParseStatus, position?: number): ParseQueueEntry { - return { - kind: stored.kind, - name: stored.name, - version: stored.version, - status: stored.status, - step: stored.step, - error: stored.error, - requestId: stored.requestId, - workflowId: stored.workflowId, - githubRunId: stored.githubRunId, - githubRunUrl: stored.githubRunUrl, - requestedBy: stored.requestedBy, - requestedAt: stored.createdAt, - updatedAt: stored.updatedAt, - position, - }; - } - - function planReasonParserTarget(reason: string | undefined): string | null { - const match = /\bparser\s+\S+\s+(?:\u2192|->)\s+([0-9a-fA-F]{7,40})\b/.exec(reason ?? ''); - return match?.[1] ?? null; - } - - function planReasonSchemaTarget(reason: string | undefined): number | null { - const match = /\bschema\s+v\d+\s+(?:\u2192|->)\s+v(\d+)\b/.exec(reason ?? ''); - if (!match?.[1]) return null; - const value = Number.parseInt(match[1], 10); - return Number.isFinite(value) ? value : null; - } - - function revisionMatches(actual: string | undefined, target: string): boolean { - return !!actual && (actual === target || actual.startsWith(target)); - } - - function freshnessParsedAfterPlan(freshness: FreshnessEntry, planGeneratedAt: string): boolean { - const generatedAtMs = Date.parse(planGeneratedAt); - const parsedAtMs = Date.parse(freshness.parsedAt ?? ''); - return Number.isFinite(generatedAtMs) && Number.isFinite(parsedAtMs) - ? parsedAtMs >= generatedAtMs - : false; - } - - async function readPlanFreshness( - item: Pick, - ): Promise { - for (const variant of crateNameVariants(item.name)) { - const entry = await readJson( - `rust/_index/by-version/${normalizeCrateName(variant)}/${item.version}.json`, - ); - if (entry) return entry; - } - return null; - } - - async function plannedItemSatisfiedByFreshness( - item: Pick, - planGeneratedAt: string, - ): Promise { - const freshness = await readPlanFreshness(item); - if (!freshness) return false; - - const parserTarget = planReasonParserTarget(item.reason); - if (parserTarget) - return ( - revisionMatches(freshness.parserRevision, parserTarget) || - freshnessParsedAfterPlan(freshness, planGeneratedAt) - ); - - const schemaTarget = planReasonSchemaTarget(item.reason); - if (schemaTarget !== null) - return ( - freshness.schemaVersion === schemaTarget || - freshnessParsedAfterPlan(freshness, planGeneratedAt) - ); - - if ( - item.priorityTier === 'never-parsed-backfill' || - item.priorityTier === 'newer-version' || - item.reason.includes('never parsed') || - item.reason.includes('crates.io') - ) { - return freshness.version === item.version; - } - - const generatedAtMs = Date.parse(planGeneratedAt); - const parsedAtMs = Date.parse(freshness.parsedAt ?? ''); - return freshness.version === item.version && Number.isFinite(generatedAtMs) - ? Number.isFinite(parsedAtMs) && parsedAtMs >= generatedAtMs - : freshness.version === item.version; - } - - function planItemFromArtifact( - item: NonNullable[number], - ): Omit | null { - if (!item.name || !item.version) return null; - const kind = item.kind === 'std' || item.kind === 'sysroot' ? 'sysroot' : 'crate'; - return { - kind, - name: item.name, - version: item.version, - channel: item.channel ?? 'default', - priorityTier: item.priority_tier ?? item.priorityTier ?? 'unknown', - reason: item.reason ?? '', - downloadRank: item.download_rank ?? item.downloadRank, - workId: item.work_id ?? item.workId ?? `${kind}:${item.name}:${item.version}`, - }; - } - - async function planFromArtifact( - plan: WorkPlanArtifact, - limit: number, - ): Promise { - const runId = plan.run_id ?? plan.runId; - const generatedAt = plan.generated_at ?? plan.generatedAt; - if (!runId || !generatedAt) return null; - const work = Array.isArray(plan.work) ? plan.work : []; - const candidates = work - .map(planItemFromArtifact) - .filter((entry): entry is Omit => entry !== null); - const annotated = await Promise.all( - candidates.map(async (entry) => { - const ready = await plannedItemSatisfiedByFreshness(entry, generatedAt); - return { ...entry, state: ready ? ('ready' as const) : ('pending' as const) }; - }), - ); - const pending = annotated.filter((entry) => entry.state === 'pending'); - const ready = annotated.filter((entry) => entry.state === 'ready'); - const pendingShown = pending.slice(0, Math.max(1, limit)); - const readySlots = Math.max(0, Math.max(1, limit) - pendingShown.length); - const items = [...pendingShown, ...ready.slice(0, readySlots)]; - return { - runId, - generatedAt, - mode: plan.mode ?? 'unknown', - shardCount: plan.shard_count ?? plan.shardCount ?? 0, - total: pending.length, - pending: pending.length, - ready: ready.length, - items, - }; - } - - async function listPlanKeys(maxKeys = 5000): Promise { - const candidates: PlanKeyCandidate[] = []; - let cursor: string | undefined; - do { - const page = await env.CRATE_GRAPHS.list({ - prefix: 'rust/_runs/', - limit: Math.min(1000, Math.max(1, maxKeys - candidates.length)), - cursor, - }); - for (const object of page.objects) { - if (object.key.endsWith('/plan.json')) { - candidates.push({ - key: object.key, - uploaded: object.uploaded?.toISOString(), - }); - } - if (candidates.length >= maxKeys) break; - } - cursor = page.truncated ? page.cursor : undefined; - } while (cursor && candidates.length < maxKeys); - return candidates.sort( - (a, b) => (b.uploaded ?? '').localeCompare(a.uploaded ?? '') || b.key.localeCompare(a.key), - ); - } - - async function loadLatestPlannedRun(limit: number): Promise { - const plans = await Promise.all( - (await listPlanKeys()).slice(0, 25).map(async ({ key }) => { - const raw = await readJson(key); - return raw ? await planFromArtifact(raw, limit) : null; - }), - ); - return ( - plans - .filter((plan): plan is PlannedParseRun => plan !== null) - .sort((a, b) => b.generatedAt.localeCompare(a.generatedAt))[0] ?? null - ); - } - - let publishedCratesCache: Promise | null = null; - async function listPublishedCrates(): Promise { - if (!publishedCratesCache) { - publishedCratesCache = (async () => { - const catalog = await loadCatalogArtifact(); - if (catalog) { - return orderCatalogSummaries(catalog.crates) satisfies CrateSummaryResult[]; - } - return []; - })().catch((err) => { - publishedCratesCache = null; - log.warn`published crate catalog load failed: ${String(err)}`; - return []; - }); - } - return publishedCratesCache; - } - - return { - async loadSourceFile( - relativePath: string, - crateName?: string, - crateVersion?: string, - sourceProvider: SourceProviderMode = 'auto', - ) { - if (!crateName || !crateVersion) { - return { - error: 'Source file not available', - content: null, - absolutePath: null, - repoUrl: null, - }; - } - - const cacheKey = sourceCacheKey(crateName, crateVersion, relativePath, sourceProvider); - const cachedContent = getCachedSourceFile(cacheKey); - if (cachedContent !== null) { - return { error: null, content: cachedContent, absolutePath: null, repoUrl: null }; - } - - // ── Std fast-path ───────────────────────────────────────── - // std/core/alloc/proc_macro/test aren't on crates.io. Their - // sources live in rust-lang/rust under `library/{crate}/...`. - // rustdoc spans already use that form, so we just point at - // the right git ref and stream the file. - if (isStdCrate(normalizeCrateName(crateName))) { - const result = await fetchStdSourceFile( - relativePath, - crateVersion, - SOURCE_MAX_BYTES, - USER_AGENT, - ); - if ('content' in result) { - setCachedSourceFile(cacheKey, result.content); - return { - error: null, - content: result.content, - absolutePath: null, - repoUrl: result.blobUrl, - }; - } - return { error: result.error, content: null, absolutePath: null, repoUrl: result.blobUrl }; - } - - const sourceAdapterResult = getSourceAdapter('rust'); - if (sourceAdapterResult.isErr()) { - return { - error: sourceAdapterResult.error.message, - content: null, - absolutePath: null, - repoUrl: null, - }; - } - - const registryResult = getRegistry('rust'); - if (registryResult.isErr()) { - return { - error: registryResult.error.message, - content: null, - absolutePath: null, - repoUrl: null, - }; - } - - let metadata: Awaited> | null = null; - for (const variant of crateNameVariants(crateName)) { - const resolved = await registryResult.value.resolve(variant, crateVersion); - if (resolved) { - metadata = resolved; - break; - } - } - if (!metadata) { - return { - error: 'Source metadata unavailable', - content: null, - absolutePath: null, - repoUrl: null, - }; - } - - const repoUrl = buildGitHubFileUrl(metadata, relativePath); - - if ( - (sourceProvider === 'auto' || sourceProvider === 'crates-io') && - metadata.sourceArchiveUrl - ) { - const direct = await fetchSourceFileFromArchive(metadata.sourceArchiveUrl, relativePath, { - maxBytes: SOURCE_MAX_BYTES, - userAgent: USER_AGENT, - }); - if (direct.status === 'ok') { - setCachedSourceFile(cacheKey, direct.content); - return { error: null, content: direct.content, absolutePath: null, repoUrl }; - } - if (sourceProvider === 'crates-io') { - return { - error: direct.status === 'error' ? direct.message : 'Source file not available', - content: null, - absolutePath: null, - repoUrl: null, - }; - } - } - - const providers = sourceAdapterResult.value.getProviders({ - ecosystem: 'rust', - name: metadata.name, - version: metadata.version, - metadata, - }); - const selectedProviders = source.selectProviders(providers, sourceProvider); - const files = await fetchSourcesWithProviders( - selectedProviders, - { ecosystem: 'rust', name: metadata.name, version: metadata.version, metadata }, - { - maxBytes: SOURCE_MAX_BYTES, - userAgent: USER_AGENT, - githubToken: env.GITHUB_TOKEN, - }, - ); - if (!files) { - return { - error: 'Source file not available', - content: null, - absolutePath: null, - repoUrl: null, - }; - } - - const content = source.resolveFromMap(files, relativePath); - if (content === null) { - return { error: 'File not found', content: null, absolutePath: null, repoUrl }; - } - setCachedSourceFile(cacheKey, content); - return { error: null, content, absolutePath: null, repoUrl }; - }, - - async loadCrateGraph(name: string, version: string): Promise { - return null; - }, - - async loadTreeMeta(name: string, version: string) { - const meta = await loadHostedMetaArtifact(name, version); - return meta ? { kindCounts: meta.kindCounts, roots: meta.roots } : null; - }, - - async loadTreeRootsDirect(name: string, version: string): Promise { - return (await loadHostedMetaArtifact(name, version))?.roots ?? []; - }, - - async loadTreeChildrenDirect( - name: string, - version: string, - parentId: string, - ): Promise { - const context = await loadHostedContext(name, version); - if (!context) return []; - const rootChildren = context.meta.rootChildren[parentId]; - if (rootChildren !== undefined) return rootChildren; - return (await loadHostedTreeChildrenFromContext(context, parentId)) ?? []; - }, - - async loadTreeAncestorsDirect( - name: string, - version: string, - nodeId: string, - ): Promise { - const view = await loadNodeView(name, version, nodeId); - return view?.ancestors ?? []; - }, - - async loadCrateTree(name: string, version: string): Promise { - return null; - }, - - async loadCrateIndex(name: string, version: string): Promise { - return (await loadHostedMetaArtifact(name, version))?.index ?? null; - }, - - async loadNodeViewDirect( - name: string, - version: string, - nodeId: string, - ): Promise { - return loadNodeView(name, version, nodeId); - }, - - async loadNodeDetail( - name: string, - version: string, - nodeId: string, - ): Promise { - const view = await loadNodeView(name, version, nodeId); - return view?.detail ?? null; - }, - - async loadCrateMap( - name: string, - version: string, - options?: CrateMapOptions, - ): Promise { - const context = await loadHostedContext(name, version); - if (!context) return null; - return readArtifactJson(context.ref, 'crate-map.json'); - }, - - async getCrossEdgeData(_nodeId: string): Promise { - return { edges: [], nodes: [] }; - }, - - async searchNodesDirect( - crateName: string, - crateVersion: string, - queryText: string, - limit = 200, - kinds: NodeKind[] = [], - ): Promise { - const context = await loadHostedContext(crateName, crateVersion); - if (!context) return []; - const kindSet = new Set(kinds); - const needle = queryText.trim().toLowerCase(); - if (!needle) { - return filterNodesFromKindIndex(context.ref, kindSet, limit); - } - const manifest = await loadHostedSearchManifestFromRef(context.ref); - if (!manifest) return []; - const queryP = searchPrefix(needle); - const prefixes = manifest.prefixes.filter((prefix) => prefix.startsWith(queryP)); - const entries: NodeSummary[] = []; - for (const prefix of prefixes.slice(0, 64)) { - const shard = await loadHostedSearchShardFromRef(context.ref, prefix); - if (shard) entries.push(...shard.entries); - } - return searchSummaries(entries, queryText, limit, kindSet); - }, - - async getCrateStatus(name: string, version: string) { - if (!isValidCrateName(name) || !isValidVersion(version)) { - return { status: 'failed' as const, error: 'Invalid crate name or version' }; - } - const ref = await resolveRefForArtifact(name, version); - if (ref) { - const meta = await readArtifactJson(ref, 'site/meta.json'); - if (isCurrentHostedMeta(meta, ref)) { - return { status: 'ready' as const }; - } - } - const hostedStatus = await readHostedParseStatus(name, version); - // Artifact validation is authoritative for readiness. A completed parse row can - // outlive its artifact contract, for example after a clean schema migration. - if (hostedStatus && hostedStatus.status !== 'ready') { - return storedStatusToCrateStatus(hostedStatus); - } - return { - status: 'failed' as const, - error: `No static graph is published for ${name}@${version}.`, - action: 'docs_unavailable' as const, - }; - }, - - async triggerParse(name: string, version: string, force?: boolean) { - if (!isValidCrateName(name) || !isValidVersion(version)) { - return Result.err(new ValidationError({ message: 'Invalid crate name or version' })); - } - const normalizedName = normalizeCrateName(name); - const requestKind = isStdCrate(normalizedName) ? 'sysroot' : 'crate'; - const requestedVersion = - requestKind === 'sysroot' && version === 'latest' ? DEFAULT_RUST_CHANNEL : version; - if (requestKind === 'sysroot' && !isStdJsonCrate(normalizedName)) { - return Result.err( - new NotAvailableError({ - message: 'Hosted toolchain parsing supports std, core, alloc, proc_macro, and test.', - }), - ); - } - let parseContext: Awaited> | null = null; - if (force) { - parseContext = await resolveParseRequestContext({ rateLimit: false }); - if (!parseContext.auth?.isAdmin) { - return Result.err( - new NotAvailableError({ - message: 'Force parse requires admin access', - }), - ); - } - } - if (!force) { - const ref = await resolveRefForArtifact(name, requestedVersion); - if (ref) { - const meta = await readArtifactJson(ref, 'site/meta.json'); - if (isCurrentHostedMeta(meta, ref)) { - return Result.ok(undefined); - } - } - } - if (requestKind === 'sysroot' && !isRustChannel(requestedVersion)) { - return Result.err( - new NotAvailableError({ - message: HOSTED_SYSROOT_UNAVAILABLE_MESSAGE, - }), - ); - } - parseContext ??= await resolveParseRequestContext({ rateLimit: true }); - if (parseContext.configError) return Result.err(parseContext.configError); - if (parseContext.rateLimitError) return Result.err(parseContext.rateLimitError); - if (!env.PARSE_REQUESTS) { - return Result.err( - new NotAvailableError({ - message: 'Hosted parse queue is not configured', - }), - ); - } - const parseRequest = makeParseRequest( - name, - requestedVersion, - !!force, - 'ui', - requestKind, - parseContext.actor, - ); - const workflowId = parseWorkflowId(parseRequest.requestId); - if (env.PARSE_STATUS) { - try { - const registration = await registerQueuedParseRequest(env.PARSE_STATUS, parseRequest); - if (!registration.accepted) return Result.ok(undefined); - } catch (err) { - return Result.err( - new NotAvailableError({ - message: `Hosted parse queue registration failed: ${errorMessage(err)}`, - }), - ); - } - } - try { - await env.PARSE_REQUESTS.send(parseRequest); - } catch (err) { - await recordHostedParseEvent({ - kind: parseRequest.kind, - name: parseRequest.name, - version: parseRequest.version, - status: 'failed', - step: 'queue-send', - error: errorMessage(err), - requestId: parseRequest.requestId, - workflowId, - }).catch(() => {}); - return Result.err( - new NotAvailableError({ - message: `Hosted parse queue send failed: ${errorMessage(err)}`, - }), - ); - } - return Result.ok(undefined); - }, - - async triggerStdInstall(_name: string, _version: string) { - return Result.err( - new NotAvailableError({ - message: 'std crate installation is not available in hosted mode', - }), - ); - }, - - async searchRegistry(query: string) { - const needle = query.trim().toLowerCase(); - if (!needle) return []; - const toolchainResults = searchToolchainCrates(needle); - let registryResults: CrateSummaryResult[] = []; - const registryResult = getRegistry('rust'); - if (!registryResult.isErr()) { - const live = await registryResult.value.search(needle, 20); - registryResults = live.map(registrySummary); - } - if (registryResults.length === 0) { - const crates = await listPublishedCrates(); - registryResults = crates - .map((crate) => { - const name = crate.name.toLowerCase(); - const id = (crate.id ?? crate.name).toLowerCase(); - const description = crate.description?.toLowerCase() ?? ''; - if (name === needle || id === needle) return { crate, score: 0 }; - if (name.startsWith(needle) || id.startsWith(needle)) return { crate, score: 1 }; - if (name.includes(needle) || id.includes(needle)) return { crate, score: 2 }; - if (description.includes(needle)) return { crate, score: 3 }; - return null; - }) - .filter((entry): entry is { crate: CrateSummaryResult; score: number } => entry !== null) - .sort( - (a, b) => - a.score - b.score || - a.crate.name.localeCompare(b.crate.name, undefined, { sensitivity: 'base' }), - ) - .map((entry) => entry.crate); - } - - const merged = [...toolchainResults, ...registryResults]; - const seen = new Set(); - return merged - .filter((crate) => { - const key = `${crate.id ?? crate.name}@${crate.version}`; - if (seen.has(key)) return false; - seen.add(key); - return true; - }) - .slice(0, 20); - }, - - async getTopCrates(limit = 10) { - const registryResult = getRegistry('rust'); - if (!registryResult.isErr()) { - const live = await registryResult.value.listTop(limit); - if (live.length > 0) return live.map(registrySummary); - } - return (await listPublishedCrates()).slice(0, limit); - }, - - async getProcessingCrates(limit = 20) { - return (await listHostedProcessing(limit)).map((entry) => ({ - id: hyphenateCrateName(entry.name), - name: entry.name, - version: entry.version, - description: entry.step ?? 'Parsing', - })); - }, - - async getParseQueue(limit = 50): Promise { - return buildParseQueueSnapshot(limit); - }, - - async getAdminDashboard(limit = 100): Promise { - const queue = await buildParseQueueSnapshot(limit); - const allowance = await buildParseAllowance(queue); - return { queue, allowance }; - }, - - async getCrateVersions(name: string, limit = Number.POSITIVE_INFINITY): Promise { - return listPublishedVersions(name, limit); - }, - - async resolveVersion(name: string, version: string): Promise { - if (version === 'latest' && isStdCrate(normalizeCrateName(name))) return 'stable'; - if (version === 'latest') return (await firstPublishedVersion(name)) ?? version; - const ref = await resolveRefForArtifact(name, version); - return ref?.version ?? version; - }, - }; + const mutableJsonCache = Effect.runSync( + Cache.makeWith( + (key: string) => + readR2JsonEffect(env.CRATE_GRAPHS, key).pipe( + Effect.catch((err: R2JsonError) => + Effect.sync(() => { + log.warn`${err.message}`; + return null; + }), + ), + ), + { + capacity: JSON_CACHE_MAX, + timeToLive: (exit, key) => { + if (!Exit.isSuccess(exit) || exit.value === null) return Duration.zero; + return key.includes("/_refs/") + ? Duration.millis(REF_TTL_MS) + : Duration.millis(MUTABLE_JSON_TTL_MS); + }, + }, + ), + ); + + function sourceCacheKey( + crateName: string, + crateVersion: string, + file: string, + sourceProvider: SourceProviderMode, + ): string { + return `${crateName}|${crateVersion}|${sourceProvider}|${file}`; + } + + function getCachedSourceFile(key: string): string | null { + const value = sourceFileCache.get(key); + if (value === undefined) return null; + sourceFileCache.delete(key); + sourceFileCache.set(key, value); + return value; + } + + function setCachedSourceFile(key: string, content: string): void { + if (sourceFileCache.has(key)) sourceFileCache.delete(key); + sourceFileCache.set(key, content); + while (sourceFileCache.size > SOURCE_FILE_CACHE_MAX) { + const oldestKey = sourceFileCache.keys().next().value; + if (oldestKey === undefined) break; + sourceFileCache.delete(oldestKey); + } + } + + function anonymousParseRateLimitKey(): string { + const ip = + request?.headers.get("cf-connecting-ip") ?? + request?.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? + "anonymous"; + return `parse:anon:${ip}`; + } + + async function resolveParseRequestContext({ rateLimit }: { rateLimit: boolean }) { + const auth = request ? await getAuthStateFromRequest(request, env) : null; + const actor = actorFromUser(auth?.user ?? null); + if (!rateLimit) return { auth, actor, rateLimitError: null, configError: null }; + + const limiter = actor + ? (env.RATE_LIMIT_PARSE_AUTH ?? env.RATE_LIMIT_API_AUTH ?? env.RATE_LIMIT_API) + : (env.RATE_LIMIT_PARSE_ANON ?? env.RATE_LIMIT_API_ANON ?? env.RATE_LIMIT_API); + if (!limiter) { + return { + auth, + actor, + rateLimitError: null, + configError: new NotAvailableError({ + message: "Hosted parse rate limiting is not configured", + }), + }; + } + + const key = actor ? `parse:user:${actor.id}` : anonymousParseRateLimitKey(); + const outcome = await limiter.limit({ key }); + if (outcome.success) return { auth, actor, rateLimitError: null, configError: null }; + return { + auth, + actor, + configError: null, + rateLimitError: new RateLimitError({ + message: actor + ? "Too many signed-in parse requests. Try again shortly." + : "Too many anonymous parse requests. Sign in for a higher limit or try again shortly.", + }), + }; + } + + function readJson(key: string, _ttlMs = MUTABLE_JSON_TTL_MS): Promise { + return Effect.runPromise(Cache.get(mutableJsonCache, key)) as Promise; + } + + async function readArtifactJson(ref: ArtifactRef, path: string): Promise { + const r2Key = artifactR2Key(ref, path); + const cacheUrl = artifactCacheUrl(ref, path); + if (!cacheUrl) return readJson(r2Key); + + let cached = artifactJsonCache.get(cacheUrl); + if (!cached) { + cached = readArtifactJsonWithCache(env.CRATE_GRAPHS, r2Key, cacheUrl).catch((err) => { + artifactJsonCache.delete(cacheUrl); + log.warn`R2 artifact read failed for ${r2Key}: ${String(err)}`; + return null; + }); + setArtifactJsonCache(cacheUrl, cached); + } + return cached as Promise; + } + + async function readCrateRefs(storageName: string): Promise { + const raw = await readJson(refsKey(storageName), REF_TTL_MS); + if (!raw) return null; + const refs = parseCrateRefs(raw); + if (!refs) { + log.warn`Invalid crate refs at ${refsKey(storageName)}`; + return null; + } + return refs; + } + + async function resolveRefForArtifactUncached( + name: string, + version: string, + ): Promise { + for (const variant of uniqueCrateNameVariants(name)) { + const refs = await readCrateRefs(variant); + if (!refs) continue; + const ref = resolveRefFromRefs(refs, version); + if (!ref) continue; + const meta = await readArtifactJson(ref, "site/meta.json"); + if (!isCurrentHostedMeta(meta, ref)) continue; + return ref; + } + + return null; + } + + async function resolveRefForArtifact(name: string, version: string): Promise { + const key = resolvedRefCacheKey(name, version); + const cached = getCachedResolvedRef(key); + if (cached) return cached; + + const pending = resolveRefForArtifactUncached(name, version) + .then((ref) => { + setCachedResolvedRef(key, Promise.resolve(ref), Date.now() + REF_TTL_MS); + return ref; + }) + .catch((err) => { + resolvedRefCache.delete(key); + throw err; + }); + setCachedResolvedRef(key, pending, Date.now() + REF_TTL_MS); + return pending; + } + + async function listPublishedVersionsFromRefs( + name: string, + limit: number, + ): Promise { + for (const variant of uniqueCrateNameVariants(name)) { + const refs = await readCrateRefs(variant); + if (!refs) continue; + return refs.versions.map((entry) => entry.version).slice(0, limit); + } + return null; + } + + async function listRegistryVersions(name: string, limit: number): Promise { + if (isStdCrate(normalizeCrateName(name))) return []; + const registryResult = getRegistry("rust"); + if (registryResult.isErr()) return []; + for (const variant of uniqueCrateNameVariants(name)) { + const versions = await registryResult.value.listVersions(variant, limit); + if (versions.length > 0) return versions; + } + return []; + } + + function mergeVersions(primary: string[], secondary: string[] | null, limit: number): string[] { + const versions: string[] = []; + const seen = new Set(); + for (const version of [...primary, ...(secondary ?? [])]) { + if (seen.has(version)) continue; + seen.add(version); + versions.push(version); + if (versions.length >= limit) break; + } + return versions; + } + + async function loadHostedContext( + name: string, + version: string, + ): Promise<{ ref: ArtifactRef; meta: HostedMetaArtifact } | null> { + const ref = await resolveRefForArtifact(name, version); + if (!ref) return null; + const meta = await readArtifactJson(ref, "site/meta.json"); + return isCurrentHostedMeta(meta, ref) ? { ref, meta } : null; + } + + async function loadHostedMetaArtifact( + name: string, + version: string, + ): Promise { + return (await loadHostedContext(name, version))?.meta ?? null; + } + + async function loadHostedKindShardFromRef( + ref: ArtifactRef, + kind: NodeKind, + ): Promise { + const shard = await readArtifactJson(ref, `site/kinds/${kind}.json`); + return isCurrentHostedArtifact(shard, ref) && shard?.kind === kind ? shard : null; + } + + async function filterNodesFromKindIndex( + ref: ArtifactRef, + kinds: Set, + limit: number, + ): Promise { + const pageKinds = Array.from(kinds).filter((kind) => kind !== "Impl"); + if (pageKinds.length === 0) return []; + const shards = await Promise.all( + pageKinds.sort().map((kind) => loadHostedKindShardFromRef(ref, kind)), + ); + const completeShards = shards.filter((shard): shard is HostedKindShard => shard !== null); + if (completeShards.length !== shards.length) { + log.error`Incomplete kind index for ${ref.storageName}@${ref.version}`; + return []; + } + const entries = completeShards + .flatMap((shard) => shard.entries) + .filter((entry) => entry.kind !== "Impl"); + if (shards.length <= 1) return entries.slice(0, limit); + return entries.sort((a, b) => a.id.localeCompare(b.id)).slice(0, limit); + } + + async function loadHostedAlias( + ref: ArtifactRef, + meta: HostedMetaArtifact, + nodeId: string, + ): Promise { + const bucket = nodeViewBucket(nodeId, meta.artifacts.aliasBucketCount); + const shard = await readArtifactJson(ref, `site/aliases/${bucket}.json`); + if ( + !isCurrentHostedArtifact(shard, ref) || + shard?.bucketCount !== meta.artifacts.aliasBucketCount + ) { + return null; + } + return shard.aliases[nodeId]?.canonicalId ?? null; + } + + async function loadMaterializedNodeView( + hostedRef: ArtifactRef, + hostedMeta: HostedMetaArtifact, + nodeId: string, + ): Promise { + async function loadEntry(id: string): Promise { + const bucketCount = hostedMeta.artifacts.nodeViewBucketCount; + const bucket = nodeViewBucket(id, bucketCount); + const shard = await readArtifactJson( + hostedRef, + `site/node-views/${bucket}.json`, + ); + if (!isCurrentHostedArtifact(shard, hostedRef) || shard?.bucketCount !== bucketCount) { + return null; + } + return shard.entries[id] ?? null; + } + + let resolvedId = nodeId; + let entry = await loadEntry(resolvedId); + if (!entry) { + const canonical = await loadHostedAlias(hostedRef, hostedMeta, nodeId); + if (canonical && canonical !== nodeId) { + resolvedId = canonical; + entry = await loadEntry(resolvedId); + } + } + return entry + ? { + detail: entry.detail, + ancestors: entry.ancestors, + } + : null; + } + + async function loadNodeView( + name: string, + version: string, + nodeId: string, + ): Promise { + const context = await loadHostedContext(name, version); + if (!context) return null; + const view = await loadMaterializedNodeView(context.ref, context.meta, nodeId); + if (!view) return null; + + const traitIds = Array.from( + new Set( + view.detail.relatedNodes + .filter( + (node) => + node.kind === "Impl" && node.impl_category === "Trait" && Boolean(node.impl_trait), + ) + .map((node) => node.impl_trait as string), + ), + ); + if (traitIds.length === 0) return view; + + const traitEntries = await Promise.all( + traitIds.map(async (traitId): Promise<[string, NodeViewBase] | null> => { + const traitCrate = traitId.split("::")[0]; + if (!traitCrate) return null; + let traitContext = context; + if (normalizeCrateName(traitCrate) !== normalizeCrateName(name)) { + if (!isStdCrate(traitCrate)) return null; + const externalContext = await loadHostedContext(traitCrate, "latest"); + if (!externalContext) return null; + traitContext = externalContext; + } + const traitView = await loadMaterializedNodeView( + traitContext.ref, + traitContext.meta, + traitId, + ); + return traitView ? [traitId, traitView] : null; + }), + ); + return mergeTraitMemberDocumentation( + view, + new Map(traitEntries.filter((entry): entry is [string, NodeViewBase] => entry !== null)), + ); + } + + async function loadHostedSearchManifestFromRef( + ref: ArtifactRef, + ): Promise { + const manifest = await readArtifactJson(ref, "site/search-manifest.json"); + return isCurrentHostedArtifact(manifest, ref) ? manifest : null; + } + + async function loadHostedSearchShardFromRef( + ref: ArtifactRef, + prefix: string, + ): Promise { + const shard = await readArtifactJson(ref, `site/search/${prefix}.json`); + return isCurrentHostedArtifact(shard, ref) && shard?.prefix === prefix ? shard : null; + } + + async function loadHostedTreeChildrenFromContext( + context: { ref: ArtifactRef; meta: HostedMetaArtifact }, + parentId: string, + ): Promise { + const bucket = treeChildrenBucket(parentId, context.meta.artifacts.treeChildrenBucketCount); + const shard = await readArtifactJson( + context.ref, + `site/tree-children/${bucket}.json`, + ); + if ( + !isCurrentHostedArtifact(shard, context.ref) || + shard?.bucketCount !== context.meta.artifacts.treeChildrenBucketCount + ) { + return null; + } + return shard.parents[parentId]?.children ?? null; + } + + async function loadCatalogArtifact(): Promise { + const catalog = await readJson("rust/catalog.json"); + if ( + catalog?.schema_version !== STATIC_ARTIFACT_SCHEMA_VERSION || + !Array.isArray(catalog.crates) + ) { + return null; + } + return catalog; + } + + async function listPublishedVersions( + name: string, + limit = Number.POSITIVE_INFINITY, + ): Promise { + const [refsVersions, registryVersions] = await Promise.all([ + listPublishedVersionsFromRefs(name, limit), + listRegistryVersions(name, limit), + ]); + if (isStdCrate(normalizeCrateName(name))) { + return mergeVersions([...RUST_CHANNEL_ORDER], refsVersions, limit); + } + if (registryVersions.length > 0) return mergeVersions(registryVersions, refsVersions, limit); + return refsVersions ?? []; + } + + async function firstPublishedVersion(name: string): Promise { + return (await listPublishedVersions(name, 1))[0] ?? null; + } + + function storedStatusToCrateStatus(stored: StoredParseStatus) { + return { + status: stored.status, + error: stored.error, + step: stored.step, + action: stored.action, + installedVersion: stored.installedVersion, + }; + } + + async function readHostedParseStatus( + name: string, + version: string, + ): Promise { + if (!env.PARSE_STATUS) return null; + const url = new URL("https://status/status"); + url.searchParams.set("name", name); + url.searchParams.set("version", version); + const response = await parseStatusObject(env.PARSE_STATUS).fetch(url); + if (!response.ok) return null; + return (await response.json()) as StoredParseStatus | null; + } + + async function listHostedProcessing(limit: number): Promise { + if (!env.PARSE_STATUS) return []; + const url = new URL("https://status/processing"); + url.searchParams.set("limit", String(limit)); + const response = await parseStatusObject(env.PARSE_STATUS).fetch(url); + if (!response.ok) return []; + return (await response.json()) as StoredParseStatus[]; + } + + async function readHostedQueue(limit: number): Promise { + if (!env.PARSE_STATUS) return { active: [], recent: [] }; + const url = new URL("https://status/queue"); + url.searchParams.set("limit", String(limit)); + const response = await parseStatusObject(env.PARSE_STATUS).fetch(url); + if (!response.ok) return { active: [], recent: [] }; + return (await response.json()) as StoredParseQueueSnapshot; + } + + function githubHeaders(): HeadersInit { + const headers: Record = { + accept: "application/vnd.github+json", + "user-agent": USER_AGENT, + "x-github-api-version": GITHUB_API_VERSION, + }; + if (env.GITHUB_TOKEN) headers.authorization = `Bearer ${env.GITHUB_TOKEN}`; + return headers; + } + + function workflowRunToActiveRun(run: GitHubWorkflowRun): ActiveParseRun | null { + if (!run.id || !run.html_url || !run.created_at || !run.updated_at) return null; + return { + id: String(run.id), + title: run.display_title || run.name || "parse", + status: run.status ?? "unknown", + event: run.event ?? "workflow", + branch: run.head_branch, + url: run.html_url, + createdAt: run.created_at, + updatedAt: run.updated_at, + }; + } + + async function listActiveGitHubParseRuns(limit: number): Promise { + const repo = env.GITHUB_REPO; + if (!repo) return []; + const workflowFile = env.GITHUB_WORKFLOW_FILE ?? DEFAULT_GITHUB_WORKFLOW_FILE; + const runs = await Promise.all( + ACTIVE_GITHUB_RUN_STATUSES.map(async (status) => { + const url = new URL( + `https://api.github.com/repos/${repo}/actions/workflows/${workflowFile}/runs`, + ); + url.searchParams.set("status", status); + url.searchParams.set("per_page", String(Math.max(1, Math.min(limit, 20)))); + const response = await fetch(url, { headers: githubHeaders() }); + if (!response.ok) { + log.warn`GitHub workflow run lookup failed status=${status} code=${String(response.status)}`; + return []; + } + const body = (await response.json()) as GitHubWorkflowRunsResponse; + return (body.workflow_runs ?? []) + .map(workflowRunToActiveRun) + .filter((run): run is ActiveParseRun => run !== null); + }), + ); + const byId = new Map(); + for (const run of runs.flat()) byId.set(run.id, run); + return [...byId.values()] + .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) + .slice(0, Math.max(1, Math.min(limit, 20))); + } + + async function loadGitHubRepository(): Promise { + const repo = env.GITHUB_REPO; + if (!repo) return null; + const response = await fetch(`https://api.github.com/repos/${repo}`, { + headers: githubHeaders(), + }); + if (!response.ok) { + log.warn`GitHub repository lookup failed code=${String(response.status)}`; + return null; + } + return (await response.json()) as GitHubRepositoryResponse; + } + + function emptyBillingSummary( + owner: string, + accountType: GitHubActionsBillingSummary["accountType"], + error?: string, + ): GitHubActionsBillingSummary { + return { + available: false, + owner, + accountType, + totalMinutesUsed: null, + totalPaidMinutesUsed: null, + error, + }; + } + + function unmeteredBillingSummary( + owner: string, + accountType: GitHubActionsBillingSummary["accountType"], + ): GitHubActionsBillingSummary { + return { + available: true, + owner, + accountType, + totalMinutesUsed: null, + totalPaidMinutesUsed: null, + }; + } + + function actionsBillingUsageUrl( + owner: string, + accountType: GitHubActionsBillingSummary["accountType"], + ): string { + const path = + accountType === "Organization" + ? `/organizations/${owner}/settings/billing/usage/summary` + : `/users/${owner}/settings/billing/usage/summary`; + const url = new URL(`https://api.github.com${path}`); + url.searchParams.set("product", "Actions"); + if (env.GITHUB_REPO) url.searchParams.set("repository", env.GITHUB_REPO); + return url.toString(); + } + + async function loadGitHubActionsBilling( + repository: GitHubRepositoryResponse | null, + ): Promise { + const owner = repository?.owner?.login ?? env.GITHUB_REPO?.split("/")[0] ?? ""; + const ownerType = + repository?.owner?.type === "Organization" + ? "Organization" + : repository?.owner?.type === "User" + ? "User" + : "unknown"; + if (!owner) return emptyBillingSummary("", "unknown", "GITHUB_REPO is not configured"); + if (!env.GITHUB_TOKEN) + return emptyBillingSummary(owner, ownerType, "GITHUB_TOKEN is not configured"); + + const response = await fetch(actionsBillingUsageUrl(owner, ownerType), { + headers: githubHeaders(), + }); + if (!response.ok) { + return emptyBillingSummary( + owner, + ownerType, + `GitHub billing usage unavailable: ${response.status} ${response.statusText}`, + ); + } + const body = (await response.json()) as GitHubBillingUsageSummaryResponse; + return { + available: true, + owner, + accountType: ownerType, + totalMinutesUsed: totalGrossActionsMinutes(body), + totalPaidMinutesUsed: totalBillableActionsMinutes(body), + }; + } + + function workflowRunDurationMinutes(run: GitHubWorkflowRun, nowMs: number): number { + const start = run.created_at ? Date.parse(run.created_at) : NaN; + if (!Number.isFinite(start)) return 0; + const isActive = run.status + ? (ACTIVE_GITHUB_RUN_STATUSES as readonly string[]).includes(run.status) + : false; + const updated = run.updated_at ? Date.parse(run.updated_at) : NaN; + const end = isActive ? nowMs : Number.isFinite(updated) ? updated : nowMs; + return Math.max(0, (end - start) / 60_000); + } + + async function estimateParseWorkflowMinutesThisMonth(): Promise { + const repo = env.GITHUB_REPO; + if (!repo) return null; + const workflowFile = env.GITHUB_WORKFLOW_FILE ?? DEFAULT_GITHUB_WORKFLOW_FILE; + const startedAt = monthStartIso(); + let total = 0; + let loaded = 0; + const nowMs = Date.now(); + for (let page = 1; page <= 5; page += 1) { + const url = new URL( + `https://api.github.com/repos/${repo}/actions/workflows/${workflowFile}/runs`, + ); + url.searchParams.set("created", `>=${startedAt}`); + url.searchParams.set("per_page", "100"); + url.searchParams.set("page", String(page)); + const response = await fetch(url, { headers: githubHeaders() }); + if (!response.ok) { + log.warn`GitHub monthly workflow usage lookup failed code=${String(response.status)}`; + return null; + } + const body = (await response.json()) as GitHubWorkflowRunsResponse; + const runs = body.workflow_runs ?? []; + loaded += runs.length; + for (const run of runs) total += workflowRunDurationMinutes(run, nowMs); + if (runs.length < 100) break; + } + return loaded > 0 ? total : 0; + } + + async function buildParseQueueSnapshot(limit: number): Promise { + return Effect.runPromise( + Effect.gen(function* () { + const boundedLimit = Math.max(1, Math.min(limit, 100)); + const [queue, activeRuns] = yield* Effect.all( + [ + Effect.tryPromise({ + try: () => readHostedQueue(boundedLimit), + catch: (cause) => new Error(`hosted queue load failed: ${errorMessage(cause)}`), + }).pipe( + Effect.catch((err) => + Effect.sync(() => { + log.warn`${err.message}`; + return { active: [], recent: [] } satisfies StoredParseQueueSnapshot; + }), + ), + ), + Effect.tryPromise({ + try: () => listActiveGitHubParseRuns(boundedLimit), + catch: (cause) => + new Error(`active GitHub parse run load failed: ${errorMessage(cause)}`), + }).pipe( + Effect.catch((err) => + Effect.sync(() => { + log.warn`${err.message}`; + return [] as ActiveParseRun[]; + }), + ), + ), + ], + { concurrency: 2 }, + ); + const recent = yield* Effect.promise(() => removeStaleFailedQueueEntries(queue.recent)); + const planned = yield* Effect.tryPromise({ + try: () => loadLatestPlannedRun(boundedLimit), + catch: (cause) => new Error(`planned parse run load failed: ${errorMessage(cause)}`), + }).pipe( + Effect.catch((err) => + Effect.sync(() => { + log.warn`${err.message}`; + return null; + }), + ), + ); + return { + active: queue.active.map((entry, index) => storedStatusToQueueEntry(entry, index + 1)), + activeRuns, + recent: recent.map((entry) => storedStatusToQueueEntry(entry)), + planned, + } satisfies ParseQueueSnapshot; + }), + ); + } + + async function hasReadyArtifact(name: string, version: string): Promise { + const ref = await resolveRefForArtifact(name, version); + if (!ref) return false; + const meta = await readArtifactJson(ref, "site/meta.json"); + return isCurrentHostedMeta(meta, ref); + } + + async function removeStaleFailedQueueEntries( + entries: StoredParseStatus[], + ): Promise { + const stale = await Promise.all( + entries.map(async (entry) => { + if (entry.status !== "failed") return false; + return hasReadyArtifact(entry.name, entry.version).catch(() => false); + }), + ); + return entries.filter((_, index) => !stale[index]); + } + + async function buildParseAllowance(queue: ParseQueueSnapshot): Promise { + const activeTarget = parsePositiveInteger( + env.PLAN_DRAIN_ACTIVE_TARGET, + DEFAULT_PLAN_DRAIN_ACTIVE_TARGET, + ); + const batchSize = parseNonNegativeInteger( + env.PLAN_DRAIN_BATCH_SIZE, + DEFAULT_PLAN_DRAIN_BATCH_SIZE, + ); + const repoUsageTargetPercent = parsePositiveNumber( + env.GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT, + DEFAULT_GITHUB_ACTIONS_REPO_USAGE_TARGET_PERCENT, + ); + const trackedActiveCount = queue.active.length; + const githubActiveRunCount = queue.activeRuns.length; + const actionsInUse = Math.max(trackedActiveCount, githubActiveRunCount); + const availableSlots = Math.max(0, activeTarget - actionsInUse); + const [repository, estimatedRepoMinutesThisMonth] = await Promise.all([ + loadGitHubRepository().catch(() => null), + estimateParseWorkflowMinutesThisMonth().catch(() => null), + ]); + const repoPrivate = typeof repository?.private === "boolean" ? repository.private : null; + const standardRunnerMinutesMetered = repoPrivate === null ? null : repoPrivate; + const loadedBilling = await loadGitHubActionsBilling(repository).catch((err) => + emptyBillingSummary( + repository?.owner?.login ?? env.GITHUB_REPO?.split("/")[0] ?? "", + repository?.owner?.type === "Organization" + ? "Organization" + : repository?.owner?.type === "User" + ? "User" + : "unknown", + errorMessage(err), + ), + ); + const billing = + standardRunnerMinutesMetered === false && !loadedBilling.available + ? unmeteredBillingSummary( + repository?.owner?.login ?? env.GITHUB_REPO?.split("/")[0] ?? "", + repository?.owner?.type === "Organization" + ? "Organization" + : repository?.owner?.type === "User" + ? "User" + : "unknown", + ) + : loadedBilling; + return { + repo: repository?.full_name ?? env.GITHUB_REPO ?? null, + workflowFile: env.GITHUB_WORKFLOW_FILE ?? DEFAULT_GITHUB_WORKFLOW_FILE, + activeTarget, + batchSize, + trackedActiveCount, + githubActiveRunCount, + actionsInUse, + availableSlots, + repoUsageTargetPercent, + repoPrivate, + standardRunnerMinutesMetered, + monthStartedAt: monthStartIso(), + estimatedRepoMinutesThisMonth, + billing, + }; + } + + async function recordHostedParseEvent(event: ParseStatusEvent): Promise { + if (!env.PARSE_STATUS) return; + const response = await parseStatusObject(env.PARSE_STATUS).fetch("https://status/event", { + method: "POST", + headers: { "content-type": "application/json; charset=utf-8" }, + body: JSON.stringify(event), + }); + if (!response.ok) { + throw new Error(`parse status update failed: ${response.status}`); + } + } + + function storedStatusToQueueEntry(stored: StoredParseStatus, position?: number): ParseQueueEntry { + return { + kind: stored.kind, + name: stored.name, + version: stored.version, + status: stored.status, + step: stored.step, + error: stored.error, + requestId: stored.requestId, + workflowId: stored.workflowId, + githubRunId: stored.githubRunId, + githubRunUrl: stored.githubRunUrl, + requestedBy: stored.requestedBy, + requestedAt: stored.createdAt, + updatedAt: stored.updatedAt, + position, + }; + } + + function planReasonParserTarget(reason: string | undefined): string | null { + const match = /\bparser\s+\S+\s+(?:\u2192|->)\s+([0-9a-fA-F]{7,40})\b/.exec(reason ?? ""); + return match?.[1] ?? null; + } + + function planReasonSchemaTarget(reason: string | undefined): number | null { + const match = /\bschema\s+v\d+\s+(?:\u2192|->)\s+v(\d+)\b/.exec(reason ?? ""); + if (!match?.[1]) return null; + const value = Number.parseInt(match[1], 10); + return Number.isFinite(value) ? value : null; + } + + function revisionMatches(actual: string | undefined, target: string): boolean { + return !!actual && (actual === target || actual.startsWith(target)); + } + + function freshnessParsedAfterPlan(freshness: FreshnessEntry, planGeneratedAt: string): boolean { + const generatedAtMs = Date.parse(planGeneratedAt); + const parsedAtMs = Date.parse(freshness.parsedAt ?? ""); + return Number.isFinite(generatedAtMs) && Number.isFinite(parsedAtMs) + ? parsedAtMs >= generatedAtMs + : false; + } + + async function readPlanFreshness( + item: Pick, + ): Promise { + for (const variant of crateNameVariants(item.name)) { + const entry = await readJson( + `rust/_index/by-version/${normalizeCrateName(variant)}/${item.version}.json`, + ); + if (entry) return entry; + } + return null; + } + + async function plannedItemSatisfiedByFreshness( + item: Pick, + planGeneratedAt: string, + ): Promise { + const freshness = await readPlanFreshness(item); + if (!freshness) return false; + + const parserTarget = planReasonParserTarget(item.reason); + if (parserTarget) + return ( + revisionMatches(freshness.parserRevision, parserTarget) || + freshnessParsedAfterPlan(freshness, planGeneratedAt) + ); + + const schemaTarget = planReasonSchemaTarget(item.reason); + if (schemaTarget !== null) + return ( + freshness.schemaVersion === schemaTarget || + freshnessParsedAfterPlan(freshness, planGeneratedAt) + ); + + if ( + item.priorityTier === "never-parsed-backfill" || + item.priorityTier === "newer-version" || + item.reason.includes("never parsed") || + item.reason.includes("crates.io") + ) { + return freshness.version === item.version; + } + + const generatedAtMs = Date.parse(planGeneratedAt); + const parsedAtMs = Date.parse(freshness.parsedAt ?? ""); + return freshness.version === item.version && Number.isFinite(generatedAtMs) + ? Number.isFinite(parsedAtMs) && parsedAtMs >= generatedAtMs + : freshness.version === item.version; + } + + function planItemFromArtifact( + item: NonNullable[number], + ): Omit | null { + if (!item.name || !item.version) return null; + const kind = item.kind === "std" || item.kind === "sysroot" ? "sysroot" : "crate"; + return { + kind, + name: item.name, + version: item.version, + channel: item.channel ?? "default", + priorityTier: item.priority_tier ?? item.priorityTier ?? "unknown", + reason: item.reason ?? "", + downloadRank: item.download_rank ?? item.downloadRank, + workId: item.work_id ?? item.workId ?? `${kind}:${item.name}:${item.version}`, + }; + } + + async function planFromArtifact( + plan: WorkPlanArtifact, + limit: number, + ): Promise { + const runId = plan.run_id ?? plan.runId; + const generatedAt = plan.generated_at ?? plan.generatedAt; + if (!runId || !generatedAt) return null; + const work = Array.isArray(plan.work) ? plan.work : []; + const candidates = work + .map(planItemFromArtifact) + .filter((entry): entry is Omit => entry !== null); + const annotated = await Promise.all( + candidates.map(async (entry) => { + const ready = await plannedItemSatisfiedByFreshness(entry, generatedAt); + return { ...entry, state: ready ? ("ready" as const) : ("pending" as const) }; + }), + ); + const pending = annotated.filter((entry) => entry.state === "pending"); + const ready = annotated.filter((entry) => entry.state === "ready"); + const pendingShown = pending.slice(0, Math.max(1, limit)); + const readySlots = Math.max(0, Math.max(1, limit) - pendingShown.length); + const items = [...pendingShown, ...ready.slice(0, readySlots)]; + return { + runId, + generatedAt, + mode: plan.mode ?? "unknown", + shardCount: plan.shard_count ?? plan.shardCount ?? 0, + total: pending.length, + pending: pending.length, + ready: ready.length, + items, + }; + } + + async function listPlanKeys(maxKeys = 5000): Promise { + const candidates: PlanKeyCandidate[] = []; + let cursor: string | undefined; + do { + const page = await env.CRATE_GRAPHS.list({ + prefix: "rust/_runs/", + limit: Math.min(1000, Math.max(1, maxKeys - candidates.length)), + cursor, + }); + for (const object of page.objects) { + if (object.key.endsWith("/plan.json")) { + candidates.push({ + key: object.key, + uploaded: object.uploaded?.toISOString(), + }); + } + if (candidates.length >= maxKeys) break; + } + cursor = page.truncated ? page.cursor : undefined; + } while (cursor && candidates.length < maxKeys); + return candidates.sort( + (a, b) => (b.uploaded ?? "").localeCompare(a.uploaded ?? "") || b.key.localeCompare(a.key), + ); + } + + async function loadLatestPlannedRun(limit: number): Promise { + const plans = await Promise.all( + (await listPlanKeys()).slice(0, 25).map(async ({ key }) => { + const raw = await readJson(key); + return raw ? await planFromArtifact(raw, limit) : null; + }), + ); + return ( + plans + .filter((plan): plan is PlannedParseRun => plan !== null) + .sort((a, b) => b.generatedAt.localeCompare(a.generatedAt))[0] ?? null + ); + } + + let publishedCratesCache: Promise | null = null; + async function listPublishedCrates(): Promise { + if (!publishedCratesCache) { + publishedCratesCache = (async () => { + const catalog = await loadCatalogArtifact(); + if (catalog) { + return orderCatalogSummaries(catalog.crates) satisfies CrateSummaryResult[]; + } + return []; + })().catch((err) => { + publishedCratesCache = null; + log.warn`published crate catalog load failed: ${String(err)}`; + return []; + }); + } + return publishedCratesCache; + } + + return { + async loadSourceFile( + relativePath: string, + crateName?: string, + crateVersion?: string, + sourceProvider: SourceProviderMode = "auto", + ) { + if (!crateName || !crateVersion) { + return { + error: "Source file not available", + content: null, + absolutePath: null, + repoUrl: null, + }; + } + + const cacheKey = sourceCacheKey(crateName, crateVersion, relativePath, sourceProvider); + const cachedContent = getCachedSourceFile(cacheKey); + if (cachedContent !== null) { + return { error: null, content: cachedContent, absolutePath: null, repoUrl: null }; + } + + // ── Std fast-path ───────────────────────────────────────── + // std/core/alloc/proc_macro/test aren't on crates.io. Their + // sources live in rust-lang/rust under `library/{crate}/...`. + // rustdoc spans already use that form, so we just point at + // the right git ref and stream the file. + if (isStdCrate(normalizeCrateName(crateName))) { + const result = await fetchStdSourceFile( + relativePath, + crateVersion, + SOURCE_MAX_BYTES, + USER_AGENT, + ); + if ("content" in result) { + setCachedSourceFile(cacheKey, result.content); + return { + error: null, + content: result.content, + absolutePath: null, + repoUrl: result.blobUrl, + }; + } + return { error: result.error, content: null, absolutePath: null, repoUrl: result.blobUrl }; + } + + const sourceAdapterResult = getSourceAdapter("rust"); + if (sourceAdapterResult.isErr()) { + return { + error: sourceAdapterResult.error.message, + content: null, + absolutePath: null, + repoUrl: null, + }; + } + + const registryResult = getRegistry("rust"); + if (registryResult.isErr()) { + return { + error: registryResult.error.message, + content: null, + absolutePath: null, + repoUrl: null, + }; + } + + let metadata: Awaited> | null = null; + for (const variant of crateNameVariants(crateName)) { + const resolved = await registryResult.value.resolve(variant, crateVersion); + if (resolved) { + metadata = resolved; + break; + } + } + if (!metadata) { + return { + error: "Source metadata unavailable", + content: null, + absolutePath: null, + repoUrl: null, + }; + } + + const repoUrl = buildGitHubFileUrl(metadata, relativePath); + + if ( + (sourceProvider === "auto" || sourceProvider === "crates-io") && + metadata.sourceArchiveUrl + ) { + const direct = await fetchSourceFileFromArchive(metadata.sourceArchiveUrl, relativePath, { + maxBytes: SOURCE_MAX_BYTES, + userAgent: USER_AGENT, + }); + if (direct.status === "ok") { + setCachedSourceFile(cacheKey, direct.content); + return { error: null, content: direct.content, absolutePath: null, repoUrl }; + } + if (sourceProvider === "crates-io") { + return { + error: direct.status === "error" ? direct.message : "Source file not available", + content: null, + absolutePath: null, + repoUrl: null, + }; + } + } + + const providers = sourceAdapterResult.value.getProviders({ + ecosystem: "rust", + name: metadata.name, + version: metadata.version, + metadata, + }); + const selectedProviders = source.selectProviders(providers, sourceProvider); + const files = await fetchSourcesWithProviders( + selectedProviders, + { ecosystem: "rust", name: metadata.name, version: metadata.version, metadata }, + { + maxBytes: SOURCE_MAX_BYTES, + userAgent: USER_AGENT, + githubToken: env.GITHUB_TOKEN, + }, + ); + if (!files) { + return { + error: "Source file not available", + content: null, + absolutePath: null, + repoUrl: null, + }; + } + + const content = source.resolveFromMap(files, relativePath); + if (content === null) { + return { error: "File not found", content: null, absolutePath: null, repoUrl }; + } + setCachedSourceFile(cacheKey, content); + return { error: null, content, absolutePath: null, repoUrl }; + }, + + async loadCrateGraph(name: string, version: string): Promise { + return null; + }, + + async loadTreeMeta(name: string, version: string) { + const meta = await loadHostedMetaArtifact(name, version); + return meta ? { kindCounts: meta.kindCounts, roots: meta.roots } : null; + }, + + async loadTreeRootsDirect(name: string, version: string): Promise { + return (await loadHostedMetaArtifact(name, version))?.roots ?? []; + }, + + async loadTreeChildrenDirect( + name: string, + version: string, + parentId: string, + ): Promise { + const context = await loadHostedContext(name, version); + if (!context) return []; + const rootChildren = context.meta.rootChildren[parentId]; + if (rootChildren !== undefined) return rootChildren; + return (await loadHostedTreeChildrenFromContext(context, parentId)) ?? []; + }, + + async loadTreeAncestorsDirect( + name: string, + version: string, + nodeId: string, + ): Promise { + const view = await loadNodeView(name, version, nodeId); + return view?.ancestors ?? []; + }, + + async loadCrateTree(name: string, version: string): Promise { + return null; + }, + + async loadCrateIndex(name: string, version: string): Promise { + return (await loadHostedMetaArtifact(name, version))?.index ?? null; + }, + + async loadNodeViewDirect( + name: string, + version: string, + nodeId: string, + ): Promise { + return loadNodeView(name, version, nodeId); + }, + + async loadNodeDetail( + name: string, + version: string, + nodeId: string, + ): Promise { + const view = await loadNodeView(name, version, nodeId); + return view?.detail ?? null; + }, + + async loadCrateMap( + name: string, + version: string, + options?: CrateMapOptions, + ): Promise { + const context = await loadHostedContext(name, version); + if (!context) return null; + return readArtifactJson(context.ref, "crate-map.json"); + }, + + async getCrossEdgeData(_nodeId: string): Promise { + return { edges: [], nodes: [] }; + }, + + async searchNodesDirect( + crateName: string, + crateVersion: string, + queryText: string, + limit = 200, + kinds: NodeKind[] = [], + ): Promise { + const context = await loadHostedContext(crateName, crateVersion); + if (!context) return []; + const kindSet = new Set(kinds); + const needle = queryText.trim().toLowerCase(); + if (!needle) { + return filterNodesFromKindIndex(context.ref, kindSet, limit); + } + const manifest = await loadHostedSearchManifestFromRef(context.ref); + if (!manifest) return []; + const queryP = searchPrefix(needle); + const prefixes = manifest.prefixes.filter((prefix) => prefix.startsWith(queryP)); + const entries: NodeSummary[] = []; + for (const prefix of prefixes.slice(0, 64)) { + const shard = await loadHostedSearchShardFromRef(context.ref, prefix); + if (shard) entries.push(...shard.entries); + } + return searchSummaries(entries, queryText, limit, kindSet); + }, + + async getCrateStatus(name: string, version: string) { + if (!isValidCrateName(name) || !isValidVersion(version)) { + return { status: "failed" as const, error: "Invalid crate name or version" }; + } + const ref = await resolveRefForArtifact(name, version); + if (ref) { + const meta = await readArtifactJson(ref, "site/meta.json"); + if (isCurrentHostedMeta(meta, ref)) { + return { status: "ready" as const }; + } + } + const hostedStatus = await readHostedParseStatus(name, version); + // Artifact validation is authoritative for readiness. A completed parse row can + // outlive its artifact contract, for example after a clean schema migration. + if (hostedStatus && hostedStatus.status !== "ready") { + return storedStatusToCrateStatus(hostedStatus); + } + return { + status: "failed" as const, + error: `No static graph is published for ${name}@${version}.`, + action: "docs_unavailable" as const, + }; + }, + + async triggerParse(name: string, version: string, force?: boolean) { + if (!isValidCrateName(name) || !isValidVersion(version)) { + return Result.err(new ValidationError({ message: "Invalid crate name or version" })); + } + const normalizedName = normalizeCrateName(name); + const requestKind = isStdCrate(normalizedName) ? "sysroot" : "crate"; + const requestedVersion = + requestKind === "sysroot" && version === "latest" ? DEFAULT_RUST_CHANNEL : version; + if (requestKind === "sysroot" && !isStdJsonCrate(normalizedName)) { + return Result.err( + new NotAvailableError({ + message: "Hosted toolchain parsing supports std, core, alloc, proc_macro, and test.", + }), + ); + } + let parseContext: Awaited> | null = null; + if (force) { + parseContext = await resolveParseRequestContext({ rateLimit: false }); + if (!parseContext.auth?.isAdmin) { + return Result.err( + new NotAvailableError({ + message: "Force parse requires admin access", + }), + ); + } + } + if (!force) { + const ref = await resolveRefForArtifact(name, requestedVersion); + if (ref) { + const meta = await readArtifactJson(ref, "site/meta.json"); + if (isCurrentHostedMeta(meta, ref)) { + return Result.ok(undefined); + } + } + } + if (requestKind === "sysroot" && !isRustChannel(requestedVersion)) { + return Result.err( + new NotAvailableError({ + message: HOSTED_SYSROOT_UNAVAILABLE_MESSAGE, + }), + ); + } + parseContext ??= await resolveParseRequestContext({ rateLimit: true }); + if (parseContext.configError) return Result.err(parseContext.configError); + if (parseContext.rateLimitError) return Result.err(parseContext.rateLimitError); + if (!env.PARSE_REQUESTS) { + return Result.err( + new NotAvailableError({ + message: "Hosted parse queue is not configured", + }), + ); + } + const parseRequest = makeParseRequest( + name, + requestedVersion, + !!force, + "ui", + requestKind, + parseContext.actor, + ); + const workflowId = parseWorkflowId(parseRequest.requestId); + if (env.PARSE_STATUS) { + try { + const registration = await registerQueuedParseRequest(env.PARSE_STATUS, parseRequest); + if (!registration.accepted) return Result.ok(undefined); + } catch (err) { + return Result.err( + new NotAvailableError({ + message: `Hosted parse queue registration failed: ${errorMessage(err)}`, + }), + ); + } + } + try { + await env.PARSE_REQUESTS.send(parseRequest); + } catch (err) { + await recordHostedParseEvent({ + kind: parseRequest.kind, + name: parseRequest.name, + version: parseRequest.version, + status: "failed", + step: "queue-send", + error: errorMessage(err), + requestId: parseRequest.requestId, + workflowId, + }).catch(() => {}); + return Result.err( + new NotAvailableError({ + message: `Hosted parse queue send failed: ${errorMessage(err)}`, + }), + ); + } + return Result.ok(undefined); + }, + + async triggerStdInstall(_name: string, _version: string) { + return Result.err( + new NotAvailableError({ + message: "std crate installation is not available in hosted mode", + }), + ); + }, + + async searchRegistry(query: string) { + const needle = query.trim().toLowerCase(); + if (!needle) return []; + const toolchainResults = searchToolchainCrates(needle); + let registryResults: CrateSummaryResult[] = []; + const registryResult = getRegistry("rust"); + if (!registryResult.isErr()) { + const live = await registryResult.value.search(needle, 20); + registryResults = live.map(registrySummary); + } + if (registryResults.length === 0) { + const crates = await listPublishedCrates(); + registryResults = crates + .map((crate) => { + const name = crate.name.toLowerCase(); + const id = (crate.id ?? crate.name).toLowerCase(); + const description = crate.description?.toLowerCase() ?? ""; + if (name === needle || id === needle) return { crate, score: 0 }; + if (name.startsWith(needle) || id.startsWith(needle)) return { crate, score: 1 }; + if (name.includes(needle) || id.includes(needle)) return { crate, score: 2 }; + if (description.includes(needle)) return { crate, score: 3 }; + return null; + }) + .filter((entry): entry is { crate: CrateSummaryResult; score: number } => entry !== null) + .sort( + (a, b) => + a.score - b.score || + a.crate.name.localeCompare(b.crate.name, undefined, { sensitivity: "base" }), + ) + .map((entry) => entry.crate); + } + + const merged = [...toolchainResults, ...registryResults]; + const seen = new Set(); + return merged + .filter((crate) => { + const key = `${crate.id ?? crate.name}@${crate.version}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }) + .slice(0, 20); + }, + + async getTopCrates(limit = 10) { + const registryResult = getRegistry("rust"); + if (!registryResult.isErr()) { + const live = await registryResult.value.listTop(limit); + if (live.length > 0) return live.map(registrySummary); + } + return (await listPublishedCrates()).slice(0, limit); + }, + + async getProcessingCrates(limit = 20) { + return (await listHostedProcessing(limit)).map((entry) => ({ + id: hyphenateCrateName(entry.name), + name: entry.name, + version: entry.version, + description: entry.step ?? "Parsing", + })); + }, + + async getParseQueue(limit = 50): Promise { + return buildParseQueueSnapshot(limit); + }, + + async getAdminDashboard(limit = 100): Promise { + const queue = await buildParseQueueSnapshot(limit); + const allowance = await buildParseAllowance(queue); + return { queue, allowance }; + }, + + async getCrateVersions(name: string, limit = Number.POSITIVE_INFINITY): Promise { + return listPublishedVersions(name, limit); + }, + + async resolveVersion(name: string, version: string): Promise { + if (version === "latest" && isStdCrate(normalizeCrateName(name))) return "stable"; + if (version === "latest") return (await firstPublishedVersion(name)) ?? version; + const ref = await resolveRefForArtifact(name, version); + return ref?.version ?? version; + }, + }; } /** Build-time entry point imported through the `$provider` alias. */ export function createProvider(event: RequestEvent): DataProvider { - const env = (event.platform as { env: AppEnv }).env; - return createCloudflareProvider(env, event.request); + const env = (event.platform as { env: AppEnv }).env; + return createCloudflareProvider(env, event.request); } /** Hosted mode uses the parser status Durable Object for realtime parse/status events. */ export function handleWsUpgrade(event?: RequestEvent): Response | Promise { - if (!event) - return new Response('Hosted realtime status requires a request event', { status: 500 }); - const env = (event?.platform as { env?: AppEnv } | undefined)?.env; - if (!env?.PARSE_STATUS) { - return new Response('Hosted realtime status is not configured', { status: 503 }); - } - return parseStatusObject(env.PARSE_STATUS).fetch(event.request); + if (!event) + return new Response("Hosted realtime status requires a request event", { status: 500 }); + const env = (event?.platform as { env?: AppEnv } | undefined)?.env; + if (!env?.PARSE_STATUS) { + return new Response("Hosted realtime status is not configured", { status: 503 }); + } + return parseStatusObject(env.PARSE_STATUS).fetch(event.request); } diff --git a/codeview-ui/src/lib/server/cloudflare/workers/parse-worker.d.ts b/codeview-ui/src/lib/server/cloudflare/workers/parse-worker.d.ts index d72bbb8..b8af758 100644 --- a/codeview-ui/src/lib/server/cloudflare/workers/parse-worker.d.ts +++ b/codeview-ui/src/lib/server/cloudflare/workers/parse-worker.d.ts @@ -2,36 +2,54 @@ // Generated by Wrangler by running `wrangler types --config=./wrangler.parser.toml src/lib/server/cloudflare/workers/parse-worker.d.ts` (hash: dcc16970e44945608e3234d0e5eb9f15) // Runtime types generated with workerd@1.20260706.1 2026-07-08 nodejs_compat interface __BaseEnv_Env { - CRATE_GRAPHS: R2Bucket; - PARSE_REQUESTS: Queue; - GITHUB_REPO: "themixednuts/codeview"; - GITHUB_REF: "main"; - GITHUB_WORKFLOW_FILE: "parse.yml"; - PARSE_CALLBACK_BASE_URL: "https://codeview-parser.jonfonts.workers.dev"; - PARSE_DISPATCH_BURST: "4"; - PARSE_DISPATCH_REFILL_SECONDS: "45"; - DOCSRS_PARSE_BURST: "4"; - DOCSRS_PARSE_REFILL_SECONDS: "20"; - SYSROOT_PARSE_BURST: "1"; - SYSROOT_PARSE_REFILL_SECONDS: "600"; - PLAN_DRAIN_ACTIVE_TARGET: "4"; - PLAN_DRAIN_BATCH_SIZE: "0"; - PARSE_STATUS: DurableObjectNamespace; - PARSE_WORKFLOW: Workflow[0]['payload']>; + CRATE_GRAPHS: R2Bucket; + PARSE_REQUESTS: Queue; + GITHUB_REPO: "themixednuts/codeview"; + GITHUB_REF: "main"; + GITHUB_WORKFLOW_FILE: "parse.yml"; + PARSE_CALLBACK_BASE_URL: "https://codeview-parser.jonfonts.workers.dev"; + PARSE_DISPATCH_BURST: "4"; + PARSE_DISPATCH_REFILL_SECONDS: "45"; + DOCSRS_PARSE_BURST: "4"; + DOCSRS_PARSE_REFILL_SECONDS: "20"; + SYSROOT_PARSE_BURST: "1"; + SYSROOT_PARSE_REFILL_SECONDS: "600"; + PLAN_DRAIN_ACTIVE_TARGET: "4"; + PLAN_DRAIN_BATCH_SIZE: "0"; + PARSE_STATUS: DurableObjectNamespace; + PARSE_WORKFLOW: Workflow< + Parameters[0]["payload"] + >; } declare namespace Cloudflare { - interface GlobalProps { - mainModule: typeof import("../../../../parse-worker"); - durableNamespaces: "ParseStatusDurableObject"; - } - interface Env extends __BaseEnv_Env {} + interface GlobalProps { + mainModule: typeof import("../../../../parse-worker"); + durableNamespaces: "ParseStatusDurableObject"; + } + interface Env extends __BaseEnv_Env {} } interface Env extends __BaseEnv_Env {} type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; + [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; }; declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} + interface ProcessEnv extends StringifyValues< + Pick< + Cloudflare.Env, + | "GITHUB_REPO" + | "GITHUB_REF" + | "GITHUB_WORKFLOW_FILE" + | "PARSE_CALLBACK_BASE_URL" + | "PARSE_DISPATCH_BURST" + | "PARSE_DISPATCH_REFILL_SECONDS" + | "DOCSRS_PARSE_BURST" + | "DOCSRS_PARSE_REFILL_SECONDS" + | "SYSROOT_PARSE_BURST" + | "SYSROOT_PARSE_REFILL_SECONDS" + | "PLAN_DRAIN_ACTIVE_TARGET" + | "PLAN_DRAIN_BATCH_SIZE" + > + > {} } // Begin runtime types @@ -58,63 +76,63 @@ declare var onmessage: never; * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) */ declare class DOMException extends Error { - constructor(message?: string, name?: string); - /** - * 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; - /** - * 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) - */ - readonly code: number; - static readonly INDEX_SIZE_ERR: number; - static readonly DOMSTRING_SIZE_ERR: number; - static readonly HIERARCHY_REQUEST_ERR: number; - static readonly WRONG_DOCUMENT_ERR: number; - static readonly INVALID_CHARACTER_ERR: number; - static readonly NO_DATA_ALLOWED_ERR: number; - static readonly NO_MODIFICATION_ALLOWED_ERR: number; - static readonly NOT_FOUND_ERR: number; - static readonly NOT_SUPPORTED_ERR: number; - static readonly INUSE_ATTRIBUTE_ERR: number; - static readonly INVALID_STATE_ERR: number; - static readonly SYNTAX_ERR: number; - static readonly INVALID_MODIFICATION_ERR: number; - static readonly NAMESPACE_ERR: number; - static readonly INVALID_ACCESS_ERR: number; - static readonly VALIDATION_ERR: number; - static readonly TYPE_MISMATCH_ERR: number; - static readonly SECURITY_ERR: number; - static readonly NETWORK_ERR: number; - static readonly ABORT_ERR: number; - static readonly URL_MISMATCH_ERR: number; - static readonly QUOTA_EXCEEDED_ERR: number; - static readonly TIMEOUT_ERR: number; - static readonly INVALID_NODE_TYPE_ERR: number; - static readonly DATA_CLONE_ERR: number; - get stack(): any; - set stack(value: any); + constructor(message?: string, name?: string); + /** + * 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; + /** + * 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) + */ + readonly code: number; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; + get stack(): any; + set stack(value: any); } type WorkerGlobalScopeEventMap = { - fetch: FetchEvent; - scheduled: ScheduledEvent; - queue: QueueEvent; - unhandledrejection: PromiseRejectionEvent; - rejectionhandled: PromiseRejectionEvent; + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; }; declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget; + EventTarget: typeof EventTarget; } /* 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). @@ -122,186 +140,197 @@ declare abstract class WorkerGlobalScope extends EventTarget; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - class Instance { - constructor(module: Module, imports?: Imports); - readonly exports: Exports; - } - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - class Memory { - constructor(descriptor: MemoryDescriptor); - readonly buffer: ArrayBuffer; - grow(delta: number): number; - } - type ImportExportKind = "function" | "global" | "memory" | "table"; - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[]; - static exports(module: Module): ModuleExportDescriptor[]; - static imports(module: Module): ModuleImportDescriptor[]; - } - type TableKind = "anyfunc" | "externref"; - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - class Table { - constructor(descriptor: TableDescriptor, value?: any); - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; - } - function instantiate(module: Module, imports?: Imports): Promise; - function validate(bytes: BufferSource): boolean; + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; } /** * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. @@ -310,94 +339,112 @@ declare namespace WebAssembly { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) */ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException; - WorkerGlobalScope: typeof WorkerGlobalScope; - btoa(data: string): string; - atob(data: string): string; - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; - setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - self: ServiceWorkerGlobalScope; - crypto: Crypto; - caches: CacheStorage; - scheduler: Scheduler; - performance: Performance; - Cloudflare: Cloudflare; - readonly origin: string; - Event: typeof Event; - ExtendableEvent: typeof ExtendableEvent; - CustomEvent: typeof CustomEvent; - PromiseRejectionEvent: typeof PromiseRejectionEvent; - FetchEvent: typeof FetchEvent; - TailEvent: typeof TailEvent; - TraceEvent: typeof TailEvent; - ScheduledEvent: typeof ScheduledEvent; - MessageEvent: typeof MessageEvent; - CloseEvent: typeof CloseEvent; - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; - ReadableStream: typeof ReadableStream; - WritableStream: typeof WritableStream; - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; - TransformStream: typeof TransformStream; - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; - CountQueuingStrategy: typeof CountQueuingStrategy; - ErrorEvent: typeof ErrorEvent; - MessageChannel: typeof MessageChannel; - MessagePort: typeof MessagePort; - EventSource: typeof EventSource; - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; - ReadableStreamDefaultController: typeof ReadableStreamDefaultController; - ReadableByteStreamController: typeof ReadableByteStreamController; - WritableStreamDefaultController: typeof WritableStreamDefaultController; - TransformStreamDefaultController: typeof TransformStreamDefaultController; - CompressionStream: typeof CompressionStream; - DecompressionStream: typeof DecompressionStream; - TextEncoderStream: typeof TextEncoderStream; - TextDecoderStream: typeof TextDecoderStream; - Headers: typeof Headers; - Body: typeof Body; - Request: typeof Request; - Response: typeof Response; - WebSocket: typeof WebSocket; - WebSocketPair: typeof WebSocketPair; - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; - AbortController: typeof AbortController; - AbortSignal: typeof AbortSignal; - TextDecoder: typeof TextDecoder; - TextEncoder: typeof TextEncoder; - navigator: Navigator; - Navigator: typeof Navigator; - URL: typeof URL; - URLSearchParams: typeof URLSearchParams; - URLPattern: typeof URLPattern; - Blob: typeof Blob; - File: typeof File; - FormData: typeof FormData; - Crypto: typeof Crypto; - SubtleCrypto: typeof SubtleCrypto; - CryptoKey: typeof CryptoKey; - CacheStorage: typeof CacheStorage; - Cache: typeof Cache; - FixedLengthStream: typeof FixedLengthStream; - IdentityTransformStream: typeof IdentityTransformStream; - HTMLRewriter: typeof HTMLRewriter; -} -declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; -declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + Cloudflare: Cloudflare; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + MessageChannel: typeof MessageChannel; + MessagePort: typeof MessagePort; + EventSource: typeof EventSource; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + TransformStreamDefaultController: typeof TransformStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | boolean, +): void; /** * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ -declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ declare function btoa(data: string): string; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ @@ -405,13 +452,21 @@ declare function atob(data: string): string; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ declare function clearTimeout(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ declare function clearInterval(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ @@ -421,245 +476,313 @@ declare function structuredClone(value: T, options?: StructuredSerializeOptio /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ declare function reportError(error: any): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +declare function fetch( + input: RequestInfo | URL, + init?: RequestInit, +): Promise; declare const self: ServiceWorkerGlobalScope; /** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ + * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. + * The Workers runtime implements the full surface of this API, but with some differences in + * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) + * compared to those implemented in most browsers. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) + */ declare const crypto: Crypto; /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ declare const caches: CacheStorage; declare const scheduler: Scheduler; /** -* 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/) -*/ + * 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 const performance: Performance; declare const Cloudflare: Cloudflare; declare const origin: string; declare const navigator: Navigator; -interface TestController { -} +interface TestController {} interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - cache?: CacheContext; - readonly access?: CloudflareAccessContext; - tracing: Tracing; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerConnectHandler = (socket: Socket, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - connect?: ExportedHandlerConnectHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; + waitUntil(promise: Promise): void; + passThroughOnException(): void; + readonly exports: Cloudflare.Exports; + readonly props: Props; + cache?: CacheContext; + readonly access?: CloudflareAccessContext; + tracing: Tracing; +} +type ExportedHandlerFetchHandler = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +type ExportedHandlerConnectHandler = ( + socket: Socket, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTailStreamHandler = ( + event: TailStream.TailEvent, + env: Env, + ctx: ExecutionContext, +) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +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[]; + transfer?: any[]; } declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean; - readonly userAgent: string; - readonly hardwareConcurrency: number; - readonly platform: string; - readonly language: string; - readonly languages: string[]; + sendBeacon(url: string, body?: BodyInit): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; + readonly platform: string; + readonly language: string; + readonly languages: string[]; } interface AlarmInvocationInfo { - readonly isRetry: boolean; - readonly retryCount: number; - readonly scheduledTime: number; + readonly isRetry: boolean; + readonly retryCount: number; + readonly scheduledTime: number; } interface Cloudflare { - readonly compatibilityFlags: Record; + readonly compatibilityFlags: Record; } interface CachePurgeError { - code: number; - message: string; + code: number; + message: string; } interface CachePurgeResult { - success: boolean; - errors: CachePurgeError[]; + success: boolean; + errors: CachePurgeError[]; } interface CachePurgeOptions { - tags?: string[]; - pathPrefixes?: string[]; - purgeEverything?: boolean; + tags?: string[]; + pathPrefixes?: string[]; + purgeEverything?: boolean; } interface CacheContext { - purge(options: CachePurgeOptions): Promise; + purge(options: CachePurgeOptions): Promise; } interface CloudflareAccessContext { - readonly aud: string; - getIdentity(): Promise; + readonly aud: string; + getIdentity(): Promise; } declare abstract class ColoLocalActorNamespace { - get(actorId: string): Fetcher; + 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?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher & { - readonly id: DurableObjectId; - readonly name?: string; + fetch(request: Request): Response | Promise; + connect?(socket: Socket): void | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +type DurableObjectStub = Fetcher< + T, + "alarm" | "connect" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; }; interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; - readonly jurisdiction?: string; -} -declare abstract class DurableObjectNamespace { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; + readonly jurisdiction?: string; +} +declare abstract class DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + getByName( + name: string, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; } type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us"; interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me"; + jurisdiction?: DurableObjectJurisdiction; +} +type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "apac-ne" + | "apac-se" + | "oc" + | "afr" + | "me"; type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { + locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; } +interface 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[]; - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; - getHibernatableWebSocketEventTimeout(): number | null; - getTags(ws: WebSocket): string[]; - abort(reason?: string): void; + 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[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; } interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; } interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + kv: SyncKvStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; } interface DurableObjectListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; - allowConcurrency?: boolean; - noCache?: boolean; + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; + allowConcurrency?: boolean; } interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; } interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; } declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; + constructor(request: string, response: string); + 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; + 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; + id?: DurableObjectId | string; + class: DurableObjectClass; } interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; + writeDataPoint(event?: AnalyticsEngineDataPoint): void; } interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; } /** * The **`Event`** interface represents an event which takes place on an `EventTarget`. @@ -667,171 +790,181 @@ interface AnalyticsEngineDataPoint { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ declare class Event { - constructor(type: string, init?: EventInit); - /** - * 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; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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) - */ - composedPath(): EventTarget[]; - static readonly NONE: number; - static readonly CAPTURING_PHASE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; + constructor(type: string, init?: EventInit); + /** + * 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; + /** + * The **`eventPhase`** read-only property of the being evaluated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; } interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; } type EventListener = (event: EventType) => void; interface EventListenerObject { - handleEvent(event: EventType): void; + handleEvent(event: EventType): void; } -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +type EventListenerOrEventListenerObject = + | EventListener + | EventListenerObject; /** * 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(); - /** - * 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) - */ - addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean; + constructor(); + /** + * 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) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | boolean, + ): void; + /** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; } interface EventTargetEventListenerOptions { - capture?: boolean; + capture?: boolean; } interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; } interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; + handleEvent: (event: Event) => any | undefined; } /** * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. @@ -839,19 +972,19 @@ interface EventTargetHandlerObject { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) */ declare class AbortController { - constructor(); - /** - * 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; - /** - * 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; + constructor(); + /** + * 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; + /** + * 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; } /** * 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. @@ -859,52 +992,52 @@ declare class AbortController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) */ declare abstract class AbortSignal extends EventTarget { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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); - /** - * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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); + /** + * 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 { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; } interface SchedulerWaitOptions { - signal?: AbortSignal; + signal?: AbortSignal; } /** * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. @@ -912,12 +1045,12 @@ interface SchedulerWaitOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ declare abstract class ExtendableEvent extends Event { - /** - * 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; + /** + * 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; } /** * The **`CustomEvent`** interface represents events initialized by an application for any purpose. @@ -925,19 +1058,19 @@ declare abstract class ExtendableEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit); - /** - * 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) - */ - get detail(): T; + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * 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) + */ + get detail(): T; } interface CustomEventCustomEventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; - detail?: any; + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; } /** * 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. @@ -945,52 +1078,52 @@ interface CustomEventCustomEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ declare class Blob { - 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + type?: string; } /** * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. @@ -998,84 +1131,98 @@ interface BlobOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ declare class File extends Blob { - constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); - /** - * 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; - /** - * 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; + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** + * 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; + /** + * 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 { - type?: string; - lastModified?: number; + type?: string; + lastModified?: number; } /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ declare abstract class CacheStorage { - /** - * 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; + /** + * 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; } /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise; } interface CacheQueryOptions { - ignoreMethod?: boolean; + ignoreMethod?: boolean; } /** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ + * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. + * The Workers runtime implements the full surface of this API, but with some differences in + * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) + * compared to those implemented in most browsers. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) + */ 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; - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues(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) - */ - randomUUID(): string; - DigestStream: typeof DigestStream; + /** + * 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; + /** + * 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 + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | 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) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; } /** * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. @@ -1084,79 +1231,132 @@ declare abstract class Crypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) */ declare abstract class SubtleCrypto { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * 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; - /** - * 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, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * 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; - /** - * 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; - /** - * 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, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** + * 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; + /** + * 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, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** + * 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; + /** + * 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; + /** + * 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, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; } /** * 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. @@ -1165,133 +1365,139 @@ declare abstract class SubtleCrypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) */ declare abstract class CryptoKey { - /** - * 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; - /** - * 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; - /** - * 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 | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; - /** - * 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[]; + /** + * 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; + /** + * 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; + /** + * 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 + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** + * 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 { - publicKey: CryptoKey; - privateKey: CryptoKey; + publicKey: CryptoKey; + privateKey: CryptoKey; } interface JsonWebKey { - kty: string; - use?: string; - key_ops?: string[]; - alg?: string; - ext?: boolean; - crv?: string; - x?: string; - y?: string; - d?: string; - n?: string; - e?: string; - p?: string; - q?: string; - dp?: string; - dq?: string; - qi?: string; - oth?: RsaOtherPrimesInfo[]; - k?: string; + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; } interface RsaOtherPrimesInfo { - r?: string; - d?: string; - t?: string; + r?: string; + d?: string; + t?: string; } interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: (ArrayBuffer | ArrayBufferView); - iterations?: number; - hash?: (string | SubtleCryptoHashAlgorithm); - $public?: CryptoKey; - info?: (ArrayBuffer | ArrayBufferView); + name: string; + salt?: ArrayBuffer | ArrayBufferView; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer | ArrayBufferView; } interface SubtleCryptoEncryptAlgorithm { - name: string; - iv?: (ArrayBuffer | ArrayBufferView); - additionalData?: (ArrayBuffer | ArrayBufferView); - tagLength?: number; - counter?: (ArrayBuffer | ArrayBufferView); - length?: number; - label?: (ArrayBuffer | ArrayBufferView); + name: string; + iv?: ArrayBuffer | ArrayBufferView; + additionalData?: ArrayBuffer | ArrayBufferView; + tagLength?: number; + counter?: ArrayBuffer | ArrayBufferView; + length?: number; + label?: ArrayBuffer | ArrayBufferView; } interface SubtleCryptoGenerateKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - modulusLength?: number; - publicExponent?: (ArrayBuffer | ArrayBufferView); - length?: number; - namedCurve?: string; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer | ArrayBufferView; + length?: number; + namedCurve?: string; } interface SubtleCryptoHashAlgorithm { - name: string; + name: string; } interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - length?: number; - namedCurve?: string; - compressed?: boolean; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; } interface SubtleCryptoSignAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - dataLength?: number; - saltLength?: number; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; } interface CryptoKeyKeyAlgorithm { - name: string; + name: string; } interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; + name: string; + length: number; } interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; } interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; } interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; + name: string; + namedCurve: string; } interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; } declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; + get bytesWritten(): number | bigint; } /** * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. @@ -1299,16 +1505,16 @@ declare class DigestStream extends WritableStream * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) */ declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions); - /** - * 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) - */ - decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * 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) + */ + decode(input?: ArrayBuffer | ArrayBufferView, options?: TextDecoderDecodeOptions): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } /** * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. @@ -1316,31 +1522,31 @@ declare class TextDecoder { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) */ declare class TextEncoder { - constructor(); - /** - * 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; - /** - * 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: Uint8Array): TextEncoderEncodeIntoResult; - get encoding(): string; + constructor(); + /** + * 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; + /** + * 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: Uint8Array): TextEncoderEncodeIntoResult; + get encoding(): string; } interface TextDecoderConstructorOptions { - fatal: boolean; - ignoreBOM: boolean; + fatal: boolean; + ignoreBOM: boolean; } interface TextDecoderDecodeOptions { - stream: boolean; + stream: boolean; } interface TextEncoderEncodeIntoResult { - read: number; - written: number; + read: number; + written: number; } /** * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. @@ -1348,44 +1554,44 @@ interface TextEncoderEncodeIntoResult { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) */ declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + constructor(type: string, init?: ErrorEventErrorEventInit); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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 { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; } /** * The **`MessageEvent`** interface represents a message received by a target object. @@ -1393,40 +1599,40 @@ interface ErrorEventErrorEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) */ declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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) - */ - readonly ports: MessagePort[]; + constructor(type: string, initializer: MessageEventInit); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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) + */ + readonly ports: MessagePort[]; } interface MessageEventInit { - data: ArrayBuffer | string; + data: ArrayBuffer | string; } /** * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. @@ -1434,18 +1640,18 @@ interface MessageEventInit { * [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 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. @@ -1453,151 +1659,148 @@ declare abstract class PromiseRejectionEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ declare class FormData { - constructor(); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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 - ]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator<(File | string)>; - forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: File | string - ]>; + constructor(); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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]>; + /* Returns a list of keys in the list. */ + keys(): IterableIterator; + /* Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: (this: This, value: File | string, key: string, parent: FormData) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; } interface ContentOptions { - html?: boolean; + html?: boolean; } declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; + constructor(); + on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; } interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; } interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; } interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; } interface Element { - tagName: string; - readonly attributes: IterableIterator; - readonly removed: boolean; - readonly namespaceURI: string; - getAttribute(name: string): string | null; - hasAttribute(name: string): boolean; - setAttribute(name: string, value: string): Element; - removeAttribute(name: string): Element; - before(content: string | ReadableStream | Response, options?: ContentOptions): Element; - after(content: string | ReadableStream | Response, options?: ContentOptions): Element; - prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; - append(content: string | ReadableStream | Response, options?: ContentOptions): Element; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; - remove(): Element; - removeAndKeepContent(): Element; - setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; - onEndTag(handler: (tag: EndTag) => void | Promise): void; + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string | ReadableStream | Response, options?: ContentOptions): Element; + after(content: string | ReadableStream | Response, options?: ContentOptions): Element; + prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; + append(content: string | ReadableStream | Response, options?: ContentOptions): Element; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; } interface EndTag { - name: string; - before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - remove(): EndTag; + name: string; + before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + remove(): EndTag; } interface Comment { - text: string; - readonly removed: boolean; - before(content: string, options?: ContentOptions): Comment; - after(content: string, options?: ContentOptions): Comment; - replace(content: string, options?: ContentOptions): Comment; - remove(): Comment; + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; } interface Text { - readonly text: string; - readonly lastInTextNode: boolean; - readonly removed: boolean; - before(content: string | ReadableStream | Response, options?: ContentOptions): Text; - after(content: string | ReadableStream | Response, options?: ContentOptions): Text; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; - remove(): Text; + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string | ReadableStream | Response, options?: ContentOptions): Text; + after(content: string | ReadableStream | Response, options?: ContentOptions): Text; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; + remove(): Text; } interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd; + append(content: string, options?: ContentOptions): DocumentEnd; } /** * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. @@ -1605,19 +1808,19 @@ interface DocumentEnd { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) */ declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * 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; + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ + readonly request: Request; + /** + * 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; /** @@ -1626,77 +1829,83 @@ type HeadersInit = Headers | Iterable> | Record * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) */ declare class Headers { - constructor(init?: HeadersInit); - /** - * 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[]; - /** - * 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[]; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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, thisArg?: This): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable | AsyncIterable; + constructor(init?: HeadersInit); + /** + * 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[]; + /** + * 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[]; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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, + thisArg?: This, + ): void; + /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData + | Iterable + | AsyncIterable; declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; } /** * The **`Response`** interface of the Fetch API represents the response to a request. @@ -1704,11 +1913,11 @@ declare abstract class Body { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ declare var Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; - json(any: any, maybeInit?: (ResponseInit | Response)): Response; + prototype: Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; + json(any: any, maybeInit?: ResponseInit | Response): Response; }; /** * The **`Response`** interface of the Fetch API represents the response to a request. @@ -1716,74 +1925,79 @@ declare var Response: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ interface Response extends Body { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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"; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ + headers: Headers; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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 { - status?: number; - statusText?: string; - headers?: HeadersInit; - cf?: any; - webSocket?: (WebSocket | null); - encodeBody?: "automatic" | "manual"; + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; } -type RequestInfo> = Request | string; +type RequestInfo> = + | Request + | string; /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ declare var Request: { - prototype: Request; - new >(input: RequestInfo | URL, init?: RequestInit): Request; + prototype: Request; + new >( + input: RequestInfo | URL, + init?: RequestInit, + ): Request; }; /** * The **`Request`** interface of the Fetch API represents a resource request. @@ -1791,498 +2005,606 @@ declare var Request: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ interface Request> extends Body { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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" | "no-cache"; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * The **`headers`** read-only property of the with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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" | "no-cache"; } interface RequestInit { - /* A string to set request's method. */ - method?: string; - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string; - fetcher?: (Fetcher | null); - cf?: Cf; - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - 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. */ - signal?: (AbortSignal | null); - encodeResponseBody?: "automatic" | "manual"; -} -type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; + /* A string to set request's method. */ + method?: string; + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /* A string indicating how the request will interact with the browser's cache to set request's cache. */ + 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. */ + signal?: AbortSignal | null; + encodeResponseBody?: "automatic" | "manual"; +} +type Service< + T extends + | (new (...args: any[]) => Rpc.WorkerEntrypointBranded) + | Rpc.WorkerEntrypointBranded + | ExportedHandler + | undefined = undefined, +> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded + ? Fetcher> + : T extends Rpc.WorkerEntrypointBranded + ? Fetcher + : T extends Exclude + ? never + : Fetcher; +type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; }; interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; + name: Key; + expiration?: number; + metadata?: Metadata; +} +type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: "text"): Promise; - get(key: Key, type: "json"): Promise; - get(key: Key, type: "arrayBuffer"): Promise; - get(key: Key, type: "stream"): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; - get(key: Array, type: "text"): Promise>; - get(key: Array, type: "json"): Promise>; - get(key: Array, options?: Partial>): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; - list(options?: KVNamespaceListOptions): Promise>; - put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; - getWithMetadata(key: Key, options?: Partial>): Promise>; - getWithMetadata(key: Key, type: "text"): Promise>; - getWithMetadata(key: Key, type: "json"): Promise>; - getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; - getWithMetadata(key: Key, type: "stream"): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; - getWithMetadata(key: Array, type: "text"): Promise>>; - getWithMetadata(key: Array, type: "json"): Promise>>; - getWithMetadata(key: Array, options?: Partial>): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; - delete(key: Key): Promise; + get(key: Key, options?: Partial>): Promise; + get(key: Key, type: "text"): Promise; + get(key: Key, type: "json"): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; + get(key: Array, type: "text"): Promise>; + get( + key: Array, + type: "json", + ): Promise>; + get( + key: Array, + options?: Partial>, + ): Promise>; + get( + key: Array, + options?: KVNamespaceGetOptions<"text">, + ): Promise>; + get( + key: Array, + options?: KVNamespaceGetOptions<"json">, + ): Promise>; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + getWithMetadata( + key: Array, + type: "text", + ): Promise>>; + getWithMetadata( + key: Array, + type: "json", + ): Promise>>; + getWithMetadata( + key: Array, + options?: Partial>, + ): Promise>>; + getWithMetadata( + key: Array, + options?: KVNamespaceGetOptions<"text">, + ): Promise>>; + getWithMetadata( + key: Array, + options?: KVNamespaceGetOptions<"json">, + ): Promise>>; + delete(key: Key): Promise; } interface KVNamespaceListOptions { - limit?: number; - prefix?: (string | null); - cursor?: (string | null); + limit?: number; + prefix?: string | null; + cursor?: string | null; } interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; + type: Type; + cacheTtl?: number; } interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); + expiration?: number; + expirationTtl?: number; + metadata?: any | null; } interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; } type QueueContentType = "text" | "bytes" | "json" | "v8"; interface Queue { - metrics(): Promise; - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; + metrics(): Promise; + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; } interface QueueSendMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; } interface QueueSendMetadata { - metrics: QueueSendMetrics; + metrics: QueueSendMetrics; } interface QueueSendResponse { - metadata: QueueSendMetadata; + metadata: QueueSendMetadata; } interface QueueSendBatchMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; } interface QueueSendBatchMetadata { - metrics: QueueSendBatchMetrics; + metrics: QueueSendBatchMetrics; } interface QueueSendBatchResponse { - metadata: QueueSendBatchMetadata; + metadata: QueueSendBatchMetadata; } interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueSendBatchOptions { - delaySeconds?: number; + delaySeconds?: number; } interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; } interface MessageBatchMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; } interface MessageBatchMetadata { - metrics: MessageBatchMetrics; + metrics: MessageBatchMetrics; } interface QueueRetryOptions { - delaySeconds?: number; + delaySeconds?: number; } interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; } interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - readonly metadata: MessageBatchMetadata; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; + 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; + readonly messages: readonly Message[]; + readonly queue: string; + readonly metadata: MessageBatchMetadata; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; } interface R2Error extends Error { - readonly name: string; - readonly code: number; - readonly message: string; - readonly action: string; - readonly stack: any; + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; } interface R2ListOptions { - limit?: number; - prefix?: string; - cursor?: string; - delimiter?: string; - startAfter?: string; - include?: ("httpMetadata" | "customMetadata")[]; + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; } interface R2Bucket { - head(key: string): Promise; - get(key: string, options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - get(key: string, options?: R2GetOptions): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; } interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + options?: R2UploadPartOptions, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; } interface R2UploadedPart { - partNumber: number; - etag: string; + partNumber: number; + etag: string; } declare abstract class R2Object { - readonly key: string; - readonly version: string; - readonly size: number; - readonly etag: string; - readonly httpEtag: string; - readonly checksums: R2Checksums; - readonly uploaded: Date; - readonly httpMetadata?: R2HTTPMetadata; - readonly customMetadata?: Record; - readonly range?: R2Range; - readonly storageClass: string; - readonly ssecKeyMd5?: string; - writeHttpMetadata(headers: Headers): void; + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + readonly ssecKeyMd5?: string; + writeHttpMetadata(headers: Headers): void; } interface R2ObjectBody extends R2Object { - get body(): ReadableStream; - get bodyUsed(): boolean; - arrayBuffer(): Promise; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -type R2Range = { - offset: number; - length?: number; -} | { - offset?: number; - length: number; -} | { - suffix: number; -}; + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + bytes(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; } interface R2GetOptions { - onlyIf?: (R2Conditional | Headers); - range?: (R2Range | Headers); - ssecKey?: (ArrayBuffer | string); + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; + ssecKey?: ArrayBuffer | string; } interface R2PutOptions { - onlyIf?: (R2Conditional | Headers); - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - md5?: ((ArrayBuffer | ArrayBufferView) | string); - sha1?: ((ArrayBuffer | ArrayBufferView) | string); - sha256?: ((ArrayBuffer | ArrayBufferView) | string); - sha384?: ((ArrayBuffer | ArrayBufferView) | string); - sha512?: ((ArrayBuffer | ArrayBufferView) | string); - storageClass?: string; - ssecKey?: (ArrayBuffer | string); + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: (ArrayBuffer | ArrayBufferView) | string; + sha1?: (ArrayBuffer | ArrayBufferView) | string; + sha256?: (ArrayBuffer | ArrayBufferView) | string; + sha384?: (ArrayBuffer | ArrayBufferView) | string; + sha512?: (ArrayBuffer | ArrayBufferView) | string; + storageClass?: string; + ssecKey?: ArrayBuffer | string; } interface R2MultipartOptions { - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - storageClass?: string; - ssecKey?: (ArrayBuffer | string); + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; + ssecKey?: ArrayBuffer | string; } interface R2Checksums { - readonly md5?: ArrayBuffer; - readonly sha1?: ArrayBuffer; - readonly sha256?: ArrayBuffer; - readonly sha384?: ArrayBuffer; - readonly sha512?: ArrayBuffer; - toJSON(): R2StringChecksums; + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; } interface R2StringChecksums { - md5?: string; - sha1?: string; - sha256?: string; - sha384?: string; - sha512?: string; + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; } interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; } type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ({ - truncated: true; - cursor: string; -} | { - truncated: false; -}); + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); interface R2UploadPartOptions { - ssecKey?: (ArrayBuffer | string); + ssecKey?: ArrayBuffer | string; } declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface QueuingStrategy { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; } interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; } interface UnderlyingByteSource { - type: "bytes"; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; } interface UnderlyingSource { - type?: "" | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: (number | bigint); + type?: "" | undefined; + start?: (controller: ReadableStreamDefaultController) => void | Promise; + pull?: (controller: ReadableStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; } interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number; + readableType?: string; + writableType?: string; + start?: (controller: TransformStreamDefaultController) => void | Promise; + transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; + flush?: (controller: TransformStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + 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. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - signal?: AbortSignal; -} -type ReadableStreamReadResult = { - done: false; - value: R; -} | { - done: true; - value?: undefined; -}; + 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + signal?: AbortSignal; +} +type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; /** * 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 { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; } /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. @@ -2290,9 +2612,15 @@ interface ReadableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ declare const ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; }; /** * 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). @@ -2300,21 +2628,21 @@ declare const ReadableStream: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * 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>; - /** - * 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; + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * 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>; + /** + * 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; } /** * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. @@ -2322,33 +2650,36 @@ declare class ReadableStreamDefaultReader { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * 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>; - /** - * 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, view: T): Promise>; + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * 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>; + /** + * 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, + view: T, + ): Promise>; } interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number; + min?: number; } interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: "byob"; + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; } /** * 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). @@ -2356,25 +2687,25 @@ interface ReadableStreamGetReaderOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ declare abstract class ReadableStreamBYOBRequest { - /** - * 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; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; + /** + * 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; } /** * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. @@ -2382,30 +2713,30 @@ declare abstract class ReadableStreamBYOBRequest { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ declare abstract class ReadableStreamDefaultController { - /** - * 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; - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ + close(): void; + /** + * 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; + /** + * 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; } /** * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. @@ -2413,36 +2744,36 @@ declare abstract class ReadableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ declare abstract class ReadableByteStreamController { - /** - * 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; - /** - * 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; - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ + close(): void; + /** + * 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; + /** + * 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; } /** * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. @@ -2450,18 +2781,18 @@ declare abstract class ReadableByteStreamController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) */ declare abstract class WritableStreamDefaultController { - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; } /** * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. @@ -2469,39 +2800,39 @@ declare abstract class WritableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ declare abstract class TransformStreamDefaultController { - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -2509,31 +2840,31 @@ interface ReadableWritablePair { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) */ declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /** - * 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; - /** - * 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; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * 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; + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /** + * 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; + /** + * 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; + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ + close(): Promise; + /** + * 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; } /** * 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. @@ -2541,49 +2872,49 @@ declare class WritableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) */ declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void; + constructor(stream: WritableStream); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ + close(): Promise; + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ + write(chunk?: W): Promise; + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ + releaseLock(): void; } /** * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. @@ -2591,31 +2922,41 @@ declare class WritableStreamDefaultWriter { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ declare class TransformStream { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /** - * 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; - /** - * 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; + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** + * 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; + /** + * 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 { - constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); } -declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); } interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); + highWaterMark?: number | bigint; } interface ReadableStreamValuesOptions { - preventCancel?: boolean; + preventCancel?: boolean; } /** * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. @@ -2623,15 +2964,18 @@ interface ReadableStreamValuesOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); + constructor(format: "gzip" | "deflate" | "deflate-raw"); } /** * 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 { - constructor(format: "gzip" | "deflate" | "deflate-raw"); +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); } /** * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. @@ -2639,8 +2983,8 @@ declare class DecompressionStream extends TransformStream { - constructor(); - get encoding(): string; + constructor(); + get encoding(): string; } /** * 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. @@ -2648,14 +2992,14 @@ declare class TextEncoderStream extends TransformStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ declare class TextDecoderStream extends TransformStream { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; + fatal?: boolean; + ignoreBOM?: boolean; } /** * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. @@ -2663,15 +3007,15 @@ interface TextDecoderStreamTextDecoderStreamInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) */ declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * 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; + constructor(init: QueuingStrategyInit); + /** + * 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; } /** * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. @@ -2679,137 +3023,151 @@ declare class ByteLengthQueuingStrategy implements QueuingStrategy number; + constructor(init: QueuingStrategyInit); + /** + * 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; } interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; } interface TracePreviewInfo { - id: string; - slug: string; - name: string; + id: string; + slug: string; + name: string; } interface ScriptVersion { - id?: string; - tag?: string; - message?: string; + id?: string; + tag?: string; + message?: string; } declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; + readonly events: TraceItem[]; + readonly traces: TraceItem[]; } interface TraceItem { - readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; - readonly eventTimestamp: number | null; - readonly logs: TraceLog[]; - readonly exceptions: TraceException[]; - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; - readonly scriptName: string | null; - readonly entrypoint?: string; - 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; - readonly cpuTime: number; - readonly wallTime: number; + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemConnectEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + 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; + readonly cpuTime: number; + readonly wallTime: number; } interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date; -} -interface TraceItemConnectEventInfo { -} -interface TraceItemCustomEventInfo { + readonly scheduledTime: Date; } +interface TraceItemConnectEventInfo {} +interface TraceItemCustomEventInfo {} interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; + readonly scheduledTime: number; + readonly cron: string; } interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; + readonly queue: string; + readonly batchSize: number; } interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; } interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; } interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; + readonly scriptName: string | null; } interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoResponse { - readonly status: number; + readonly status: number; } interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; + readonly rpcMethod: string; } interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; } interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; } interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; + readonly timestamp: number; + readonly level: string; + readonly message: any; } interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; } interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; + readonly timestamp: number; + readonly channel: string; + readonly message: any; } interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; + readonly cpuTime: number; + readonly wallTime: number; } interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; + fromTrace(item: TraceItem): TraceMetrics; } /** * The **`URL`** interface is used to parse, construct, normalize, and encode URL. @@ -2817,171 +3175,171 @@ interface UnsafeTraceMetrics { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) */ declare class URL { - constructor(url: string | URL, base?: string | URL); - /** - * 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; - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; + constructor(url: string | URL, base?: string | URL); + /** + * 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; + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; } /** * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. @@ -2989,114 +3347,115 @@ declare class URL { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ declare class URLSearchParams { - constructor(init?: (Iterable> | Record | string)); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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[]; - /** - * 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; - /** - * 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; - /** - * 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 - ]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; - /*function toString() { [native code] }*/ - toString(): string; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; + constructor(init?: Iterable> | Record | string); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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[]; + /** + * 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; + /** + * 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; + /** + * 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]>; + /* Returns a list of keys in the search params. */ + keys(): IterableIterator; + /* Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, + thisArg?: This, + ): void; + /*function toString() { [native code] }*/ + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; } declare class URLPattern { - constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; + constructor( + input?: string | URLPatternInit, + baseURL?: string | URLPatternOptions, + patternOptions?: URLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + get hasRegExpGroups(): boolean; + test(input?: string | URLPatternInit, baseURL?: string): boolean; + exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; } interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; } interface URLPatternComponentResult { - input: string; - groups: Record; + input: string; + groups: Record; } interface URLPatternResult { - inputs: (string | URLPatternInit)[]; - protocol: URLPatternComponentResult; - username: URLPatternComponentResult; - password: URLPatternComponentResult; - hostname: URLPatternComponentResult; - port: URLPatternComponentResult; - pathname: URLPatternComponentResult; - search: URLPatternComponentResult; - hash: URLPatternComponentResult; + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; } interface URLPatternOptions { - ignoreCase?: boolean; + ignoreCase?: boolean; } /** * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. @@ -3104,36 +3463,36 @@ interface URLPatternOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) */ declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit); - /** - * 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; - /** - * 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; - /** - * 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) - */ - readonly wasClean: boolean; + constructor(type: string, initializer?: CloseEventInit); + /** + * 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; + /** + * 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; + /** + * 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) + */ + readonly wasClean: boolean; } interface CloseEventInit { - code?: number; - reason?: string; - wasClean?: boolean; + code?: number; + reason?: string; + wasClean?: boolean; } type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; }; /** * 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. @@ -3141,16 +3500,16 @@ type WebSocketEventMap = { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ declare var WebSocket: { - prototype: WebSocket; - new (url: string, protocols?: (string[] | string)): WebSocket; - readonly READY_STATE_CONNECTING: number; - readonly CONNECTING: number; - readonly READY_STATE_OPEN: number; - readonly OPEN: number; - readonly READY_STATE_CLOSING: number; - readonly CLOSING: number; - readonly READY_STATE_CLOSED: number; - readonly CLOSED: number; + prototype: WebSocket; + new (url: string, protocols?: string[] | string): WebSocket; + readonly READY_STATE_CONNECTING: number; + readonly CONNECTING: number; + readonly READY_STATE_OPEN: number; + readonly OPEN: number; + readonly READY_STATE_CLOSING: number; + readonly CLOSING: number; + readonly READY_STATE_CLOSED: number; + readonly CLOSED: number; }; /** * 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. @@ -3158,118 +3517,122 @@ declare var WebSocket: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(options?: WebSocketAcceptOptions): void; - /** - * 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; - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void; - serializeAttachment(attachment: any): void; - deserializeAttachment(): any | null; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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"; + accept(options?: WebSocketAcceptOptions): void; + /** + * 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; + /** + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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 (): { - 0: WebSocket; - 1: WebSocket; - }; + new (): { + 0: WebSocket; + 1: WebSocket; + }; }; interface SqlStorage { - exec>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement { -} + exec>( + query: string, + ...bindings: any[] + ): SqlStorageCursor; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement {} type SqlStorageValue = ArrayBuffer | string | number | null; declare abstract class SqlStorageCursor> { - next(): { + next(): + | { done?: false; value: T; - } | { + } + | { done: true; value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; + }; + toArray(): T[]; + one(): T; + raw(): IterableIterator; + columnNames: string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator; } interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): "on" | "off" | "starttls"; - close(): Promise; - startTls(options?: TlsOptions): Socket; + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + get upgraded(): boolean; + get secureTransport(): "on" | "off" | "starttls"; + close(): Promise; + startTls(options?: TlsOptions): Socket; } interface SocketOptions { - secureTransport?: string; - allowHalfOpen: boolean; - highWaterMark?: (number | bigint); + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: number | bigint; } interface SocketAddress { - hostname: string; - port: number; + hostname: string; + port: number; } interface TlsOptions { - expectedServerHostname?: string; + expectedServerHostname?: string; } interface SocketInfo { - remoteAddress?: string; - localAddress?: string; + remoteAddress?: string; + localAddress?: string; } /** * The **`EventSource`** interface is web content's interface to server-sent events. @@ -3277,118 +3640,120 @@ interface SocketInfo { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * The **`readyState`** read-only property of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; } interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; + withCredentials?: boolean; + fetcher?: Fetcher; } interface ExecOutput { - readonly stdout: ArrayBuffer; - readonly stderr: ArrayBuffer; - readonly exitCode: number; + 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"; + 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; + 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; - monitor(): Promise; - 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; + get running(): boolean; + start(options?: ContainerStartupOptions): void; + monitor(): Promise; + 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; + id: string; + size: number; + dir: string; + name?: string; } interface ContainerDirectorySnapshotOptions { - dir: string; - name?: string; + dir: string; + name?: string; } interface ContainerDirectorySnapshotRestoreParams { - snapshot: ContainerDirectorySnapshot; - mountPoint?: string; + snapshot: ContainerDirectorySnapshot; + mountPoint?: string; } interface ContainerSnapshot { - id: string; - size: number; - name?: string; + id: string; + size: number; + name?: string; } interface ContainerSnapshotOptions { - name?: string; + name?: string; } interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - labels?: Record; - directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; - containerSnapshot?: ContainerSnapshot; + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; + labels?: Record; + directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; + containerSnapshot?: ContainerSnapshot; } /** * 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. @@ -3396,26 +3761,26 @@ interface ContainerStartupOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ declare abstract class MessagePort extends EventTarget { - /** - * 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; - /** - * 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; - /** - * 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) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); + /** + * 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; + /** + * 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; + /** + * 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) + */ + start(): void; + 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. @@ -3423,119 +3788,142 @@ declare abstract class MessagePort extends EventTarget { * [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; + 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 LoopbackForExport 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 { -} + transfer?: any[]; +} +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; + 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; + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; } interface WorkerStub { - getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; - getDurableObjectClass(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass; + getEntrypoint( + name?: string, + options?: WorkerStubEntrypointOptions, + ): Fetcher; + getDurableObjectClass( + name?: string, + options?: WorkerStubEntrypointOptions, + ): DurableObjectClass; } interface WorkerStubEntrypointOptions { - props?: any; - limits?: workerdResourceLimits; + props?: any; + limits?: workerdResourceLimits; } interface WorkerLoader { - get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; - load(code: WorkerLoaderWorkerCode): WorkerStub; + 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; + 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[]; + 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; + cpuMs?: number; + subRequests?: number; } /** -* 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/) -*/ + * 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; + /* [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; } 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; + 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; } declare abstract class Span { - get isTraced(): boolean; - setAttribute(key: string, value?: (boolean | number | string)): void; - end(): void; + get isTraced(): boolean; + setAttribute(key: string, value?: boolean | number | string): void; + end(): void; } /** * Represents the identity of a user authenticated via Cloudflare Access. @@ -3546,41 +3934,41 @@ declare abstract class Span { * 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. */ + /** 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; - /** 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; + }>; + /** 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 @@ -3595,62 +3983,62 @@ type AgentMemoryThinkingLevel = "low" | "medium" | "high"; type AgentMemoryResponseLength = "short" | "medium" | "long"; /** A conversation message passed to ingest(). */ interface AgentMemoryMessage { - role: "system" | "user" | "assistant"; - content: string; - /** Optional message timestamp. */ - timestamp?: Date; + role: "system" | "user" | "assistant"; + content: string; + /** Optional message timestamp. */ + timestamp?: Date; } /** 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; + /** 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; - /** Memory text. */ - content: string; - /** Session that created this memory. */ - sessionId: string | null; - /** Memory creation time. */ - createdAt: Date; - /** Memory last-update time. */ - updatedAt: Date; + /** Memory ID. */ + id: string; + /** Memory type. */ + type: AgentMemoryMemoryType; + /** Text summary. */ + summary: string; + /** 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; + /** 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; } /** Options for the ingest() method. */ interface AgentMemoryIngestOptions { - /** Session identifier to associate with memories created during ingestion. */ - sessionId?: string | null | undefined; + /** Session identifier to associate with memories created during ingestion. */ + sessionId?: string | null | undefined; } /** Options for the getSummary() method. */ interface AgentMemoryGetSummaryOptions { - /** Session identifier to retrieve session summary for. */ - sessionId?: string | null | undefined; + /** Session identifier to retrieve session summary for. */ + sessionId?: string | null | undefined; } /** Response from the getSummary() method. */ interface AgentMemoryGetSummaryResponse { - /** Markdown summary. */ - summary: string; + /** Markdown summary. */ + summary: string; } /** * Options for the recall() method. @@ -3661,21 +4049,21 @@ interface AgentMemoryGetSummaryResponse { * ("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; + /** 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[]; + /** 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. @@ -3685,20 +4073,20 @@ interface AgentMemoryRecallResult { * 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; + /** 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; + memories: AgentMemoryMemoryListEntry[]; + /** Continuation cursor; absent when this page exhausted the result set. */ + cursor?: string; } /** * A single Agent Memory profile, scoped to a profile name. @@ -3706,70 +4094,70 @@ interface AgentMemoryListMemoriesResult { * 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; + /** + * 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. @@ -3789,500 +4177,505 @@ declare abstract class AgentMemoryProfile { * ``` */ 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; + /** + * 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 { -} +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; + role: "system" | "developer" | "user" | "assistant" | "tool"; + content: string | null; }; /** * 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'; - }; + 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; }; // ============ 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 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; + messages: AiSearchMessage[]; + model?: string; + stream?: boolean; + ai_search_options?: AiSearchOptions; + [key: string]: unknown; }; // ============ 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[]; + /** 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; -}; +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; +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; + 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[]; + 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 & { - ai_search_options: AiSearchMultiSearchOptions; +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[]; +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; - }; - 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; - }; - }>; + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + 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 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']; + 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; - }; + 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; + }; + }; }; // ============ 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'; + 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"; }>; - /** Sync interval in seconds. */ - sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; - metadata?: Record; - [key: string]: unknown; + } | 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; }; /** 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'; + 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 AiSearchListResponse = { - result: AiSearchInstanceInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; + result: AiSearchInstanceInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; }; // ============ 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'; + /** 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"; }>; - 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; + } | 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; }; // ============ 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; + 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 AiSearchItemContentResult = { - body: ReadableStream; - contentType: string; - filename: string; - size: number; + body: ReadableStream; + contentType: string; + filename: string; + size: number; }; type AiSearchUploadItemOptions = { - metadata?: Record; + metadata?: Record; }; 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; + 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; }; type AiSearchListItemsResponse = { - result: AiSearchItemInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; + 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; + /** 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; + 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; - }; + 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; + /** 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; - }; + 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; - }; + 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; + 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; + id: number; + message: string; + message_type: number; + created_at: number; }; type AiSearchCreateJobParams = { - description?: string; + description?: string; }; type AiSearchListJobsParams = { - page?: number; - per_page?: number; + page?: number; + per_page?: number; }; type AiSearchListJobsResponse = { - result: AiSearchJobInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; + result: AiSearchJobInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; }; type AiSearchJobLogsParams = { - page?: number; - per_page?: number; + page?: number; + per_page?: number; }; type AiSearchJobLogsResponse = { - result: AiSearchJobLog[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; + result: AiSearchJobLog[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; }; // ============ AI Search Sub-Service Classes ============ /** @@ -4290,109 +4683,117 @@ type AiSearchJobLogsResponse = { * Provides info, download, sync, logs, and chunks operations on a specific item. */ declare abstract class AiSearchItem { - /** Get metadata about this item. */ - info(): Promise; - /** - * Download the item's content. - * @returns Object with body stream, content type, filename, and size. - */ - 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; + /** Get metadata about this item. */ + info(): Promise; + /** + * Download the item's content. + * @returns Object with body stream, content type, filename, and size. + */ + 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; } /** * 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; + /** 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; } /** * 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; - /** - * Cancel a running job. - * @returns The updated job info. - * @throws AiSearchNotFoundError if the job does not exist. - */ - cancel(): Promise; + /** Get metadata about this job. */ + info(): Promise; + /** Get logs for this job. */ + logs(params?: AiSearchJobLogsParams): Promise; + /** + * Cancel a running job. + * @returns The updated job info. + * @throws AiSearchNotFoundError if the job does not exist. + */ + cancel(): Promise; } /** * 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; + /** 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; } // ============ AI Search Binding Classes ============ /** @@ -4419,43 +4820,45 @@ declare abstract class AiSearchJobs { * ``` */ 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; + /** + * 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; } /** * Namespace-level AI Search service. @@ -4490,449 +4893,476 @@ declare abstract class AiSearchInstance { * ``` */ 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; + /** + * 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 AiImageClassificationInput = { - image: number[]; + image: number[]; }; type AiImageClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; } 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[]; + 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; + description: string; }; declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; } 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[]; + 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; + description: string; }; declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiMultimodalEmbeddingsInput = { - image: string; - text: string[]; + image: string; + text: string[]; }; type AiIMultimodalEmbeddingsOutput = { - data: number[][]; - shape: number[]; + data: number[][]; + shape: number[]; }; declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiObjectDetectionInput = { - image: number[]; + image: number[]; }; type AiObjectDetectionOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; } type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; + source: string; + sentences: string[]; }; type AiSentenceSimilarityOutput = number[]; declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; } type AiAutomaticSpeechRecognitionInput = { - audio: number[]; + audio: number[]; }; type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; }; declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; } type AiSummarizationInput = { - input_text: string; - max_length?: number; + input_text: string; + max_length?: number; }; type AiSummarizationOutput = { - summary: string; + summary: string; }; declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; } type AiTextClassificationInput = { - text: string; + text: string; }; type AiTextClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; } type AiTextEmbeddingsInput = { - text: string | string[]; + text: string | string[]; }; type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; + shape: number[]; + data: number[][]; }; declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; } type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; + 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[]; + 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: "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; + name: string; + code: string; }; type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; + type: string; + json_schema?: any; }; 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[]; + 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 AiTextGenerationToolLegacyOutput = { - name: string; - arguments: unknown; + name: string; + arguments: unknown; }; type AiTextGenerationToolOutput = { - id: string; - type: "function"; - function: { - name: string; - arguments: string; - }; + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; }; type UsageTags = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; }; type AiTextGenerationOutput = { - response?: string; - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; - usage?: UsageTags; + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; }; declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; } type AiTextToSpeechInput = { - prompt: string; - lang?: string; -}; -type AiTextToSpeechOutput = Uint8Array | { - audio: string; + prompt: string; + lang?: string; }; +type AiTextToSpeechOutput = + | Uint8Array + | { + audio: string; + }; declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; + 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; + 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; + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; } type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; + text: string; + target_lang: string; + source_lang?: string; }; type AiTranslationOutput = { - translated_text?: string; + translated_text?: string; }; declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; } /** * Workers AI support for OpenAI's Chat Completions API */ type ChatCompletionContentPartText = { - type: "text"; - text: string; + type: "text"; + text: string; }; type ChatCompletionContentPartImage = { - type: "image_url"; - image_url: { - url: string; - detail?: "auto" | "low" | "high"; - }; + 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: "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: "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: "refusal"; + refusal: string; +}; +type ChatCompletionContentPart = + | ChatCompletionContentPartText + | ChatCompletionContentPartImage + | ChatCompletionContentPartInputAudio + | ChatCompletionContentPartFile; type FunctionDefinition = { - name: string; - description?: string; - parameters?: Record; - strict?: boolean | null; + name: string; + description?: string; + parameters?: Record; + strict?: boolean | null; }; type ChatCompletionFunctionTool = { - type: "function"; - function: FunctionDefinition; + type: "function"; + function: FunctionDefinition; }; type ChatCompletionCustomToolGrammarFormat = { - type: "grammar"; - grammar: { - definition: string; - syntax: "lark" | "regex"; - }; + type: "grammar"; + grammar: { + definition: string; + syntax: "lark" | "regex"; + }; }; type ChatCompletionCustomToolTextFormat = { - type: "text"; + type: "text"; }; -type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat; +type ChatCompletionCustomToolFormat = + | ChatCompletionCustomToolTextFormat + | ChatCompletionCustomToolGrammarFormat; type ChatCompletionCustomTool = { - type: "custom"; - custom: { - name: string; - description?: string; - format?: ChatCompletionCustomToolFormat; - }; + 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; - }; + id: string; + type: "function"; + function: { + name: string; + /** JSON-encoded arguments string. */ + arguments: string; + }; }; type ChatCompletionMessageCustomToolCall = { - id: string; - type: "custom"; - custom: { - name: string; - input: string; - }; + id: string; + type: "custom"; + custom: { + name: string; + input: string; + }; }; -type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall; +type ChatCompletionMessageToolCall = + | ChatCompletionMessageFunctionToolCall + | ChatCompletionMessageCustomToolCall; type ChatCompletionToolChoiceFunction = { - type: "function"; - function: { - name: string; - }; + type: "function"; + function: { + name: string; + }; }; type ChatCompletionToolChoiceCustom = { - type: "custom"; - custom: { - name: string; - }; + 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: "allowed_tools"; + allowed_tools: { + mode: "auto" | "required"; + tools: Array>; + }; +}; +type ChatCompletionToolChoiceOption = + | "none" + | "auto" + | "required" + | ChatCompletionToolChoiceFunction + | ChatCompletionToolChoiceCustom + | ChatCompletionToolChoiceAllowedTools; type DeveloperMessage = { - role: "developer"; - content: string | Array<{ + role: "developer"; + content: + | string + | Array<{ type: "text"; text: string; - }>; - name?: string; + }>; + name?: string; }; type SystemMessage = { - role: "system"; - content: string | Array<{ + role: "system"; + content: + | string + | Array<{ type: "text"; text: string; - }>; - name?: string; + }>; + name?: string; }; /** * Permissive merged content part used inside UserMessage arrays. @@ -4942,226 +5372,244 @@ type SystemMessage = { * 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: "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; + role: "user"; + content: string | Array; + name?: string; }; type AssistantMessageContentPart = { - type: "text" | "refusal"; - text?: string; - refusal?: string; + 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; - }; + 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<{ + role: "tool"; + content: + | string + | Array<{ type: "text"; text: string; - }>; - tool_call_id: string; + }>; + tool_call_id: string; }; type FunctionMessage = { - role: "function"; - content: string; - name: string; -}; -type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage; + role: "function"; + content: string; + name: string; +}; +type ChatCompletionMessageParam = + | DeveloperMessage + | SystemMessage + | UserMessage + | AssistantMessage + | ToolMessage + | FunctionMessage; type ChatCompletionsResponseFormatText = { - type: "text"; + type: "text"; }; type ChatCompletionsResponseFormatJSONObject = { - type: "json_object"; + type: "json_object"; }; type ResponseFormatJSONSchema = { - type: "json_schema"; - json_schema: { - name: string; - description?: string; - schema?: Record; - strict?: boolean | null; - }; + type: "json_schema"; + json_schema: { + name: string; + description?: string; + schema?: Record; + strict?: boolean | null; + }; }; -type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema; +type ResponseFormat = + | ChatCompletionsResponseFormatText + | ChatCompletionsResponseFormatJSONObject + | ResponseFormatJSONSchema; type ChatCompletionsStreamOptions = { - include_usage?: boolean; - include_obfuscation?: boolean; + include_usage?: boolean; + include_obfuscation?: boolean; }; type PredictionContent = { - type: "content"; - content: string | Array<{ + type: "content"; + content: + | string + | Array<{ type: "text"; text: string; - }>; + }>; }; type AudioParams = { - voice: string | { + voice: + | string + | { id: string; - }; - format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; + }; + format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; }; type WebSearchUserLocation = { - type: "approximate"; - approximate: { - city?: string; - country?: string; - region?: string; - timezone?: string; - }; + type: "approximate"; + approximate: { + city?: string; + country?: string; + region?: string; + timezone?: string; + }; }; type WebSearchOptions = { - search_context_size?: "low" | "medium" | "high"; - user_location?: WebSearchUserLocation; + 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; + /** 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" | { + 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; + }; + functions?: Array; }; type PromptTokensDetails = { - cached_tokens?: number; - audio_tokens?: number; + cached_tokens?: number; + audio_tokens?: number; }; type CompletionTokensDetails = { - reasoning_tokens?: number; - audio_tokens?: number; - accepted_prediction_tokens?: number; - rejected_prediction_tokens?: number; + 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; + 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; + token: string; + logprob: number; + bytes: Array | null; }; type ChatCompletionTokenLogprob = { - token: string; - logprob: number; - bytes: Array | null; - top_logprobs: Array; + 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; + 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: "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; + 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; + 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; + index: number; + message: ChatCompletionResponseMessage; + finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; + logprobs: ChatCompletionLogprobs | null; }; type ChatCompletionsMessagesInput = { - messages: Array; + 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; + 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 @@ -5174,444 +5622,509 @@ type ChatCompletionsOutput = { * 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; + 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; + 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"; + 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; + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; }; type ResponseIncompleteDetails = { - reason?: "max_output_tokens" | "content_filter"; + reason?: "max_output_tokens" | "content_filter"; }; type ResponsePrompt = { - id: string; - variables?: { - [key: string]: string | ResponseInputText | ResponseInputImage; - } | null; - version?: string | null; + 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; + 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"; + text: string; + type: "reasoning_text"; }; type ResponseConversationParam = { - id: string; + id: string; }; type ResponseCreatedEvent = { - response: Response; - sequence_number: number; - type: "response.created"; + response: Response; + sequence_number: number; + type: "response.created"; }; type ResponseCustomToolCallOutput = { - call_id: string; - output: string | Array; - type: "custom_tool_call_output"; - id?: string; + 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; + 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"; + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; }; type ResponseFailedEvent = { - response: Response; - sequence_number: number; - type: "response.failed"; + response: Response; + sequence_number: number; + type: "response.failed"; }; type ResponseFormatText = { - type: "text"; + type: "text"; }; type ResponseFormatJSONObject = { - type: "json_object"; + type: "json_object"; }; -type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextConfig = + | ResponseFormatText + | ResponseFormatTextJSONSchemaConfig + | ResponseFormatJSONObject; type ResponseFormatTextJSONSchemaConfig = { - name: string; - schema: { - [key: string]: unknown; - }; - type: "json_schema"; - description?: string; - strict?: boolean | null; + 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"; + 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"; + 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"; + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; }; interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { - id: string; + id: string; } type ResponseFunctionToolCallOutputItem = { - id: string; - call_id: string; - output: string | Array; - type: "function_call_output"; - status?: "in_progress" | "completed" | "incomplete"; + 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"; + response: Response; + sequence_number: number; + type: "response.incomplete"; }; type ResponseInput = Array; type ResponseInputContent = ResponseInputText | ResponseInputImage; type ResponseInputImage = { - detail: "low" | "high" | "auto"; - type: "input_image"; - /** - * Base64 encoded image - */ - image_url?: string | null; + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; }; type ResponseInputImageContent = { - type: "input_image"; - detail?: "low" | "high" | "auto" | null; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + 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; + 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"; + 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"; + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; }; type ResponseInputText = { - text: string; - type: "input_text"; + text: string; + type: "input_text"; }; type ResponseInputTextContent = { - text: string; - type: "input_text"; -}; -type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; + 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"; + 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"; + 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"; + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; }; type ResponseOutputRefusal = { - refusal: string; - type: "refusal"; + refusal: string; + type: "refusal"; }; type ResponseOutputText = { - text: string; - type: "output_text"; - logprobs?: Array; + 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"; + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; }; type ResponseReasoningSummaryItem = { - text: string; - type: "summary_text"; + text: string; + type: "summary_text"; }; type ResponseReasoningContentItem = { - text: string; - type: "reasoning_text"; + 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"; + 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"; + 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"; + 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; + 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"; + response: Response; + sequence_number: number; + type: "response.completed"; }; type ResponseTextConfig = { - format?: ResponseFormatTextConfig; - verbosity?: "low" | "medium" | "high" | null; + 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"; + 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"; + 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; + token: string; + logprob: number; + top_logprobs?: Array; }; type TopLogprob = { - token?: string; - logprob?: number; + token?: string; + logprob?: number; }; type ResponseUsage = { - input_tokens: number; - output_tokens: number; - total_tokens: number; + input_tokens: number; + output_tokens: number; + total_tokens: number; }; type Tool = ResponsesFunctionTool; type ToolChoiceFunction = { - name: string; - type: "function"; + name: string; + type: "function"; }; type ToolChoiceOptions = "none"; type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; type StreamOptions = { - include_obfuscation?: boolean; + include_obfuscation?: boolean; }; /** Marks keys from T that aren't in U as optional never */ type Without = { - [P in Exclude]?: never; + [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: { +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"; -} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; + }[]; + }; +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 { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; + /** + * The async request id that can be used to obtain the results. + */ + 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 | { + 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 { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + * The second this word begins in the recording */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Output { + start?: number; /** - * The transcription + * The ending second when the word completes */ - 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; + end?: number; + }[]; + vtt?: string; } 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 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: { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +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 */ @@ -5624,527 +6137,559 @@ type Ai_Cf_Meta_M2M100_1_2B_Input = { * 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; -} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; + }[]; + }; +type Ai_Cf_Meta_M2M100_1_2B_Output = + | { + /** + * The translated text in the target language + */ + 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; + /** + * 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: { + 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. */ 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; + }[]; + }; +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; + /** + * 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: { + 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 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"; -} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; + }[]; + }; +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"; + } + | 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; + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; } 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; -}; + 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; + 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 | { + 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 { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + * The second this word begins in the recording */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + start?: number; /** - * The transcription + * The ending second when the word completes */ - 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; + 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; + 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 | { + audio: + | string + | { body?: object; contentType?: string; - }; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: 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 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?: { /** * 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. + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. */ - initial_prompt?: string; + language_probability?: number; /** - * The prefix appended to the beginning of the output of the transcription and can guide the transcription result. + * The total duration of the original audio file, in seconds. */ - prefix?: string; + duration?: number; /** - * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed. + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. */ - beam_size?: number; + duration_after_vad?: number; + }; + /** + * The complete transcription of the audio. + */ + text: string; + /** + * The total number of words in the transcription. + */ + word_count?: number; + segments?: { /** - * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops. + * The starting time of the segment within the audio, in seconds. */ - condition_on_previous_text?: boolean; + start?: number; /** - * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped. + * The ending time of the segment within the audio, in seconds. */ - no_speech_threshold?: number; + end?: number; /** - * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text. + * The transcription of the segment. */ - compression_ratio_threshold?: number; + text?: string; /** - * Threshold for filtering out segments with low average log probability, indicating low confidence. + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. */ - log_prob_threshold?: number; + temperature?: number; /** - * Optional threshold (in seconds) to skip silent periods that may cause hallucinations. + * The average log probability of the predictions for the words in this segment, indicating overall confidence. */ - hallucination_silence_threshold?: number; -} -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; - }; + avg_logprob?: number; /** - * The complete transcription of the audio. + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. */ - text: string; + compression_ratio?: number; /** - * The total number of words in the transcription. + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. */ - 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; - }[]; + 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; + }[]; + /** + * 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)[]; -}; + 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. + */ + 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. - */ - 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? + * One of the provided context content */ - truncate_inputs?: boolean; + 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 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; + 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: { /** - * 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? + * One of the provided context content */ - truncate_inputs?: boolean; + 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[]; + 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?: { /** - * When provided with too long context should the model error out or truncate the context to fit? + * Index of the context in the request */ - 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 - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { - response?: number[][]; - shape?: number[]; + id?: number; /** - * The pooling method used in the embedding process. + * Score of the context under the index. */ - pooling?: "mean" | "cls"; + score?: number; + }[]; +} +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; } interface Ai_Cf_Baai_Bge_M3_Output_Embedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; + shape?: number[]; + /** + * 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; + /** + * 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; + 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; + /** + * 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; + /** + * 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; + 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; +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. - */ - 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; + /** + * 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. + */ + 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 Ai_Cf_Meta_Llama_3_2_11B_Vision_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 | { + /** + * 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?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - 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; - }; - }[] | { + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - 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; - }; + url?: string; + }; }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ + }[]; + image?: number[] | (string & NonNullable); + 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. */ @@ -6157,31 +6702,32 @@ interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { * 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; - }; + /** + * 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'). */ @@ -6190,188 +6736,195 @@ interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. + * A description of the expected parameter. */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; + 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; + } + )[]; + /** + * 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 + */ + response?: string; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * 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. + * The arguments passed to be passed to the tool call request */ - top_k?: number; + arguments?: object; /** - * Random seed for reproducibility of the generation. + * The name of the tool to be called */ - 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 - */ - 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; - }[]; + name?: string; + }[]; }; 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; + 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_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; +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; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - 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. - */ - 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; + /** + * 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_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. + */ + 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_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; + 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. - */ - 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; + /** + * 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?: ({ + }[]; + 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. */ @@ -6384,31 +6937,32 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * 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; - }; + /** + * 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'). */ @@ -6417,49 +6971,101 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. + * A description of the expected parameter. */ - 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; - }; - }; + description: string; + }; }; + }; }; - })[]; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + } + )[]; + 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. + */ + 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_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; /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * Prompt for the text generation model */ - raw?: boolean; + prompt?: string; /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ @@ -6476,10 +7082,6 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * 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. */ @@ -6496,69 +7098,23 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; -} -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; - }[]; + 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?: { + 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 */ @@ -6571,11 +7127,11 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { * Total number of input and output tokens */ total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** * The arguments passed to be passed to the tool call request */ @@ -6584,52 +7140,56 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { * The name of the tool to be called */ name?: string; - }[]; -} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; + }[]; + } + | 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 async request id that can be used to obtain the results. - */ - request_id?: string; + /** + * The async request id that can be used to obtain the results. + */ + 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; + 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: { /** - * 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. + * The role of the message sender must alternate between 'user' and 'assistant'. */ - max_tokens?: number; + role: "user" | "assistant"; /** - * Controls the randomness of the output; higher values produce more random results. + * The content of the message as a string. */ - temperature?: number; - /** - * Dictate the output format of the generated response. + 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. */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; + type?: string; + }; } interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: string | { + response?: + | string + | { /** * Whether the conversation is safe or not. */ @@ -6638,141 +7198,144 @@ interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. */ categories?: string[]; - }; + }; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * Usage statistics for the inference request + * Total number of tokens in input */ - 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; - }; + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + 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; + 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. + /** + * A query you wish to perform against the provided contexts. + */ + /** + * 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: { + /** + * One of the provided context content */ + text?: string; + }[]; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Output { + response?: { /** - * Number of returned results starting with the best score. + * Index of the context in the request */ - top_k?: number; + id?: number; /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + * Score of the context under the index. */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; + 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; + 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; +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; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - 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. - */ - 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; + /** + * 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_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. + */ + 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_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; + 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. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - 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; - }[]; + role: string; /** - * A list of tools available for the assistant to use. + * The content of the message as a string. */ - tools?: ({ + content: 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. */ @@ -6785,31 +7348,32 @@ interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { * 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; - }; + /** + * 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'). */ @@ -6818,228 +7382,507 @@ interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. + * A description of the expected parameter. */ - 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; - }; - }; + description: string; + }; }; + }; }; - })[]; - 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. - */ - 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; + } + )[]; + 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. + */ + 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_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 + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * 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. + * Total number of tokens in input */ - top_k?: number; + prompt_tokens?: number; /** - * Random seed for reproducibility of the generation. + * Total number of tokens in output */ - seed?: number; + completion_tokens?: number; /** - * Penalty for repeated tokens; higher values discourage repetition. + * Total number of input and output tokens */ - repetition_penalty?: number; + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * The arguments passed to be passed to the tool call request */ - frequency_penalty?: number; + arguments?: object; /** - * Increases the likelihood of the model introducing new topics. + * The name of the tool to be called */ - presence_penalty?: number; + 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; } -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; +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 fulfilled 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 Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +interface Ai_Cf_Qwen_Qwq_32B_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?: ( + | { /** - * Total number of tokens in input + * The name of the tool. More descriptive the better. */ - prompt_tokens?: number; + name: string; /** - * Total number of tokens in output + * A brief description of what the tool does. */ - completion_tokens?: number; + description: string; /** - * Total number of input and output tokens + * Schema defining the parameters accepted by the tool. */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + 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; + }; + }; + }; + } + | { /** - * The arguments passed to be passed to the tool call request + * Specifies the type of tool (e.g., 'function'). */ - arguments?: object; + type: string; /** - * The name of the tool to be called + * Details of the function tool. */ - 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; + 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; + }; + }; + }; + }; + } + )[]; + /** + * 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 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 fulfilled 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; +type Ai_Cf_Qwen_Qwq_32B_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * 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. + * Total number of tokens in input */ - top_k?: number; + prompt_tokens?: number; /** - * Random seed for reproducibility of the generation. + * Total number of tokens in output */ - seed?: number; + completion_tokens?: number; /** - * Penalty for repeated tokens; higher values discourage repetition. + * Total number of input and output tokens */ - repetition_penalty?: number; + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * The arguments passed to be passed to the tool call request */ - frequency_penalty?: number; + arguments?: object; /** - * Increases the likelihood of the model introducing new topics. + * The name of the tool to be called */ - presence_penalty?: number; + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -interface Ai_Cf_Qwen_Qwq_32B_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 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. + */ + prompt: string; + /** + * JSON schema that should be fulfilled 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; +} +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_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. 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?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - 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; - }; - }[] | { + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - 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; - }; + url?: string; + }; }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ + }[]; + 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. */ @@ -7052,6 +7895,52 @@ interface Ai_Cf_Qwen_Qwq_32B_Messages { * 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'). */ @@ -7064,19 +7953,231 @@ interface Ai_Cf_Qwen_Qwq_32B_Messages { * Definitions of each parameter. */ properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: 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 Ai_Cf_Mistralai_Mistral_Small_3_1_24B_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; + }; + /** + * 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; + }[]; +}; +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; +} +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; +} +interface Ai_Cf_Google_Gemma_3_12B_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 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?: ( + | { + /** + * 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'). */ @@ -7085,227 +8186,753 @@ interface Ai_Cf_Qwen_Qwq_32B_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. + * A description of the expected parameter. */ - 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; - }; - }; + description: 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; + } + )[]; + /** + * 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 Ai_Cf_Google_Gemma_3_12B_It_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * 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. + * Total number of tokens in input */ - top_p?: number; + prompt_tokens?: 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. + * Total number of tokens in output */ - top_k?: number; + completion_tokens?: number; /** - * Random seed for reproducibility of the generation. + * Total number of input and output tokens */ - seed?: number; + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * Penalty for repeated tokens; higher values discourage repetition. + * The arguments passed to be passed to the tool call request */ - repetition_penalty?: number; + arguments?: object; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * The name of the tool to be called */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + 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_Qwen_Qwq_32B_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +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 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_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_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?: ( + | { /** - * Total number of tokens in input + * The name of the tool. More descriptive the better. */ - prompt_tokens?: number; + name: string; /** - * Total number of tokens in output + * A brief description of what the tool does. */ - completion_tokens?: number; + description: string; /** - * Total number of input and output tokens + * Schema defining the parameters accepted by the tool. */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + 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; + }; + }; + }; + } + | { /** - * The arguments passed to be passed to the tool call request + * Specifies the type of tool (e.g., 'function'). */ - arguments?: object; + type: string; /** - * The name of the tool to be called + * Details of the function tool. */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; + 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; + /** + * 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 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. - */ - prompt: string; - /** - * JSON schema that should be fulfilled 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; +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_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_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_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { + /** + * 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?: ( + | { + /** + * 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; + }; + }; + }; + } + | { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * Specifies the type of tool (e.g., 'function'). */ - role?: string; + type: 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 + * Details of the function tool. */ - tool_call_id?: string; - content?: string | { + 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: { /** - * Type of the content provided + * The type of the parameters object (usually 'object'). */ - 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: string; + /** + * List of required parameter names. + */ + required?: string[]; /** - * Type of the content provided + * Definitions of each parameter. */ - type?: string; - text?: string; - image_url?: { + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + * A description of the expected parameter. */ - url?: string; + description: string; + }; }; + }; }; - }[]; - functions?: { - name: string; - code: string; - }[]; + } + )[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * 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 Ai_Cf_Meta_Llama_4_Scout_17B_16E_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; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The tool call id. + */ + id?: string; /** - * A list of tools available for the assistant to use. + * Specifies the type of tool (e.g., 'function'). */ - tools?: ({ + 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 { + /** + * 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_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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?: ( + | { /** * The name of the tool. More descriptive the better. */ @@ -7318,6 +8945,52 @@ interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { * 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'). */ @@ -7330,19 +9003,194 @@ interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { * Definitions of each parameter. */ properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; + [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; + /** + * 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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +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 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_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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'). */ @@ -7351,211 +9199,784 @@ interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. + * A description of the expected parameter. */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; + description: string; + }; }; + }; }; - })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; + } + )[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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_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; + }; + }[]; + }; /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * Reason why the model stopped generating */ - raw?: boolean; + finish_reason?: string; /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * Stop reason (may be null) */ - stream?: boolean; + stop_reason?: string | null; /** - * The maximum number of tokens to generate in the response. + * Log probabilities (if requested) */ - max_tokens?: number; + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * Controls the randomness of the output; higher values produce more random results. + * Total number of tokens in input */ - temperature?: number; + prompt_tokens?: 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. + * Total number of tokens in output */ - top_p?: number; + completion_tokens?: 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. + * Total number of input and output tokens */ - 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_Mistralai_Mistral_Small_3_1_24B_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; - }; - /** - * 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; - }[]; -}; -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; + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; } -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. +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 */ - stream?: boolean; + index: number; /** - * The maximum number of tokens to generate in the response. + * The generated text completion */ - max_tokens?: number; + text: string; /** - * Controls the randomness of the output; higher values produce more random results. + * Reason why the model stopped generating */ - temperature?: number; + finish_reason: string; /** - * 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. + * Stop reason (may be null) */ - top_p?: number; + stop_reason?: string | null; /** - * 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. + * Log probabilities (if requested) */ - top_k?: number; + logprobs?: {} | null; /** - * Random seed for reproducibility of the generation. + * Log probabilities for the prompt (if requested) */ - seed?: number; + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * Penalty for repeated tokens; higher values discourage repetition. + * Total number of tokens in input */ - repetition_penalty?: number; + prompt_tokens?: number; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * Total number of tokens in output */ - frequency_penalty?: number; + completion_tokens?: number; /** - * Increases the likelihood of the model introducing new topics. + * Total number of input and output tokens */ - presence_penalty?: number; + total_tokens?: number; + }; } -interface Ai_Cf_Google_Gemma_3_12B_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 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; - }; +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; }[]; + }[]; }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ + 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 = + | { + /** + * 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"; + } + | { + /** + * 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"; + }; +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?: ( + | { /** * The name of the tool. More descriptive the better. */ @@ -7568,6 +9989,52 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Messages { * 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'). */ @@ -7580,19 +10047,197 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Messages { * Definitions of each parameter. */ properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; + [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'). */ @@ -7601,2775 +10246,918 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Messages { * 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 name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string; /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[]; /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ type: string; /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. + * A description of the expected parameter. */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; + 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; }; - })[]; + }[]; + }; /** - * JSON schema that should be fufilled for the response. + * Reason why the model stopped generating */ - guided_json?: object; + finish_reason?: string; /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * Stop reason (may be null) */ - raw?: boolean; + stop_reason?: string | null; /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * Log probabilities (if requested) */ - stream?: boolean; + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The maximum number of tokens to generate in the response. + * Total number of tokens in input */ - max_tokens?: number; + prompt_tokens?: number; /** - * Controls the randomness of the output; higher values produce more random results. + * Total number of tokens in output */ - temperature?: number; + completion_tokens?: 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. + * Total number of input and output tokens */ - top_p?: number; + 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; /** - * 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. + * The generated text completion */ - top_k?: number; + text: string; /** - * Random seed for reproducibility of the generation. + * Reason why the model stopped generating */ - seed?: number; + finish_reason: string; /** - * Penalty for repeated tokens; higher values discourage repetition. + * Stop reason (may be null) */ - repetition_penalty?: number; + stop_reason?: string | null; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * Log probabilities (if requested) */ - frequency_penalty?: number; + logprobs?: {} | null; /** - * Increases the likelihood of the model introducing new topics. + * Log probabilities for the prompt (if requested) */ - presence_penalty?: number; -} -type Ai_Cf_Google_Gemma_3_12B_It_Output = { + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The generated text response from the model + * Total number of tokens in input */ - response: string; + prompt_tokens?: number; /** - * Usage statistics for the inference request + * Total number of tokens in output */ - 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; - }[]; -}; -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 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_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_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?: ({ - /** - * 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; - /** - * 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; -} -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 input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_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_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { - /** - * 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?: ({ - /** - * 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; - /** - * 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 Ai_Cf_Meta_Llama_4_Scout_17B_16E_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; - }; - /** - * An array of tool calls requests made during the response generation - */ - 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 { - /** - * 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_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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?: ({ - /** - * 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; - /** - * 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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -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 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_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_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_Qwen_Qwen3_30B_A3B_Fp8_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_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 = { - /** - * 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"; -} | { - /** - * 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"; -}; -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?: ({ - /** - * 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_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; - }[]; + completion_tokens?: number; /** - * Usage statistics for the inference request + * Total number of input and output tokens */ - 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; - }; + 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; + /** + * 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; + 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[]; + /** + * 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 - ]; + /** + * 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; + 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; + /** + * 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; + /** + * 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; + 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; + /** + * 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; +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; + 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; - }; + multipart: { + body?: object; + contentType?: string; + }; } interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output { - /** - * Generated image as Base64 string. - */ - image?: string; + /** + * 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; + 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; - }; + multipart: { + body?: object; + contentType?: string; + }; } interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output { - /** - * Generated image as Base64 string. - */ - image?: string; + /** + * 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; + 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; - }; + multipart: { + body?: object; + contentType?: string; + }; } interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output { - /** - * Generated image as Base64 string. - */ - image?: string; + /** + * 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; + 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; + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; } declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; } declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; } declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; } declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; + 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; + "@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; + /** + * 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; + 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; - source: number; name: string; description: string; - task: { - id: string; - name: string; - description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; }; type ChatCompletionsBase = ChatCompletionsMessagesInput; type ChatCompletionsInput = ChatCompletionsMessagesInput; -interface InferenceUpstreamError extends Error { -} -interface AiInternalError extends Error { -} +interface InferenceUpstreamError extends Error {} +interface AiInternalError extends Error {} type AiModelListType = Record; type AiAsyncBatchResponse = { - request_id: string; + 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; + 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'; + 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; + 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; + 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'; + 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': { + "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; + } + | 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; + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; }; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} +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 + 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: @@ -10382,83 +11170,83 @@ declare abstract class AiGateway { */ /** 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; + /** 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; + /** 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; + /** 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; + /** 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; + /** 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; + /** Tokens in this page. */ + tokens: ArtifactsTokenInfo[]; + /** Total number of tokens for the repository. */ + total: number; } /** * Handle for a single repository. Returned by Artifacts.get(). @@ -10466,36 +11254,39 @@ interface ArtifactsTokenListResult { * 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; + /** + * 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 ────────────────────────────────────────────────────────────── /** @@ -10503,7 +11294,19 @@ interface ArtifactsRepo extends ArtifactsRepoInfo { * * 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'; +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. * @@ -10512,11 +11315,11 @@ type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' * 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; + readonly name: "ArtifactsError"; + /** String error code for programmatic matching. */ + readonly code: ArtifactsErrorCode; + /** Numeric error code matching the REST API. */ + readonly numericCode: number; } // ── Binding ────────────────────────────────────────────────────────────────── /** @@ -10525,761 +11328,793 @@ interface ArtifactsError extends Error { * 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; + /** + * 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; - 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; + 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 { -} +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 { -} +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 { -} +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 { -} +interface AutoRAGNameNotSetError extends Error {} type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; + key: string; + type: "eq" | "ne" | "gt" | "gte" | "lt" | "lte"; + value: string | number | boolean; }; type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; + 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; + 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; + 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; +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; - }[]; + 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; + }[]; + 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; + 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; + 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'; + /** + * @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 ` - -
- - {@html renderedHtml} -
- - diff --git a/codeview-ui/src/lib/components/CrateGrid.svelte b/codeview-ui/src/lib/components/CrateGrid.svelte index a2312a7..c75f418 100644 --- a/codeview-ui/src/lib/components/CrateGrid.svelte +++ b/codeview-ui/src/lib/components/CrateGrid.svelte @@ -3,10 +3,14 @@ CrateMapData, CrateMapModuleNode, CrateMapSemanticKind, - } from '#lib/graph/crate-map'; - import { resolveAppPath } from '#lib/app-paths'; - import { findContainingModule, moduleDepthColor } from '#lib/graph/crate-map'; - import { edgeLabels } from '#lib/display-names'; + } from '#lib/graph/crate-map.js'; + import { resolveAppPath } from '#lib/app-paths.js'; + import { + CRATE_MAP_SEMANTIC_KINDS, + findContainingModule, + moduleDepthColor, + } from '#lib/graph/crate-map.js'; + import { edgeLabels } from '#lib/display-names.js'; let { data, @@ -36,12 +40,10 @@ byKind = new Map(); outgoing.set(edge.from, byKind); } - for (const [kind, count] of Object.entries(edge.kindCounts) as [string, number][]) { - if (count > 0) { - byKind.set( - kind as CrateMapSemanticKind, - (byKind.get(kind as CrateMapSemanticKind) ?? 0) + count, - ); + for (const kind of CRATE_MAP_SEMANTIC_KINDS) { + const count = edge.kindCounts[kind]; + if (count !== undefined && count > 0) { + byKind.set(kind, (byKind.get(kind) ?? 0) + count); } } } diff --git a/codeview-ui/src/lib/components/CrateParseState.svelte b/codeview-ui/src/lib/components/CrateParseState.svelte index 2a32e1d..012bc8c 100644 --- a/codeview-ui/src/lib/components/CrateParseState.svelte +++ b/codeview-ui/src/lib/components/CrateParseState.svelte @@ -1,5 +1,5 @@ - -
- - - - -
- - diff --git a/codeview-ui/src/lib/components/Skeleton.svelte b/codeview-ui/src/lib/components/Skeleton.svelte index 9376bc9..ff6b0c3 100644 --- a/codeview-ui/src/lib/components/Skeleton.svelte +++ b/codeview-ui/src/lib/components/Skeleton.svelte @@ -3,17 +3,19 @@ * Skeleton loading component with shimmer animation. * Uses CSS custom properties for theming consistency. */ + type SkeletonProps = { + class?: string; + width?: string; + height?: string; + rounded?: 'sm' | 'md' | 'lg' | 'full'; + }; + let { class: className = '', width = '100%', height = '1rem', rounded = 'md', - } = $props<{ - class?: string; - width?: string; - height?: string; - rounded?: 'sm' | 'md' | 'lg' | 'full'; - }>(); + }: SkeletonProps = $props(); const radiusMap = { sm: 'var(--radius-chip)', @@ -27,7 +29,7 @@ class="skeleton {className}" style:width style:height - style:border-radius={radiusMap[rounded as keyof typeof radiusMap]} + style:border-radius={radiusMap[rounded]} >
diff --git a/codeview-ui/src/lib/components/design/docs/DocArticle.svelte b/codeview-ui/src/lib/components/design/docs/DocArticle.svelte index 55bc4e6..577634e 100644 --- a/codeview-ui/src/lib/components/design/docs/DocArticle.svelte +++ b/codeview-ui/src/lib/components/design/docs/DocArticle.svelte @@ -1,7 +1,7 @@ diff --git a/codeview-ui/src/lib/components/design/docs/DocReading.svelte b/codeview-ui/src/lib/components/design/docs/DocReading.svelte index efe47ee..7f643cb 100644 --- a/codeview-ui/src/lib/components/design/docs/DocReading.svelte +++ b/codeview-ui/src/lib/components/design/docs/DocReading.svelte @@ -1,6 +1,6 @@