diff --git a/benchmarks/backend-behavior.ts b/benchmarks/backend-behavior.ts new file mode 100644 index 0000000..f9bd3c5 --- /dev/null +++ b/benchmarks/backend-behavior.ts @@ -0,0 +1,284 @@ +import assert from 'node:assert/strict'; +import { mock } from 'bun:test'; +import { AuthService } from '../src/services/auth'; +import { CacheService, withCache } from '../src/services/cache'; +import { ContactService } from '../src/services/contact'; +import { ContributionService, type Contribution } from '../src/services/contributions'; +import { StorageService } from '../src/services/storage'; +import { VatsimService } from '../src/services/vatsim'; + +mock.module('cloudflare:workers', () => ({ + DurableObject: class {}, + waitUntil: () => undefined, +})); + +class FakeCache { + readonly entries = new Map(); + matchCalls: string[] = []; + putCalls: string[] = []; + + async match(request: Request): Promise { + this.matchCalls.push(request.url); + return this.entries.get(request.url)?.clone(); + } + + async put(request: Request, response: Response): Promise { + this.putCalls.push(request.url); + this.entries.set(request.url, response.clone()); + } + + async delete(request: Request): Promise { + return this.entries.delete(request.url); + } +} + +const fakeCache = new FakeCache(); +Object.defineProperty(globalThis, 'caches', { + configurable: true, + value: { default: fakeCache }, +}); + +const originalDateNow = Date.now; +let currentTime = 1_000_000; +Date.now = () => currentTime; +try { + const namespace = `backend-behavior-${crypto.randomUUID()}`; + const cache = new CacheService({} as Env); + const misses = await Promise.all(Array.from({ length: 100 }, (_, index) => cache.getResponse(`missing-${index}`, namespace))); + assert(misses.every((value) => value === null)); + assert.equal(fakeCache.matchCalls.filter((url) => url.includes('/__version/')).length, 1); + assert.equal(fakeCache.matchCalls.filter((url) => url.includes(`/${namespace}/v1/`)).length, 100); + + await cache.getResponse('another-miss', namespace); + assert.equal(fakeCache.matchCalls.filter((url) => url.includes('/__version/')).length, 1, 'fresh hints avoid marker reads'); + + currentTime += 5_001; + await cache.getResponse('after-revalidation-window', namespace); + assert.equal(fakeCache.matchCalls.filter((url) => url.includes('/__version/')).length, 2, 'stale hints revalidate'); + + const nextVersion = await cache.bumpNamespaceVersion(namespace); + assert.equal(nextVersion, 2); + await cache.set('versioned-hit', { ok: true }, { namespace }); + assert.deepEqual(await cache.get<{ ok: boolean }>('versioned-hit', namespace), { ok: true }); + assert(fakeCache.putCalls.some((url) => url.includes(`/${namespace}/v2/versioned-hit`))); + + const xmlNamespace = `xml-behavior-${crypto.randomUUID()}`; + const middleware = withCache(() => 'latest-map', 60, xmlNamespace); + const background: Promise[] = []; + let handlerCalls = 0; + const makeContext = () => ({ + req: { method: 'GET', raw: new Request('https://api.stopbars.test/maps/YSSY/latest') }, + env: {} as Env, + res: new Response(null), + header: () => undefined, + executionCtx: { waitUntil: (promise: Promise) => void background.push(promise) }, + }); + const firstContext = makeContext(); + await middleware(firstContext as never, async () => { + handlerCalls += 1; + firstContext.res = new Response('', { headers: { 'Content-Type': 'application/xml' } }); + }); + await Promise.all(background.splice(0)); + const secondContext = makeContext(); + const cachedXml = await middleware(secondContext as never, async () => { + handlerCalls += 1; + }); + assert(cachedXml instanceof Response); + assert.equal(await cachedXml.text(), ''); + assert.equal(cachedXml.headers.get('X-Cache'), 'HIT'); + assert.equal(handlerCalls, 1, 'XML responses must be served from Cache API after the first request'); +} finally { + Date.now = originalDateNow; +} + +const originalFetch = globalThis.fetch; +let connectionFetches = 0; +globalThis.fetch = (async () => { + connectionFetches += 1; + await Promise.resolve(); + return new Response('1234567,YSSY_TWR,atc'); +}) as typeof fetch; +try { + const vatsim = new VatsimService('client', 'secret'); + const [status, csv] = await Promise.all([vatsim.getUserStatus('1234567'), vatsim.getUserConnectionsCsv('1234567')]); + assert.deepEqual(status, { cid: '1234567', callsign: 'YSSY_TWR', type: 'atc' }); + assert.equal(csv, '1234567,YSSY_TWR,atc'); + assert.equal(vatsim.isController(status), true); + assert.equal(vatsim.isController({ callsign: 'YSSY_APP_TWR', type: 'atc' }), true); + assert.equal(vatsim.isController({ callsign: 'YSSY_', type: 'atc' }), false); + assert.equal(vatsim.isObserver({ callsign: 'YSSY_OBS', type: 'atc' }), true); + assert.equal(connectionFetches, 1, 'concurrent status consumers must share one upstream request'); + await vatsim.getUserStatus('1234567'); + assert.equal(connectionFetches, 2, 'completed requests are not cached or made stale'); + assert.equal(await vatsim.getUserStatus('invalid'), null); + assert.equal(connectionFetches, 2); +} finally { + globalThis.fetch = originalFetch; +} + +const rangeRequests: Array<{ key: string; options?: R2GetOptions }> = []; +const fakeBucket = { + get: async (key: string, options?: R2GetOptions) => { + rangeRequests.push({ key, options }); + const ranged = Boolean(options?.range); + return { + body: new Response(ranged ? '2345' : '0123456789').body, + size: 10, + etag: 'etag-value', + httpEtag: '"etag-value"', + range: ranged ? { offset: 2, length: 4, suffix: undefined } : undefined, + writeHttpMetadata: (headers: Headers) => { + headers.set('Content-Type', 'application/octet-stream'); + headers.set('Cache-Control', 'public, max-age=60'); + }, + }; + }, +} as unknown as R2Bucket; +const storage = new StorageService(fakeBucket); +const ranged = await storage.getFile('/large.bin', new Headers({ Range: 'bytes=2-5' })); +assert(ranged); +assert.equal(rangeRequests[0].key, 'large.bin'); +assert(rangeRequests[0].options?.range instanceof Headers); +assert.equal(ranged.status, 206); +assert.equal(ranged.headers.get('Content-Range'), 'bytes 2-5/10'); +assert.equal(ranged.headers.get('Content-Length'), '4'); +assert.equal(ranged.headers.get('ETag'), '"etag-value"'); +assert.equal(await ranged.text(), '2345'); +const full = await storage.getFile('large.bin'); +assert(full); +assert.equal(rangeRequests[1].options, undefined); +assert.equal(full.status, 200); +assert.equal(await full.text(), '0123456789'); + +const worker = (await import('../src/index')).default; +const routeResponse = await worker.fetch( + new Request('https://api.stopbars.test/cdn/files/maps/YSSY.xml', { headers: { Range: 'bytes=2-5' } }), + { BARS_STORAGE: fakeBucket } as Env, + { waitUntil: () => undefined } as unknown as ExecutionContext, +); +assert.equal(routeResponse.status, 206); +assert.equal(rangeRequests.at(-1)?.key, 'maps/YSSY.xml', 'named Hono route must preserve nested R2 keys'); +assert.equal(routeResponse.headers.get('Content-Range'), 'bytes 2-5/10'); +assert.equal(await routeResponse.text(), '2345'); + +const queries: Array<{ query: string; params: unknown[] }> = []; +const queuedResults: unknown[][] = []; +const fakeDb = { + withSession: () => ({ + prepare: (query: string) => { + let params: unknown[] = []; + const statement = { + bind: (...values: unknown[]) => { + params = values; + return statement; + }, + all: async () => { + queries.push({ query, params }); + return { results: queuedResults.shift() ?? [], success: true, meta: {} }; + }, + run: async () => { + queries.push({ query, params }); + return { results: queuedResults.shift() ?? [], success: true, meta: {} }; + }, + }; + return statement; + }, + getBookmark: () => null, + }), +} as unknown as D1Database; +const contributions = new ContributionService(fakeDb, {} as never, '', {} as R2Bucket); +queuedResults.push([{ packageName: 'Sydney Ground', simulator: 'msfs2024' }]); +assert.deepEqual(await contributions.getLatestApprovedMapDescriptor('YSSY', 'Sydney Ground', 'msfs2024'), { + packageName: 'Sydney Ground', + simulator: 'msfs2024', +}); +assert(!queries[0].query.includes('submitted_xml')); +assert(!queries[0].query.includes('datetime(c.decision_date)')); +assert(queries[0].query.includes('ORDER BY c.decision_date DESC')); + +const contribution: Contribution = { + id: 'contribution-id', + userId: '7654321', + userDisplayName: 'Submitter', + airportIcao: 'YSSY', + packageName: 'Sydney Ground', + submittedXml: '', + notes: null, + simulator: 'msfs2024', + submissionDate: '2026-07-19T00:00:00.000Z', + status: 'pending', + rejectionReason: null, + decisionDate: null, +}; +queuedResults.push([{ ...contribution, actorIsProductManager: 1 }]); +type ContributionInternals = { + getContributionActionContext( + vatsimId: string, + contributionId: string, + ): Promise<{ isProductManager: boolean; contribution: Contribution | null } | null>; +}; +const actionContext = await (contributions as unknown as ContributionInternals).getContributionActionContext( + '1234567', + 'contribution-id', +); +assert.deepEqual(actionContext, { isProductManager: true, contribution }); +assert.equal(queries.length, 2, 'actor and contribution context must use one D1 query'); +assert(queries[1].query.includes('LEFT JOIN contributions c ON c.id = ?')); + +queuedResults.push([{ id: null, actorIsProductManager: 0 }]); +assert.deepEqual( + await (contributions as unknown as ContributionInternals).getContributionActionContext('1234567', 'missing'), + { isProductManager: false, contribution: null }, +); +queuedResults.push([]); +assert.equal( + await (contributions as unknown as ContributionInternals).getContributionActionContext('missing-user', 'contribution-id'), + null, +); + +const deleteQueryStart = queries.length; +queuedResults.push([ + { + id: 'delete-id', + userId: '1234567', + status: 'pending', + simulator: 'msfs2024', + actorIsProductManager: 0, + }, +]); +queuedResults.push([]); +assert.equal(await contributions.deleteContribution('delete-id', '1234567'), true); +const deleteQueries = queries.slice(deleteQueryStart); +assert.equal(deleteQueries.length, 2, 'delete authorization and mutation should use two D1 statements'); +assert(!deleteQueries[0].query.includes('submitted_xml'), 'delete authorization must not transfer contribution XML'); + +type AuthInternals = { + fetchLoginState(vatsimId: string): Promise; +}; +const auth = new AuthService(fakeDb, new VatsimService('client', 'secret')); +queuedResults.push([]); +await assert.rejects( + () => (auth as unknown as AuthInternals).fetchLoginState('1234567'), + /Failed to load login state/, + 'an impossible empty anchor result should fail with an explicit invariant error', +); + +const contact = new ContactService(fakeDb); +queuedResults.push([{ id: 'contact-id' }]); +assert.equal(await contact.deleteMessage('contact-id'), true); +assert(queries.at(-1)?.query.includes('DELETE FROM contact_messages WHERE id = ? RETURNING id')); +queuedResults.push([]); +assert.equal(await contact.deleteMessage('missing-contact'), false); + +console.log( + JSON.stringify({ + cacheCoalescing: 'passed', + cacheRevalidation: 'passed', + xmlCache: 'passed', + vatsimCoalescing: 'passed', + r2Range: 'passed', + nestedCdnRoute: 'passed', + contributionQueryShape: 'passed', + returningDelete: 'passed', + }), +); diff --git a/benchmarks/backend.ts b/benchmarks/backend.ts new file mode 100644 index 0000000..b1bbd42 --- /dev/null +++ b/benchmarks/backend.ts @@ -0,0 +1,196 @@ +import assert from 'node:assert/strict'; +import { performance } from 'node:perf_hooks'; +import { CacheKeys } from '../src/services/cache'; + +type Variant = { name: string; iterations: number; run: () => unknown }; + +function checksum(value: unknown): number { + if (typeof value === 'string') return value.length; + if (typeof value === 'number') return value; + if (value instanceof Response) return value.status + value.headers.get('X-Cache')!.length; + if (value && typeof value === 'object') return Object.keys(value).length; + return 0; +} + +function benchmark(variants: Variant[]): Array> { + return variants.map((variant) => { + for (let index = 0; index < Math.min(2_000, variant.iterations); index++) variant.run(); + const samples: number[] = []; + let resultChecksum = 0; + for (let sample = 0; sample < 11; sample++) { + const startedAt = performance.now(); + for (let index = 0; index < variant.iterations; index++) resultChecksum += checksum(variant.run()); + samples.push(performance.now() - startedAt); + } + const ordered = samples.toSorted((left, right) => left - right); + const medianMs = ordered[5]; + return { + variant: variant.name, + iterations: variant.iterations, + medianMs: Number(medianMs.toFixed(3)), + nsPerOperation: Number(((medianMs * 1_000_000) / variant.iterations).toFixed(1)), + checksum: resultChecksum, + }; + }); +} + +const cacheRequest = new Request( + 'https://api.stopbars.test/contributions?summary=true&status=approved&airport=YSSY&simulator=msfs2024', +); +function currentCacheKey() { + return CacheKeys.fromUrl(cacheRequest); +} +function arrayCacheKey() { + const url = new URL(cacheRequest.url); + const path = url.pathname.replace(/[^A-Za-z0-9/_-]/g, ''); + const params = Array.from(url.searchParams.entries()) + .filter(([key]) => !/^auth(orization)?$/i.test(key)) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`) + .join('&'); + return params ? `${path}?${params}` : path; +} +function loopCacheKey() { + const url = new URL(cacheRequest.url); + const path = url.pathname.replace(/[^A-Za-z0-9/_-]/g, ''); + const entries: Array<[string, string]> = []; + for (const [key, value] of url.searchParams) { + if (!/^auth(orization)?$/i.test(key)) entries.push([key, value]); + } + entries.sort(([left], [right]) => left.localeCompare(right)); + let params = ''; + for (const [key, value] of entries) { + if (params) params += '&'; + params += `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + return params ? `${path}?${params}` : path; +} +assert.equal(loopCacheKey(), currentCacheKey()); +assert.equal(arrayCacheKey(), currentCacheKey()); + +const cachedPayload = JSON.stringify({ items: Array.from({ length: 30 }, (_, index) => ({ id: index, active: true })) }); +const cachedHeaders = { 'Content-Type': 'application/json', 'Cache-Control': 'max-age=60', ETag: '"cache-test"' }; +function rewriteCachedResponseWithHeadersClone() { + const cached = new Response(cachedPayload, { headers: cachedHeaders }); + const headers = new Headers(cached.headers); + headers.delete('Cache-Control'); + headers.set('X-Cache', 'HIT'); + return new Response(cached.body, { status: cached.status, statusText: cached.statusText, headers }); +} +function rewriteCachedResponseDirectly() { + const cached = new Response(cachedPayload, { headers: cachedHeaders }); + const response = new Response(cached.body, cached); + response.headers.delete('Cache-Control'); + response.headers.set('X-Cache', 'HIT'); + return response; +} +const currentResponse = rewriteCachedResponseWithHeadersClone(); +const directResponse = rewriteCachedResponseDirectly(); +assert.equal(currentResponse.status, directResponse.status); +assert.deepEqual([...currentResponse.headers], [...directResponse.headers]); + +const submittedXml = `${''.repeat(2_000)}`; +const fullContribution = { + id: 'contribution-id', + userId: '1234567', + userDisplayName: 'Controller', + airportIcao: 'YSSY', + packageName: 'Sydney Ground', + submittedXml, + notes: null, + simulator: 'msfs2024', + submissionDate: '2026-07-19T00:00:00.000Z', + status: 'approved', + rejectionReason: null, + decisionDate: '2026-07-19T01:00:00.000Z', +}; +const mapDescriptor = { packageName: fullContribution.packageName, simulator: fullContribution.simulator }; +const fullContributionBytes = JSON.stringify(fullContribution).length; +const mapDescriptorBytes = JSON.stringify(mapDescriptor).length; +assert.equal(mapDescriptor.packageName, fullContribution.packageName); +assert.equal(mapDescriptor.simulator, fullContribution.simulator); + +const isoDates = [ + '2026-07-18T10:00:00.000Z', + '2026-07-19T01:00:00.000Z', + '2025-12-31T23:59:59.000Z', +]; +assert.deepEqual( + isoDates.toSorted((left, right) => right.localeCompare(left)), + isoDates.toSorted((left, right) => Date.parse(right) - Date.parse(left)), +); + +const connectionCsv = '1234567,YSSY_TWR,atc,120.500,100,-33.946,151.177'; +function repeatedTrimStatusParse() { + if (!connectionCsv.trim()) return null; + const [cid, callsign, type] = connectionCsv.trim().split(','); + return cid && callsign && type ? { cid, callsign, type } : null; +} +function singleTrimStatusParse() { + const trimmed = connectionCsv.trim(); + if (!trimmed) return null; + const [cid, callsign, type] = trimmed.split(','); + return cid && callsign && type ? { cid, callsign, type } : null; +} +assert.deepEqual(singleTrimStatusParse(), repeatedTrimStatusParse()); + +const controllerCallsign = 'YSSY_TWR'; +function splitCallsignSuffix() { + const parts = controllerCallsign.toUpperCase().split('_'); + return parts.length < 2 ? null : (parts[parts.length - 1] || null); +} +function lastIndexCallsignSuffix() { + const upper = controllerCallsign.toUpperCase(); + const separator = upper.lastIndexOf('_'); + return separator < 0 || separator === upper.length - 1 ? null : upper.slice(separator + 1); +} +assert.equal(lastIndexCallsignSuffix(), splitCallsignSuffix()); + +console.table( + benchmark([ + { name: 'cache key/array pipeline', iterations: 100_000, run: arrayCacheKey }, + { name: 'cache key/single collection loop', iterations: 100_000, run: loopCacheKey }, + { name: 'cache hit/clone Headers + Response', iterations: 20_000, run: rewriteCachedResponseWithHeadersClone }, + { name: 'cache hit/clone Response then mutate', iterations: 20_000, run: rewriteCachedResponseDirectly }, + { name: 'VATSIM CSV/repeated trim', iterations: 200_000, run: repeatedTrimStatusParse }, + { name: 'VATSIM CSV/single trim', iterations: 200_000, run: singleTrimStatusParse }, + { name: 'callsign suffix/split', iterations: 500_000, run: splitCallsignSuffix }, + { name: 'callsign suffix/lastIndexOf', iterations: 500_000, run: lastIndexCallsignSuffix }, + { name: 'latest map/full contribution JSON', iterations: 2_000, run: () => JSON.stringify(fullContribution) }, + { name: 'latest map/slim descriptor JSON', iterations: 2_000, run: () => JSON.stringify(mapDescriptor) }, + ]), +); + +const uniqueMisses = 1_000; +const coldBurst = 100; +console.log( + JSON.stringify({ + semanticEquality: true, + cacheApiCalls: { + uniqueMissesCurrent: uniqueMisses * 2, + uniqueMissesWithFreshVersionHint: uniqueMisses + 1, + coldBurstCurrent: coldBurst * 2, + coldBurstWithCoalescedVersionRead: coldBurst + 1, + }, + contributionActionD1CallsAfterRouteAuth: { + decision: { current: 2, batchedContext: 1 }, + delete: { current: 3, batchedContext: 1 }, + regenerate: { current: 4, batchedContext: 1 }, + }, + returningMutationD1CallsAfterAuthorization: { + contactDelete: { readThenDelete: 2, deleteReturning: 1 }, + divisionRename: { readThenUpdate: 2, updateReturning: 1 }, + }, + latestMapD1PayloadBytes: { + fullContribution: fullContributionBytes, + slimDescriptor: mapDescriptorBytes, + reduction: Number((fullContributionBytes / mapDescriptorBytes).toFixed(1)), + }, + latestMapQueryPlan: { + datetimeOrder: 'covering index search + temporary B-tree sort', + isoTextOrder: 'covering index search; no temporary sort', + }, + concurrentVatsimStatusFetches: { current: 2, coalesced: 1 }, + r2BytesForOneMegabyteRangeOfHundredMegabyteObject: { current: 100 * 1024 * 1024, ranged: 1024 * 1024 }, + }), +); diff --git a/benchmarks/compute.ts b/benchmarks/compute.ts new file mode 100644 index 0000000..95ecfec --- /dev/null +++ b/benchmarks/compute.ts @@ -0,0 +1,334 @@ +import assert from 'node:assert/strict'; +import { performance } from 'node:perf_hooks'; +import { calculateDestinationPoint, calculateDistance, calculateHeading, generateEquidistantPoints } from '../src/services/bars/geoUtils'; +import type { GeoPoint } from '../src/services/bars/types'; +import { sanitizeContributionXml } from '../src/services/xml-sanitizer'; + +type Variant = { + name: string; + operationsPerSample: number; + run: () => number; +}; + +type Summary = { + name: string; + samplesMs: number[]; + medianMs: number; + minMs: number; + operationsPerSecond: number; + checksum: number; +}; + +const WARMUP_SAMPLES = 2; +const MEASURED_SAMPLES = 11; +// Mirrors the production XML 1.0 control-character filter being benchmarked. +// eslint-disable-next-line no-control-regex +const DISALLOWED_XML_CONTROL_CHARS = new RegExp('[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]', 'g'); + +function runVariant(variant: Variant): Summary { + const runSample = (): { elapsedMs: number; checksum: number } => { + let checksum = 0; + const started = performance.now(); + for (let index = 0; index < variant.operationsPerSample; index++) checksum += variant.run(); + return { elapsedMs: performance.now() - started, checksum }; + }; + + for (let index = 0; index < WARMUP_SAMPLES; index++) runSample(); + const samples: number[] = []; + let checksum = 0; + for (let index = 0; index < MEASURED_SAMPLES; index++) { + const sample = runSample(); + samples.push(sample.elapsedMs); + checksum += sample.checksum; + } + const ordered = [...samples].sort((a, b) => a - b); + const medianMs = ordered[Math.floor(ordered.length / 2)]; + return { + name: variant.name, + samplesMs: samples.map((sample) => Number(sample.toFixed(3))), + medianMs: Number(medianMs.toFixed(3)), + minMs: Number(ordered[0].toFixed(3)), + operationsPerSecond: Math.round((variant.operationsPerSample * 1000) / medianMs), + checksum, + }; +} + +// Previous implementation: creates an array entry for every Unicode code point, +// filters it, then joins the whole document again. +function stripControlsArrayFrom(value: string): string { + return Array.from(value) + .filter((character) => { + const code = character.charCodeAt(0); + return !(code <= 0x08 || code === 0x0b || code === 0x0c || (code >= 0x0e && code <= 0x1f)); + }) + .join(''); +} + +// Alternative considered: scan once and concatenate only the valid slices. +function stripControlsManualSlices(value: string): string { + let output = ''; + let sliceStart = 0; + for (let index = 0; index < value.length; index++) { + const code = value.charCodeAt(index); + if (code <= 0x08 || code === 0x0b || code === 0x0c || (code >= 0x0e && code <= 0x1f)) { + if (sliceStart < index) output += value.slice(sliceStart, index); + sliceStart = index + 1; + } + } + if (sliceStart === 0) return value; + return sliceStart < value.length ? output + value.slice(sliceStart) : output; +} + +// Selected implementation in xml-sanitizer.ts. +function stripControlsRegex(value: string): string { + return value.replace(DISALLOWED_XML_CONTROL_CHARS, ''); +} + +function generateEquidistantResetScan(points: GeoPoint[], interval: number): GeoPoint[] { + if (points.length < 2) return points; + if (interval <= 0) return points.map((point) => ({ ...point })); + const segmentLengths = new Array(points.length - 1); + const segmentBearings = new Array(points.length - 1); + for (let index = 0; index < points.length - 1; index++) { + segmentLengths[index] = calculateDistance(points[index], points[index + 1]); + segmentBearings[index] = calculateHeading(points[index], points[index + 1]); + } + const totalPathLength = segmentLengths.reduce((sum, length) => sum + length, 0); + if (totalPathLength === 0) return [{ ...points[0] }]; + const pointCount = Math.max(1, Math.floor(totalPathLength / interval) + 1); + const startOffset = Math.max(0, (totalPathLength - (pointCount - 1) * interval) / 2); + const result: GeoPoint[] = []; + for (let outputIndex = 0; outputIndex < pointCount; outputIndex++) { + const distance = Math.min(startOffset + outputIndex * interval, totalPathLength); + if (distance <= 0) { + result.push({ ...points[0] }); + continue; + } + let remaining = distance; + let segmentIndex = 0; + while (segmentIndex < segmentLengths.length) { + const length = segmentLengths[segmentIndex]; + if (remaining <= length) { + result.push(calculateDestinationPoint(points[segmentIndex], remaining, segmentBearings[segmentIndex])); + break; + } + remaining -= length; + segmentIndex++; + } + } + return result; +} + +// Alternative considered: cumulative lengths plus a binary search per output. +function generateEquidistantBinarySearch(points: GeoPoint[], interval: number): GeoPoint[] { + if (points.length < 2) return points; + if (interval <= 0) return points.map((point) => ({ ...point })); + const segmentLengths = new Array(points.length - 1); + const segmentBearings = new Array(points.length - 1); + const cumulative = new Array(points.length); + cumulative[0] = 0; + for (let index = 0; index < segmentLengths.length; index++) { + segmentLengths[index] = calculateDistance(points[index], points[index + 1]); + segmentBearings[index] = calculateHeading(points[index], points[index + 1]); + cumulative[index + 1] = cumulative[index] + segmentLengths[index]; + } + const totalPathLength = cumulative[cumulative.length - 1]; + if (totalPathLength === 0) return [{ ...points[0] }]; + const pointCount = Math.max(1, Math.floor(totalPathLength / interval) + 1); + const startOffset = Math.max(0, (totalPathLength - (pointCount - 1) * interval) / 2); + const result: GeoPoint[] = []; + for (let outputIndex = 0; outputIndex < pointCount; outputIndex++) { + const distance = Math.min(startOffset + outputIndex * interval, totalPathLength); + let low = 0; + let high = segmentLengths.length - 1; + while (low < high) { + const middle = (low + high) >>> 1; + if (distance <= cumulative[middle + 1]) high = middle; + else low = middle + 1; + } + result.push(calculateDestinationPoint(points[low], distance - cumulative[low], segmentBearings[low])); + } + return result; +} + +function generateEquidistantHybrid(points: GeoPoint[], interval: number, maxBinarySegments: number): GeoPoint[] { + if (points.length < 2) return points; + if (interval <= 0) return points.map((point) => ({ ...point })); + const segmentCount = points.length - 1; + const segmentLengths = new Array(segmentCount); + const segmentBearings = new Array(segmentCount); + const useResetScan = segmentCount <= 32; + const useBinarySearch = !useResetScan && segmentCount <= maxBinarySegments; + const cumulative = useBinarySearch ? new Array(points.length) : undefined; + if (cumulative) cumulative[0] = 0; + let totalPathLength = 0; + for (let index = 0; index < segmentCount; index++) { + const length = calculateDistance(points[index], points[index + 1]); + segmentLengths[index] = length; + segmentBearings[index] = calculateHeading(points[index], points[index + 1]); + totalPathLength += length; + if (cumulative) cumulative[index + 1] = totalPathLength; + } + if (totalPathLength === 0) return [{ ...points[0] }]; + const pointCount = Math.max(1, Math.floor(totalPathLength / interval) + 1); + const startOffset = Math.max(0, (totalPathLength - (pointCount - 1) * interval) / 2); + const result: GeoPoint[] = []; + if (useResetScan) { + for (let outputIndex = 0; outputIndex < pointCount; outputIndex++) { + const distance = Math.min(startOffset + outputIndex * interval, totalPathLength); + if (distance <= 0) { + result.push({ ...points[0] }); + continue; + } + let remaining = distance; + let segmentIndex = 0; + while (segmentIndex < segmentCount - 1 && remaining > segmentLengths[segmentIndex]) { + remaining -= segmentLengths[segmentIndex++]; + } + result.push(calculateDestinationPoint(points[segmentIndex], remaining, segmentBearings[segmentIndex])); + } + return result; + } + if (cumulative) { + for (let outputIndex = 0; outputIndex < pointCount; outputIndex++) { + const distance = Math.min(startOffset + outputIndex * interval, totalPathLength); + let low = 0; + let high = segmentCount - 1; + while (low < high) { + const middle = (low + high) >>> 1; + if (distance <= cumulative[middle + 1]) high = middle; + else low = middle + 1; + } + result.push(calculateDestinationPoint(points[low], distance - cumulative[low], segmentBearings[low])); + } + return result; + } + let segmentIndex = 0; + let segmentStartDistance = 0; + for (let outputIndex = 0; outputIndex < pointCount; outputIndex++) { + const distance = Math.min(startOffset + outputIndex * interval, totalPathLength); + if (distance <= 0) { + result.push({ ...points[0] }); + continue; + } + while (segmentIndex < segmentCount - 1 && distance - segmentStartDistance > segmentLengths[segmentIndex]) { + segmentStartDistance += segmentLengths[segmentIndex++]; + } + result.push(calculateDestinationPoint(points[segmentIndex], distance - segmentStartDistance, segmentBearings[segmentIndex])); + } + return result; +} + +function assertPointsEquivalent(actual: GeoPoint[], expected: GeoPoint[]): number { + assert.equal(actual.length, expected.length); + let maxDeltaMeters = 0; + for (let index = 0; index < actual.length; index++) { + const deltaMeters = calculateDistance(actual[index], expected[index]); + maxDeltaMeters = Math.max(maxDeltaMeters, deltaMeters); + assert.ok(deltaMeters <= 0.2, `point differs by ${deltaMeters} meters at ${index}`); + } + return maxDeltaMeters; +} + +const xmlNodes = Array.from({ length: 20_000 }, (_, index) => `value-${index}\u0001🙂`).join('\n'); +const dirtyXml = ` \n\n${xmlNodes} `; +const trimmedXml = dirtyXml.trim().replace(/(<\?)(?!xml)([\s\S]*?\?>)/gi, ''); +const expectedControls = stripControlsArrayFrom(trimmedXml); +assert.equal(stripControlsManualSlices(trimmedXml), expectedControls); +assert.equal(stripControlsRegex(trimmedXml), expectedControls); +assert.equal(sanitizeContributionXml(dirtyXml, { maxBytes: dirtyXml.length + 1 }), stripControlsRegex(trimmedXml).replace(/>\s+<')); + +const makePath = (pointCount: number): GeoPoint[] => + Array.from({ length: pointCount }, (_, index) => ({ + lat: -31.94 + index * 0.000045 + Math.sin(index / 8) * 0.00001, + lon: 115.96 + index * 0.00005, + })); +const geometryScenarios = [ + { name: 'short', points: makePath(16), interval: 11.25, operationsPerSample: 2_000 }, + { name: 'medium', points: makePath(80), interval: 3, operationsPerSample: 1_000 }, + { name: 'long', points: makePath(240), interval: 3, operationsPerSample: 400 }, + { name: 'crossover', points: makePath(400), interval: 3, operationsPerSample: 200 }, + { name: 'very-long', points: makePath(1_000), interval: 3, operationsPerSample: 50 }, +]; +let maxGeometryDeltaMeters = 0; +for (const scenario of geometryScenarios) { + const expectedPoints = generateEquidistantResetScan(scenario.points, scenario.interval); + maxGeometryDeltaMeters = Math.max( + maxGeometryDeltaMeters, + assertPointsEquivalent(generateEquidistantBinarySearch(scenario.points, scenario.interval), expectedPoints), + assertPointsEquivalent(generateEquidistantPoints(scenario.points, scenario.interval), expectedPoints), + assertPointsEquivalent(generateEquidistantHybrid(scenario.points, scenario.interval, 256), expectedPoints), + assertPointsEquivalent(generateEquidistantHybrid(scenario.points, scenario.interval, 512), expectedPoints), + ); +} + +const variants: Variant[] = [ + { name: 'xml/array-from (before)', operationsPerSample: 20, run: () => stripControlsArrayFrom(trimmedXml).length }, + { name: 'xml/manual-slices', operationsPerSample: 20, run: () => stripControlsManualSlices(trimmedXml).length }, + { name: 'xml/regex (current)', operationsPerSample: 20, run: () => stripControlsRegex(trimmedXml).length }, + ...geometryScenarios.flatMap(({ name, points, interval, operationsPerSample }) => [ + { + name: `geometry/${name}/reset-scan (before)`, + operationsPerSample, + run: () => generateEquidistantResetScan(points, interval).length, + }, + { + name: `geometry/${name}/binary-search`, + operationsPerSample, + run: () => generateEquidistantBinarySearch(points, interval).length, + }, + { + name: `geometry/${name}/single-sweep (current)`, + operationsPerSample, + run: () => generateEquidistantPoints(points, interval).length, + }, + { + name: `geometry/${name}/hybrid-256`, + operationsPerSample, + run: () => generateEquidistantHybrid(points, interval, 256).length, + }, + { + name: `geometry/${name}/hybrid-512`, + operationsPerSample, + run: () => generateEquidistantHybrid(points, interval, 512).length, + }, + ]), +]; + +const summaries = variants.map(runVariant); +const byName = new Map(summaries.map((summary) => [summary.name, summary])); +const speedups = { + xml: Number((byName.get('xml/array-from (before)')!.medianMs / byName.get('xml/regex (current)')!.medianMs).toFixed(2)), + geometry: Number( + ( + geometryScenarios.reduce( + (total, scenario) => total + byName.get(`geometry/${scenario.name}/reset-scan (before)`)!.medianMs, + 0, + ) / + geometryScenarios.reduce( + (total, scenario) => total + byName.get(`geometry/${scenario.name}/single-sweep (current)`)!.medianMs, + 0, + ) + ).toFixed(2), + ), +}; +const report = { + generatedAt: new Date().toISOString(), + runtime: process.version, + warmupSamples: WARMUP_SAMPLES, + measuredSamples: MEASURED_SAMPLES, + fixtures: { + xmlCharacters: dirtyXml.length, + geometry: geometryScenarios.map(({ name, points, interval }) => ({ name, pathPoints: points.length, intervalMeters: interval })), + }, + semanticEquality: { + xmlExact: true, + geometryToleranceMeters: 0.2, + maxGeometryDeltaMeters, + }, + speedups, + results: summaries, +}; + +console.table(summaries.map(({ name, medianMs, minMs, operationsPerSecond }) => ({ name, medianMs, minMs, operationsPerSecond }))); +console.log(JSON.stringify(report)); diff --git a/benchmarks/database.ts b/benchmarks/database.ts new file mode 100644 index 0000000..75a175a --- /dev/null +++ b/benchmarks/database.ts @@ -0,0 +1,170 @@ +import assert from 'node:assert/strict'; +import { performance } from 'node:perf_hooks'; + +type PointRow = { id: string; airportId: string; name: string }; +type DownloadCounts = { versionCount: number; productTotal: number }; + +class FakeD1 { + public calls = 0; + public readonly points = new Map(); + public readonly faqOrder = new Map(); + public readonly downloads = new Map(); + + constructor() { + for (let i = 0; i < 200; i += 1) { + const id = `BARS_${String(i).padStart(5, '0')}`; + this.points.set(id, { id, airportId: `Y${String(i % 10).padStart(3, '0')}`, name: `Point ${i}` }); + } + for (let i = 0; i < 50; i += 1) this.faqOrder.set(`faq-${i}`, i); + this.downloads.set('Installer@1.0.0', 7); + this.downloads.set('Installer@0.9.0', 3); + } + + private transportCost(): void { + // Fixed work makes the benchmark deterministic while representing per-call + // binding/serialization overhead. It is intentionally not wall-clock sleep. + let state = 0x9e3779b9; + for (let i = 0; i < 12_000; i += 1) state = Math.imul(state ^ i, 1664525) + 1013904223; + if (state === 0) throw new Error('unreachable'); + } + + async call(operation: () => T): Promise { + this.calls += 1; + this.transportCost(); + return operation(); + } + + async batch(operations: Array<() => T>): Promise { + return this.call(() => operations.map((operation) => operation())); + } +} + +const requestedIds = [ + ...Array.from({ length: 98 }, (_, index) => `BARS_${String(index).padStart(5, '0')}`), + 'BARS_00007', // duplicate: order and duplicates must be preserved + 'BARS_99999', // missing: null position must be preserved +]; + +async function pointsSequential(db: FakeD1): Promise> { + const rows: Array = []; + for (const id of requestedIds) rows.push(await db.call(() => db.points.get(id) ?? null)); + return rows; +} + +async function pointsConcurrent(db: FakeD1): Promise> { + return Promise.all(requestedIds.map((id) => db.call(() => db.points.get(id) ?? null))); +} + +async function pointsInQuery(db: FakeD1): Promise> { + const unique = [...new Set(requestedIds)]; + const rows = await db.call(() => unique.flatMap((id) => (db.points.has(id) ? [db.points.get(id)!] : []))); + const byId = new Map(rows.map((row) => [row.id, row])); + return requestedIds.map((id) => byId.get(id) ?? null); +} + +async function faqSequential(db: FakeD1): Promise { + for (let i = 0; i < 50; i += 1) await db.call(() => db.faqOrder.set(`faq-${i}`, 49 - i)); + return [...db.faqOrder.values()]; +} + +async function faqBatch(db: FakeD1): Promise { + await db.batch(Array.from({ length: 50 }, (_, i) => () => db.faqOrder.set(`faq-${i}`, 49 - i))); + return [...db.faqOrder.values()]; +} + +async function airportSeparate(db: FakeD1): Promise<{ airport: PointRow | null; runways: string[] }> { + const airport = await db.call(() => db.points.get('BARS_00001') ?? null); + const runways = await db.call(() => ['01/19', '09/27']); + return { airport, runways }; +} + +async function airportBatch(db: FakeD1): Promise<{ airport: PointRow | null; runways: string[] }> { + const [airport, runways] = await db.batch([() => db.points.get('BARS_00001') ?? null, () => ['01/19', '09/27']]); + return { airport: airport as PointRow | null, runways: runways as string[] }; +} + +async function downloadLegacy(db: FakeD1): Promise { + const key = 'Installer@1.0.0'; + await db.call(() => db.downloads.has(key)); // ensure row + await db.call(() => null); // read IP hit + await db.call(() => true); // insert/update IP hit + const versionCount = await db.call(() => { + const count = (db.downloads.get(key) ?? 0) + 1; + db.downloads.set(key, count); + return count; + }); + await db.call(() => true); // expired-hit cleanup + const productTotal = await db.call(() => [...db.downloads.values()].reduce((sum, count) => sum + count, 0)); + return { versionCount, productTotal }; +} + +async function downloadBatched(db: FakeD1): Promise { + const key = 'Installer@1.0.0'; + await db.batch([() => db.downloads.has(key), () => true, () => db.downloads.get(key) ?? 0]); + const [versionCount] = await db.batch([ + () => { + const count = (db.downloads.get(key) ?? 0) + 1; + db.downloads.set(key, count); + return count; + }, + () => true, + ]); + return { + versionCount: versionCount as number, + productTotal: [...db.downloads.values()].reduce((sum, count) => sum + count, 0), + }; +} + +type Variant = { name: string; run: (db: FakeD1) => Promise }; + +async function benchmarkGroup(variants: Variant[]): Promise>> { + const expected = await variants[0].run(new FakeD1()); + for (const variant of variants.slice(1)) assert.deepEqual(await variant.run(new FakeD1()), expected, `${variant.name} changed results`); + + for (const variant of variants) { + for (let i = 0; i < 20; i += 1) await variant.run(new FakeD1()); + } + + const rows: Array> = []; + for (const variant of variants) { + const timings: number[] = []; + let calls = 0; + for (let i = 0; i < 100; i += 1) { + const db = new FakeD1(); + const start = performance.now(); + await variant.run(db); + timings.push(performance.now() - start); + calls = db.calls; + } + timings.sort((a, b) => a - b); + rows.push({ + variant: variant.name, + calls, + p50Ms: Number(timings[50].toFixed(3)), + p95Ms: Number(timings[95].toFixed(3)), + }); + } + return rows; +} + +const results = [ + ...(await benchmarkGroup([ + { name: 'points: sequential first()', run: pointsSequential }, + { name: 'points: concurrent first()', run: pointsConcurrent }, + { name: 'points: one IN query', run: pointsInQuery }, + ])), + ...(await benchmarkGroup([ + { name: 'FAQ reorder: sequential writes', run: faqSequential }, + { name: 'FAQ reorder: D1 batch', run: faqBatch }, + ])), + ...(await benchmarkGroup([ + { name: 'airport: separate airport/runway reads', run: airportSeparate }, + { name: 'airport: read batch', run: airportBatch }, + ])), + ...(await benchmarkGroup([ + { name: 'download: legacy fresh-hit path', run: downloadLegacy }, + { name: 'download: batched upsert path', run: downloadBatched }, + ])), +]; + +console.table(results); diff --git a/benchmarks/realtime-behavior.ts b/benchmarks/realtime-behavior.ts new file mode 100644 index 0000000..97340ec --- /dev/null +++ b/benchmarks/realtime-behavior.ts @@ -0,0 +1,367 @@ +import assert from 'node:assert/strict'; +import { mock } from 'bun:test'; +import type { AirportState, ClientType, Packet } from '../src/types'; +import type { AuthService } from '../src/services/auth'; +import type { VatsimService } from '../src/services/vatsim'; + +const cloudflareBackground: Promise[] = []; +mock.module('cloudflare:workers', () => ({ + waitUntil: (promise: Promise) => void cloudflareBackground.push(promise), +})); +const { Connection } = await import('../src/network/connection'); +const { PostHogService } = await import('../src/services/posthog'); + +class FakeSocket { + readyState = WebSocket.OPEN; + sent: string[] = []; + closed?: { code?: number; reason?: string }; + + send(value: string) { + this.sent.push(value); + } + + close(code?: number, reason?: string) { + this.readyState = WebSocket.CLOSED; + this.closed = { code, reason }; + } +} + +class FakeDurableObjectState { + readonly id = { toString: () => '0000000000000000000000000000000000000000000000000000000000000000' }; + readonly values = new Map(); + readonly background: Promise[] = []; + initialization: Promise = Promise.resolve(); + readonly storage = { + list: async ({ prefix }: { prefix: string }): Promise> => + new Map( + Array.from(this.values.entries()).filter(([key]) => key.startsWith(prefix)) as Array<[string, T]>, + ), + put: async (key: string, value: unknown) => void this.values.set(key, value), + delete: async (key: string) => this.values.delete(key), + }; + + blockConcurrencyWhile(callback: () => Promise) { + this.initialization = callback(); + return this.initialization; + } + + waitUntil(promise: Promise) { + this.background.push(promise); + } +} + +type InternalSocketInfo = { + controllerId: string; + type: ClientType; + airport: string; + lastHeartbeat: number; + lastStatusCheck: number; + statusCheckInFlight: boolean; + consecutiveVatsimFailures: number; + sendFailures: number; +}; + +type ConnectionInternals = { + sockets: Map; + airportStates: Map; + offlineStateCache: Map< + string, + { + template?: Array<{ id: string; state: boolean }>; + defaultStates?: ReadonlyMap; + expiresAt: number; + } + >; + registerSocket(socket: WebSocket, info: { controllerId: string; type: ClientType; airport: string; lastHeartbeat: number }): void; + unregisterSocket(socket: WebSocket): InternalSocketInfo | undefined; + validatePacket(packet: unknown): packet is Packet; + broadcast(packet: Packet, sender?: WebSocket, trackAnalytics?: boolean): number; + broadcastToControllers(packet: Packet, sender?: WebSocket, trackAnalytics?: boolean): number; + trackMessage( + details: { clientType: ClientType; messageType: Packet['type']; airport: string; meta?: Record }, + broadcastRecipients?: number, + ): void; + posthog: { + track(event: string, properties: Record): void; + trackBatch(events: readonly { event: string; properties?: Record }[]): void; + }; + handleMultiStateUpdate( + packet: Packet, + controllerId: string, + connectionAirport: string, + ): Promise<{ updates: unknown[]; timestamp: number; airport: string }>; + handleSharedStateUpdate(packet: Packet, controllerId: string, connectionAirport: string): Promise>; + checkSocketStatus(socket: WebSocket, socketInfo: InternalSocketInfo, now: number): Promise | undefined; + enqueueSocketTask(socket: WebSocket, task: () => Promise): Promise; + flushAirportDurableState(airport: string): Promise; +}; + +let banChecks = 0; +let vatsimChecks = 0; +const fakeAuth = { + isVatsimIdBanned: async () => { + banChecks++; + await Promise.resolve(); + return false; + }, +} as unknown as AuthService; +const fakeVatsim = { + getUserStatus: async (controllerId: string) => { + vatsimChecks++; + await Promise.resolve(); + return { cid: controllerId, callsign: 'YSSY_TWR', type: 'atc' }; + }, + isController: (status: { type: string }) => status.type === 'atc', + isPilot: (status: { type: string }) => status.type === 'pilot', + isObserver: () => false, +} as unknown as VatsimService; +const fakeState = new FakeDurableObjectState(); +const fakeEnv = { DB: {}, POSTHOG_HOST: 'https://example.invalid' } as unknown as Env; +const connection = new Connection(fakeEnv, fakeAuth, fakeVatsim, fakeState as unknown as DurableObjectState); +await fakeState.initialization; +const internal = connection as unknown as ConnectionInternals; +const analyticsSingles: Array<{ event: string; properties: Record }> = []; +const analyticsBatches: Array }[]> = []; +internal.posthog = { + track: (event, properties) => void analyticsSingles.push({ event, properties }), + trackBatch: (events) => void analyticsBatches.push(events), +}; + +const template = [ + { id: 'SB1', state: false }, + { id: 'LO1', state: true }, +]; +internal.offlineStateCache.set('YSSY', { + template, + defaultStates: new Map(template.map((point) => [point.id, point.state])), + expiresAt: Date.now() + 60_000, +}); + +const controllerA = new FakeSocket(); +const controllerB = new FakeSocket(); +const pilotA = new FakeSocket(); +const pilotADuplicate = new FakeSocket(); +const observer = new FakeSocket(); +const now = Date.now(); +internal.registerSocket(controllerA as unknown as WebSocket, { + controllerId: '1000001', + type: 'controller', + airport: 'YSSY', + lastHeartbeat: now, +}); +internal.registerSocket(controllerB as unknown as WebSocket, { + controllerId: '1000002', + type: 'controller', + airport: 'YSSY', + lastHeartbeat: now, +}); +for (const socket of [pilotA, pilotADuplicate]) { + internal.registerSocket(socket as unknown as WebSocket, { + controllerId: '2000001', + type: 'pilot', + airport: 'YSSY', + lastHeartbeat: now, + }); +} +internal.registerSocket(observer as unknown as WebSocket, { + controllerId: '3000001', + type: 'observer', + airport: 'YSSY', + lastHeartbeat: now, +}); + +const indexedSnapshot = await connection.getState('YSSY'); +assert.deepEqual(indexedSnapshot.controllers, ['1000001', '1000002']); +assert.deepEqual(indexedSnapshot.pilots, ['2000001']); +assert.equal(indexedSnapshot.offline, false); + +const broadcastRecipients = internal.broadcast( + { type: 'STATE_UPDATE', airport: 'YSSY', data: { objectId: 'SB1', state: true } }, + controllerA as unknown as WebSocket, + false, +); +internal.trackMessage( + { clientType: 'controller', messageType: 'STATE_UPDATE', airport: 'YSSY', meta: { objectId: 'SB1' } }, + broadcastRecipients, +); +assert.equal(controllerA.sent.length, 0); +assert.equal(controllerB.sent.length, 1); +assert.equal(pilotA.sent.length, 1); +assert.equal(pilotADuplicate.sent.length, 1); +assert.equal(observer.sent.length, 1); +assert.equal(broadcastRecipients, 4); +assert.deepEqual( + analyticsBatches[0].map((event) => event.event), + ['ws_broadcast', 'ws_message'], +); +assert.equal(analyticsSingles.length, 0); + +for (const socket of [controllerA, controllerB, pilotA, pilotADuplicate, observer]) socket.sent.length = 0; +const controllerRecipients = internal.broadcastToControllers( + { type: 'STOPBAR_CROSSING', airport: 'YSSY', data: { objectId: 'SB1' } }, + pilotA as unknown as WebSocket, + false, +); +internal.trackMessage( + { clientType: 'pilot', messageType: 'STOPBAR_CROSSING', airport: 'YSSY', meta: { objectId: 'SB1' } }, + controllerRecipients, +); +assert.equal(controllerA.sent.length, 1); +assert.equal(controllerB.sent.length, 1); +assert.equal(pilotA.sent.length, 0); +assert.equal(observer.sent.length, 0); +assert.equal(controllerRecipients, 2); +assert.equal(analyticsBatches.length, 2); + +const validPackets: Packet[] = [ + { type: 'HEARTBEAT' }, + { type: 'GET_STATE' }, + { type: 'STATE_UPDATE', data: { objectId: 'SB1', state: true } }, + { type: 'STATE_UPDATE', data: { objectId: 'SB1', patch: { nested: { enabled: true } } } }, + { type: 'MULTI_STATE_UPDATE', data: { updates: [{ objectId: 'SB1', state: true }] } }, + { type: 'SHARED_STATE_UPDATE', data: { sharedStatePatch: { profile: 'default' } } }, + { type: 'STOPBAR_CROSSING', data: { objectId: 'SB1' } }, +]; +for (const packet of validPackets) assert.equal(internal.validatePacket(packet), true); + +let deepArray: unknown = true; +for (let depth = 0; depth < 30; depth++) deepArray = [deepArray]; +const invalidPackets: unknown[] = [ + { type: 'UNKNOWN' }, + { type: 'STATE_UPDATE', data: { objectId: 'invalid id', state: true } }, + { type: 'STATE_UPDATE', data: { objectId: 'SB1', patch: [] } }, + { type: 'STATE_UPDATE', data: { objectId: 'SB1', patch: { constructor: {} } } }, + { type: 'MULTI_STATE_UPDATE', data: { updates: [] } }, + { type: 'SHARED_STATE_UPDATE', data: { sharedStatePatch: [] } }, + { type: 'SHARED_STATE_UPDATE', data: { sharedStatePatch: { nested: deepArray } } }, + { type: 'STOPBAR_CROSSING', data: { objectId: 'invalid id' } }, +]; +for (const packet of invalidPackets) assert.equal(internal.validatePacket(packet), false); + +await internal.handleMultiStateUpdate( + { + type: 'MULTI_STATE_UPDATE', + data: { updates: [{ objectId: 'SB1', state: true }, { objectId: 'LO1', state: false }] }, + }, + '1000001', + 'YSSY', +); +assert.equal(internal.airportStates.get('YSSY')?.objects.get('SB1')?.state, true); +assert.equal(internal.airportStates.get('YSSY')?.objects.get('LO1')?.state, false); + +for (const socket of [controllerA, controllerB, pilotA, pilotADuplicate, observer]) socket.sent.length = 0; +const sharedState = await internal.handleSharedStateUpdate( + { + type: 'SHARED_STATE_UPDATE', + data: { sharedStatePatch: { profile: 'default', nodes: { A1: true } } }, + }, + '1000001', + 'YSSY', +); +assert.deepEqual(sharedState, { profile: 'default', nodes: { A1: true } }); +for (const socket of [controllerA, controllerB, pilotA, pilotADuplicate, observer]) { + assert.equal(socket.sent.length, 1); + assert.deepEqual(JSON.parse(socket.sent[0]), { + type: 'SHARED_STATE_UPDATE', + airport: 'YSSY', + data: { sharedStatePatch: { profile: 'default', nodes: { A1: true } }, controllerId: '1000001' }, + timestamp: JSON.parse(socket.sent[0]).timestamp, + }); +} + +const firstStatus = internal.checkSocketStatus(controllerA as unknown as WebSocket, internal.sockets.get(controllerA as unknown as WebSocket)!, now + 180_000); +const secondStatus = internal.checkSocketStatus(controllerB as unknown as WebSocket, internal.sockets.get(controllerB as unknown as WebSocket)!, now + 180_000); +assert(firstStatus && secondStatus); +await Promise.all([firstStatus, secondStatus]); +assert.equal(banChecks, 2, 'Different CIDs must be checked independently'); +assert.equal(vatsimChecks, 2, 'Different CIDs must be checked independently'); + +const duplicateController = new FakeSocket(); +internal.registerSocket(duplicateController as unknown as WebSocket, { + controllerId: '1000001', + type: 'controller', + airport: 'YSSY', + lastHeartbeat: now, +}); +const beforeBanChecks = banChecks; +const beforeVatsimChecks = vatsimChecks; +const duplicateStatus = internal.checkSocketStatus( + duplicateController as unknown as WebSocket, + internal.sockets.get(duplicateController as unknown as WebSocket)!, + now + 360_000, +); +const originalStatus = internal.checkSocketStatus( + controllerA as unknown as WebSocket, + internal.sockets.get(controllerA as unknown as WebSocket)!, + now + 360_000, +); +assert(duplicateStatus && originalStatus); +await Promise.all([duplicateStatus, originalStatus]); +assert.equal(banChecks - beforeBanChecks, 1); +assert.equal(vatsimChecks - beforeVatsimChecks, 1); + +const queueOrder: number[] = []; +const firstQueued = internal.enqueueSocketTask(pilotA as unknown as WebSocket, async () => { + await Promise.resolve(); + queueOrder.push(1); +}); +const secondQueued = internal.enqueueSocketTask(pilotA as unknown as WebSocket, async () => void queueOrder.push(2)); +await Promise.all([firstQueued, secondQueued]); +assert.deepEqual(queueOrder, [1, 2]); + +internal.unregisterSocket(pilotA as unknown as WebSocket); +assert.deepEqual((await connection.getState('YSSY')).pilots, ['2000001']); +internal.unregisterSocket(pilotADuplicate as unknown as WebSocket); +assert.deepEqual((await connection.getState('YSSY')).pilots, []); + +await internal.flushAirportDurableState('YSSY'); +await Promise.allSettled(fakeState.background); +assert(fakeState.values.has('airport_state:YSSY')); +assert(fakeState.values.has('airport_shared_state:YSSY')); + +const originalFetch = globalThis.fetch; +let capturedBatchRequest: { input: RequestInfo | URL; init?: RequestInit } | undefined; +try { + globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => { + capturedBatchRequest = { input, init }; + return new Response(null, { status: 200 }); + }; + const posthog = new PostHogService({ + POSTHOG_API_KEY: 'ph_test', + POSTHOG_HOST: 'https://analytics.example.test', + } as Env); + posthog.trackBatch([ + { event: 'ws_broadcast', properties: { airport: 'YSSY', recipients: 4 } }, + { event: 'ws_message', properties: { airport: 'YSSY', messageType: 'STATE_UPDATE' } }, + ]); + await Promise.all(cloudflareBackground.splice(0)); +} finally { + globalThis.fetch = originalFetch; +} +assert(capturedBatchRequest); +assert.equal(String(capturedBatchRequest.input), 'https://analytics.example.test/batch/'); +const capturedBatchBody = JSON.parse(String(capturedBatchRequest.init?.body)) as { + api_key: string; + batch: Array<{ event: string; properties: Record; $process_person_profile: boolean }>; +}; +assert.equal(capturedBatchBody.api_key, 'ph_test'); +assert.deepEqual( + capturedBatchBody.batch.map((event) => event.event), + ['ws_broadcast', 'ws_message'], +); +assert(capturedBatchBody.batch.every((event) => event.properties.product === 'Core')); +assert(capturedBatchBody.batch.every((event) => event.properties.distinct_id === 'anonymous')); +assert(capturedBatchBody.batch.every((event) => event.$process_person_profile === false)); + +console.log( + JSON.stringify({ + protocolPacketsValidated: validPackets.length + invalidPackets.length, + indexedParticipantSnapshot: true, + broadcastRouting: true, + sharedStateSerialization: true, + analyticsBatching: true, + statusCheckCoalescing: true, + perSocketQueueOrdering: true, + persistence: true, + }), +); diff --git a/benchmarks/realtime.ts b/benchmarks/realtime.ts new file mode 100644 index 0000000..6766c11 --- /dev/null +++ b/benchmarks/realtime.ts @@ -0,0 +1,438 @@ +import assert from 'node:assert/strict'; +import { performance } from 'node:perf_hooks'; + +type SyncVariant = { + name: string; + iterations: number; + run: () => unknown; +}; + +const measuredSamples = 11; + +function checksum(value: unknown): number { + if (typeof value === 'number') return value; + if (typeof value === 'boolean') return value ? 1 : 0; + if (typeof value === 'string') return value.length; + if (Array.isArray(value)) return value.length; + if (value && typeof value === 'object') return Object.keys(value).length; + return 0; +} + +function benchmark(variants: SyncVariant[]): Array> { + return variants.map((variant) => { + for (let index = 0; index < Math.min(2_000, variant.iterations); index++) variant.run(); + const samples: number[] = []; + let resultChecksum = 0; + for (let sample = 0; sample < measuredSamples; sample++) { + const startedAt = performance.now(); + for (let index = 0; index < variant.iterations; index++) resultChecksum += checksum(variant.run()); + samples.push(performance.now() - startedAt); + } + const ordered = samples.toSorted((left, right) => left - right); + const medianMs = ordered[Math.floor(ordered.length / 2)]; + return { + variant: variant.name, + iterations: variant.iterations, + medianMs: Number(medianMs.toFixed(3)), + nsPerOperation: Number(((medianMs * 1_000_000) / variant.iterations).toFixed(1)), + checksum: resultChecksum, + }; + }); +} + +type ClientType = 'controller' | 'pilot' | 'observer'; +type SocketInfo = { controllerId: string; type: ClientType; airport: string; readyState: number }; +const openState = 1; +const socketEntries = Array.from({ length: 1_000 }, (_, index) => { + const type: ClientType = index % 5 === 0 ? 'controller' : index % 7 === 0 ? 'observer' : 'pilot'; + return [ + { id: index }, + { + controllerId: `CID-${index % 220}`, + type, + airport: index < 900 ? 'YSSY' : 'YMML', + readyState: openState, + } satisfies SocketInfo, + ] as const; +}); +const sockets = new Map(socketEntries); + +function snapshotByScan() { + const controllers: string[] = []; + const pilots: string[] = []; + const controllerIds = new Set(); + const pilotIds = new Set(); + for (const info of sockets.values()) { + if (info.airport !== 'YSSY') continue; + if (info.type === 'controller' && !controllerIds.has(info.controllerId)) { + controllerIds.add(info.controllerId); + controllers.push(info.controllerId); + } else if (info.type === 'pilot' && !pilotIds.has(info.controllerId)) { + pilotIds.add(info.controllerId); + pilots.push(info.controllerId); + } + } + return { controllers, pilots }; +} + +const indexedParticipants = new Map; pilots: Map }>(); +for (const info of sockets.values()) { + let airport = indexedParticipants.get(info.airport); + if (!airport) { + airport = { controllers: new Map(), pilots: new Map() }; + indexedParticipants.set(info.airport, airport); + } + const index = info.type === 'controller' ? airport.controllers : info.type === 'pilot' ? airport.pilots : null; + if (index) index.set(info.controllerId, (index.get(info.controllerId) ?? 0) + 1); +} +function snapshotByIndex() { + const airport = indexedParticipants.get('YSSY'); + return { + controllers: airport ? Array.from(airport.controllers.keys()) : [], + pilots: airport ? Array.from(airport.pilots.keys()) : [], + }; +} +assert.deepEqual(snapshotByIndex(), snapshotByScan()); + +function broadcastForEach() { + let recipients = 0; + sockets.forEach((info, socket) => { + if (socket.id !== 1 && info.readyState === openState && info.airport === 'YSSY') recipients++; + }); + return recipients; +} +function broadcastForOf() { + let recipients = 0; + for (const [socket, info] of sockets) { + if (socket.id !== 1 && info.readyState === openState && info.airport === 'YSSY') recipients++; + } + return recipients; +} +assert.equal(broadcastForEach(), broadcastForOf()); + +const controllerSocketIndex = new Map>(); +for (const [socket, info] of sockets) { + if (info.airport !== 'YSSY' || info.type !== 'controller') continue; + let indexedSockets = controllerSocketIndex.get(info.controllerId); + if (!indexedSockets) { + indexedSockets = new Set(); + controllerSocketIndex.set(info.controllerId, indexedSockets); + } + indexedSockets.add(socket); +} +function controllerBroadcastByScan() { + let recipients = 0; + for (const [socket, info] of sockets) { + if (socket.id !== 1 && info.readyState === openState && info.airport === 'YSSY' && info.type === 'controller') recipients++; + } + return recipients; +} +function controllerBroadcastByIndex() { + let recipients = 0; + for (const indexedSockets of controllerSocketIndex.values()) { + for (const socket of indexedSockets) { + if (socket.id !== 1) recipients++; + } + } + return recipients; +} +assert.equal(controllerBroadcastByIndex(), controllerBroadcastByScan()); + +const packetTypes = [ + 'HEARTBEAT', + 'HEARTBEAT_ACK', + 'STATE_UPDATE', + 'MULTI_STATE_UPDATE', + 'CLOSE', + 'SHARED_STATE_UPDATE', + 'INITIAL_STATE', + 'CONTROLLER_CONNECT', + 'CONTROLLER_DISCONNECT', + 'ERROR', + 'GET_STATE', + 'STATE_SNAPSHOT', + 'STOPBAR_CROSSING', +] as const; +const packetTypeSet = new Set(packetTypes); +const packetTypeRecord = Object.assign(Object.create(null) as Record, Object.fromEntries(packetTypes.map((type) => [type, true]))); +const packetTypeSamples: string[] = [...packetTypes, 'UNKNOWN', 'STATE_UPDATE', 'not-a-packet']; +const packetTypeSwitch = (type: string): boolean => { + switch (type) { + case 'HEARTBEAT': + case 'HEARTBEAT_ACK': + case 'STATE_UPDATE': + case 'MULTI_STATE_UPDATE': + case 'CLOSE': + case 'SHARED_STATE_UPDATE': + case 'INITIAL_STATE': + case 'CONTROLLER_CONNECT': + case 'CONTROLLER_DISCONNECT': + case 'ERROR': + case 'GET_STATE': + case 'STATE_SNAPSHOT': + case 'STOPBAR_CROSSING': + return true; + default: + return false; + } +}; +for (const type of packetTypeSamples) { + assert.equal(packetTypeSet.has(type), packetTypeSwitch(type)); + assert.equal(packetTypeRecord[type] === true, packetTypeSwitch(type)); +} +let setTypeIndex = 0; +let recordTypeIndex = 0; +let switchTypeIndex = 0; + +function recursiveSafeValue(value: unknown, maxDepth = 20, maxProperties = 100): boolean { + const seen = new WeakSet(); + const walk = (current: unknown, depth: number): boolean => { + if (current === null || typeof current !== 'object') return true; + if (Array.isArray(current)) return current.length <= 1_000 && current.every((item) => walk(item, depth + 1)); + if (depth > maxDepth || seen.has(current)) return false; + seen.add(current); + const keys = Object.keys(current as Record); + return keys.length <= maxProperties && keys.every((key) => key.length <= 100 && walk((current as Record)[key], depth + 1)); + }; + return walk(value, 0); +} + +function iterativeSafeValue(value: unknown, maxDepth = 20, maxProperties = 100): boolean { + const pending: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }]; + const seen = new WeakSet(); + while (pending.length > 0) { + const current = pending.pop()!; + if (current.value === null || typeof current.value !== 'object') continue; + if (current.depth > maxDepth || seen.has(current.value)) return false; + seen.add(current.value); + if (Array.isArray(current.value)) { + if (current.value.length > 1_000) return false; + for (let index = current.value.length - 1; index >= 0; index--) pending.push({ value: current.value[index], depth: current.depth + 1 }); + continue; + } + const record = current.value as Record; + const keys = Object.keys(record); + if (keys.length > maxProperties) return false; + for (const key of keys) { + if (key.length > 100) return false; + pending.push({ value: record[key], depth: current.depth + 1 }); + } + } + return true; +} +const nestedFixture = { + profile: 'default', + nodes: Object.fromEntries(Array.from({ length: 80 }, (_, index) => [`TWY_${index}`, (index & 1) === 0])), + blocks: Array.from({ length: 30 }, (_, index) => ({ id: index, route: [`A${index}`, `B${index}`] })), +}; +assert.equal(iterativeSafeValue(nestedFixture), recursiveSafeValue(nestedFixture)); +let excessivelyNested: unknown = true; +for (let depth = 0; depth < 30; depth++) excessivelyNested = [excessivelyNested]; +assert.equal(iterativeSafeValue(excessivelyNested), false); + +const disallowedKeys = new Set(['__proto__', 'constructor', 'prototype']); +const nullObject = (): Record => Object.create(null) as Record; +function mergeWithEntryClone(target: unknown, source: unknown, depth = 0): unknown { + if (depth > 20) throw new Error('depth'); + if (source === null || typeof source !== 'object') return source; + if (Array.isArray(source)) return [...source]; + const sourceKeys = Object.keys(source); + if (sourceKeys.length > 100) throw new Error('properties'); + const targetRecord = target !== null && typeof target === 'object' && !Array.isArray(target) ? (target as Record) : undefined; + let result = targetRecord ?? nullObject(); + let cloned = !targetRecord; + const ensureClone = () => { + if (cloned) return; + const clone = nullObject(); + for (const [key, value] of Object.entries(targetRecord!)) clone[key] = value; + result = clone; + cloned = true; + }; + for (const key of sourceKeys) { + if (disallowedKeys.has(key)) throw new Error('key'); + const sourceValue = (source as Record)[key]; + const targetValue = targetRecord?.[key]; + if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) { + const merged = mergeWithEntryClone(targetValue, sourceValue, depth + 1); + if (merged !== targetValue) { + ensureClone(); + result[key] = merged; + } + } else { + ensureClone(); + result[key] = sourceValue; + } + } + return result; +} +function mergeWithAssignClone(target: unknown, source: unknown, depth = 0): unknown { + if (depth > 20) throw new Error('depth'); + if (source === null || typeof source !== 'object') return source; + if (Array.isArray(source)) return [...source]; + const sourceKeys = Object.keys(source); + if (sourceKeys.length > 100) throw new Error('properties'); + const targetRecord = target !== null && typeof target === 'object' && !Array.isArray(target) ? (target as Record) : undefined; + let result = targetRecord ?? nullObject(); + let cloned = !targetRecord; + const ensureClone = () => { + if (cloned) return; + result = Object.assign(nullObject(), targetRecord); + cloned = true; + }; + for (const key of sourceKeys) { + if (key === '__proto__' || key === 'constructor' || key === 'prototype') throw new Error('key'); + const sourceValue = (source as Record)[key]; + const targetValue = targetRecord?.[key]; + if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) { + const merged = mergeWithAssignClone(targetValue, sourceValue, depth + 1); + if (merged !== targetValue) { + ensureClone(); + result[key] = merged; + } + } else if (sourceValue !== targetValue) { + ensureClone(); + result[key] = sourceValue; + } + } + return result; +} +const mergeTarget = { profile: 'default', nodes: Object.fromEntries(Array.from({ length: 80 }, (_, index) => [`N${index}`, false])), untouched: { value: 1 } }; +const mergePatch = { nodes: { N2: true, N17: true, N65: true }, sequence: ['A', 'B', 'C'] }; +assert.deepEqual(mergeWithAssignClone(mergeTarget, mergePatch), mergeWithEntryClone(mergeTarget, mergePatch)); + +const sharedPatch = nestedFixture; +const sharedPacket = { + type: 'SHARED_STATE_UPDATE', + airport: 'YSSY', + data: { sharedStatePatch: sharedPatch, controllerId: '1234567' }, + timestamp: 1_753_000_000_000, +}; +function serializeSharedTwice() { + const patchString = JSON.stringify(sharedPatch); + return patchString.length + JSON.stringify(sharedPacket).length; +} +function serializeSharedOnce() { + const patchString = JSON.stringify(sharedPatch); + const packetString = `{"type":"SHARED_STATE_UPDATE","airport":"YSSY","data":{"sharedStatePatch":${patchString},"controllerId":"1234567"},"timestamp":1753000000000}`; + return patchString.length + packetString.length; +} +assert.equal(serializeSharedOnce(), serializeSharedTwice()); + +const encodedPacket = new TextEncoder().encode(JSON.stringify(sharedPacket)); +const sharedDecoder = new TextDecoder(); +assert.equal(sharedDecoder.decode(encodedPacket), new TextDecoder().decode(encodedPacket)); +const heartbeatPacket = { type: 'HEARTBEAT' }; +const serializedHeartbeat = JSON.stringify(heartbeatPacket); +const connectRequest = new Request('https://api.stopbars.test/connect?airport=YSSY&key=BARS_test', { + headers: { Authorization: 'Bearer BARS_test', Upgrade: 'websocket' }, +}); +function cloneConnectRequest() { + const headers = new Headers(connectRequest.headers); + headers.set('Authorization', 'Bearer BARS_test'); + return new Request(connectRequest.url, { method: connectRequest.method, headers, body: connectRequest.body }); +} +assert.equal(cloneConnectRequest().url, connectRequest.url); + +const dueInfo = { statusCheckInFlight: false, lastStatusCheck: 1_753_000_000_000 }; +const dueNow = dueInfo.lastStatusCheck + 1_000; +async function statusDueAsync() { + if (dueInfo.statusCheckInFlight || dueNow - dueInfo.lastStatusCheck < 120_000) return false; + return true; +} +function statusDueSync() { + return !(dueInfo.statusCheckInFlight || dueNow - dueInfo.lastStatusCheck < 120_000); +} +assert.equal(await statusDueAsync(), statusDueSync()); + +const analyticsEvents = [ + { + event: 'ws_broadcast', + properties: { distinct_id: 'anonymous', product: 'Core', airport: 'YSSY', messageType: 'STATE_UPDATE', recipients: 40 }, + $process_person_profile: false, + }, + { + event: 'ws_message', + properties: { + distinct_id: 'anonymous', + product: 'Core', + airport: 'YSSY', + clientType: 'controller', + messageType: 'STATE_UPDATE', + objectId: 'SB1', + }, + $process_person_profile: false, + }, +] as const; +function serializeAnalyticsSeparately() { + return analyticsEvents.reduce( + (total, event) => total + JSON.stringify({ api_key: 'ph_test', ...event }).length, + 0, + ); +} +function serializeAnalyticsBatch() { + return JSON.stringify({ api_key: 'ph_test', batch: analyticsEvents }).length; +} +const separateAnalyticsPayloads = analyticsEvents.map((event) => JSON.parse(JSON.stringify({ api_key: 'ph_test', ...event }))); +const batchAnalyticsPayload = JSON.parse( + JSON.stringify({ api_key: 'ph_test', batch: analyticsEvents }), +) as { batch: typeof analyticsEvents }; +assert.deepEqual( + batchAnalyticsPayload.batch, + separateAnalyticsPayloads.map((payload) => ({ + event: payload.event, + properties: payload.properties, + $process_person_profile: payload.$process_person_profile, + })), +); + +console.table( + benchmark([ + { name: 'snapshot/scan all sockets', iterations: 10_000, run: snapshotByScan }, + { name: 'snapshot/maintained indexes', iterations: 10_000, run: snapshotByIndex }, + { name: 'broadcast/Map.forEach', iterations: 10_000, run: broadcastForEach }, + { name: 'broadcast/for-of', iterations: 10_000, run: broadcastForOf }, + { name: 'controller broadcast/scan all', iterations: 10_000, run: controllerBroadcastByScan }, + { name: 'controller broadcast/controller index', iterations: 10_000, run: controllerBroadcastByIndex }, + { + name: 'packet type/Set.has', + iterations: 1_000_000, + run: () => packetTypeSet.has(packetTypeSamples[setTypeIndex++ % packetTypeSamples.length]), + }, + { + name: 'packet type/object lookup', + iterations: 1_000_000, + run: () => packetTypeRecord[packetTypeSamples[recordTypeIndex++ % packetTypeSamples.length]] === true, + }, + { + name: 'packet type/switch', + iterations: 1_000_000, + run: () => packetTypeSwitch(packetTypeSamples[switchTypeIndex++ % packetTypeSamples.length]), + }, + { name: 'nested validation/recursive', iterations: 20_000, run: () => recursiveSafeValue(nestedFixture) }, + { name: 'nested validation/iterative', iterations: 20_000, run: () => iterativeSafeValue(nestedFixture) }, + { name: 'merge/entry clone + Set keys', iterations: 50_000, run: () => mergeWithEntryClone(mergeTarget, mergePatch) }, + { name: 'merge/assign clone + direct keys', iterations: 50_000, run: () => mergeWithAssignClone(mergeTarget, mergePatch) }, + { name: 'shared packet/stringify patch twice', iterations: 20_000, run: serializeSharedTwice }, + { name: 'shared packet/reuse patch JSON', iterations: 20_000, run: serializeSharedOnce }, + { name: 'binary decode/new decoder', iterations: 50_000, run: () => new TextDecoder().decode(encodedPacket) }, + { name: 'binary decode/shared decoder', iterations: 50_000, run: () => sharedDecoder.decode(encodedPacket) }, + { name: 'heartbeat/JSON.stringify', iterations: 1_000_000, run: () => JSON.stringify(heartbeatPacket) }, + { name: 'heartbeat/pre-serialized', iterations: 1_000_000, run: () => serializedHeartbeat }, + { name: 'connect/clone headers + request', iterations: 20_000, run: cloneConnectRequest }, + { name: 'connect/forward original request', iterations: 20_000, run: () => connectRequest }, + { name: 'status due/async early return', iterations: 100_000, run: statusDueAsync }, + { name: 'status due/synchronous guard', iterations: 100_000, run: statusDueSync }, + { name: 'analytics/two capture payloads', iterations: 100_000, run: serializeAnalyticsSeparately }, + { name: 'analytics/one batch payload', iterations: 100_000, run: serializeAnalyticsBatch }, + ]), +); + +console.log( + JSON.stringify({ + semanticEquality: true, + excessiveArrayDepthRejected: true, + handshakeDatabaseCalls: { current: 2, combinedPrincipal: 1 }, + statusChecksForDuplicateCid: { current: 'one per socket', coalesced: 'one in-flight request per CID' }, + analyticsRequestsPerBroadcastMessage: { separateCaptures: 2, batched: 1 }, + }), +); diff --git a/benchmarks/routes.ts b/benchmarks/routes.ts new file mode 100644 index 0000000..3669a32 --- /dev/null +++ b/benchmarks/routes.ts @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict'; +import { performance } from 'node:perf_hooks'; +import { Hono } from 'hono'; + +type Variant = { name: string; iterations: number; run: () => T | Promise }; + +async function benchmark(variants: Variant[]): Promise>> { + const rows: Array> = []; + for (const variant of variants) { + for (let index = 0; index < Math.min(2_000, variant.iterations); index++) await variant.run(); + const samples: number[] = []; + for (let sample = 0; sample < 11; sample++) { + const started = performance.now(); + for (let index = 0; index < variant.iterations; index++) await variant.run(); + samples.push(performance.now() - started); + } + samples.sort((a, b) => a - b); + const medianMs = samples[5]; + rows.push({ + variant: variant.name, + iterations: variant.iterations, + medianMs: Number(medianMs.toFixed(3)), + nsPerOperation: Number(((medianMs * 1_000_000) / variant.iterations).toFixed(1)), + }); + } + return rows; +} + +const request = new Request('https://api.stopbars.test/airports/YSSY/points?q=1'); +const pathname = '/airports/YSSY/points'; +assert.equal(new URL(request.url).pathname, pathname); + +const icaoRegex = /^[A-Z0-9]{4}$/; +assert.equal(Boolean('YSSY'.match(icaoRegex)), icaoRegex.test('YSSY')); + +const template = Array.from({ length: 4_000 }, (_, index) => ({ id: `BARS_${index}`, state: (index & 1) === 0 })); +const updates = Array.from({ length: 200 }, (_, index) => ({ objectId: `BARS_${index * 17}`, state: (index & 1) === 0 })); +const defaultStates = new Map(template.map((point) => [point.id, point.state])); +const pruneWithFind = () => + updates.filter((update) => template.find((point) => point.id === update.objectId)?.state === update.state).length; +const pruneWithMap = () => updates.filter((update) => defaultStates.get(update.objectId) === update.state).length; +assert.equal(pruneWithFind(), pruneWithMap()); + +const stateObjects = new Map( + template.map((point, index) => [ + point.id, + { id: point.id, state: point.state, controllerId: `controller-${index % 12}`, timestamp: 1_750_000_000_000 + index }, + ]), +); +type PersistedObject = { id: string; state: boolean; controllerId: string; timestamp: number }; +const persistWithIntermediates = () => + Object.fromEntries( + Array.from(stateObjects.entries()).map(([id, object]) => [ + id, + { id: object.id, state: object.state, controllerId: object.controllerId, timestamp: object.timestamp }, + ]), + ); +const persistDirectly = () => { + const result: Record = Object.create(null) as Record; + for (const [id, object] of stateObjects) { + result[id] = { + id: object.id, + state: object.state, + controllerId: object.controllerId, + timestamp: object.timestamp, + }; + } + return result; +}; +assert.equal(JSON.stringify(persistDirectly()), JSON.stringify(persistWithIntermediates())); + +const packet = { type: 'MULTI_STATE_UPDATE', airport: 'YSSY', data: { updates } }; +const typedState = { airport: 'YSSY', objects: updates, offline: false }; +const doFetchEnvelope = async () => { + const internalRequest = new Request('https://internal/state?airport=YSSY', { headers: { 'X-Request-Type': 'get_state' } }); + const airport = new URL(internalRequest.url).searchParams.get('airport'); + return Response.json({ ...typedState, airport }).json(); +}; +assert.deepEqual(await doFetchEnvelope(), typedState); + +const oneMiddlewareApp = new Hono(); +oneMiddlewareApp.use('*', async (_context, next) => next()); +oneMiddlewareApp.get('/health', (context) => context.json({ ok: true })); + +const threeMiddlewareApp = new Hono(); +for (let index = 0; index < 3; index++) threeMiddlewareApp.use('*', async (_context, next) => next()); +threeMiddlewareApp.get('/health', (context) => context.json({ ok: true })); + +const results = await benchmark([ + { name: 'path/new URL', iterations: 100_000, run: () => new URL(request.url).pathname }, + { name: 'path/Hono pre-parsed', iterations: 100_000, run: () => pathname }, + { name: 'ICAO/String.match', iterations: 100_000, run: () => 'YSSY'.match(icaoRegex) }, + { name: 'ICAO/RegExp.test', iterations: 100_000, run: () => icaoRegex.test('YSSY') }, + { name: 'defaults/Array.find x200', iterations: 2_000, run: pruneWithFind }, + { name: 'defaults/Map.get x200', iterations: 2_000, run: pruneWithMap }, + { name: 'packet/redundant stringify', iterations: 20_000, run: () => JSON.stringify(packet).length <= 50_000 }, + { name: 'packet/pre-checked raw length', iterations: 20_000, run: () => true }, + { name: 'persist/intermediate arrays', iterations: 1_000, run: persistWithIntermediates }, + { name: 'persist/direct assignment', iterations: 1_000, run: persistDirectly }, + { name: 'DO/fetch JSON envelope', iterations: 5_000, run: doFetchEnvelope }, + { name: 'DO/typed RPC result', iterations: 5_000, run: () => typedState }, + { + name: 'Hono/one async middleware', + iterations: 10_000, + run: async () => (await oneMiddlewareApp.request('https://bench.test/health')).body?.cancel(), + }, + { + name: 'Hono/three async middleware', + iterations: 10_000, + run: async () => (await threeMiddlewareApp.request('https://bench.test/health')).body?.cancel(), + }, +]); + +console.table(results); diff --git a/benchmarks/smoke.ts b/benchmarks/smoke.ts new file mode 100644 index 0000000..65a4935 --- /dev/null +++ b/benchmarks/smoke.ts @@ -0,0 +1,96 @@ +const baseUrl = (process.env.CORE_BASE_URL ?? 'http://127.0.0.1:8790').replace(/\/$/, ''); + +const assert = (condition: unknown, message: string): asserts condition => { + if (!condition) throw new Error(message); +}; + +const request = async (path: string, init?: RequestInit): Promise => fetch(`${baseUrl}${path}`, init); + +const percentile = (sorted: number[], fraction: number): number => + sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * fraction) - 1)] ?? 0; + +const measure = async (name: string, path: (iteration: number) => string, iterations = 20) => { + const samples: number[] = []; + for (let iteration = 0; iteration < iterations; iteration++) { + const startedAt = performance.now(); + const response = await request(path(iteration)); + await response.arrayBuffer(); + assert(response.ok, `${name} returned ${response.status}`); + samples.push(performance.now() - startedAt); + } + const sorted = samples.toSorted((left, right) => left - right); + return { + name, + meanMs: Number((samples.reduce((sum, sample) => sum + sample, 0) / samples.length).toFixed(3)), + p50Ms: Number(percentile(sorted, 0.5).toFixed(3)), + p95Ms: Number(percentile(sorted, 0.95).toFixed(3)), + p99Ms: Number(percentile(sorted, 0.99).toFixed(3)), + }; +}; + +const staticProbes: Array<[path: string, expectedStatus: number]> = [ + ['/favicon.ico', 200], + ['/stateid/info.json', 200], + ['/state?airport=YBEN', 200], + ['/faqs', 200], + ['/health?service=database', 200], + ['/docs', 302], +]; + +for (const [path, expectedStatus] of staticProbes) { + const response = await request(path, path === '/docs' ? { redirect: 'manual' } : undefined); + await response.arrayBuffer(); + assert(response.status === expectedStatus, `${path} returned ${response.status}; expected ${expectedStatus}`); +} + +const pointResponse = await request('/points?ids=P001,P002,P001,MISSING'); +const pointPayload = (await pointResponse.json()) as { + points: Array<{ id: string }>; + requested: number; + found: number; + notFound?: string[]; +}; +assert(pointResponse.ok, `/points returned ${pointResponse.status}`); +assert(pointPayload.requested === 4 && pointPayload.found === 3, 'Bulk point counts changed'); +assert(pointPayload.points.map((point) => point.id).join(',') === 'P001,P002,P001', 'Bulk point ordering changed'); +assert(pointPayload.notFound?.join(',') === 'MISSING', 'Bulk point missing-ID behavior changed'); + +const probeToken = Date.now(); +const latency = [ + await measure('points/100 IDs uncached', (iteration) => { + const ids = Array.from({ length: 100 }, (_, index) => `P${String(index + 1).padStart(3, '0')}`).join(','); + return `/points?ids=${ids}&probe=${probeToken}-${iteration}`; + }), + await measure('state/typed RPC uncached', (iteration) => `/state?airport=YBEN&probe=${probeToken}-${iteration}`), + await measure('state-id/cached', () => '/stateid/info.json'), +]; + +const downloadIp = `2001:db8::${probeToken.toString(16)}`; +const downloadInit = { method: 'POST', headers: { 'CF-Connecting-IP': downloadIp } } satisfies RequestInit; +const firstDownload = await request('/download?product=Installer', downloadInit); +const firstDownloadPayload = (await firstDownload.json()) as { versionCount: number }; +const secondDownload = await request('/download?product=Installer', downloadInit); +const secondDownloadPayload = (await secondDownload.json()) as { versionCount: number }; +assert(firstDownload.ok && secondDownload.ok, 'Download smoke request failed'); +assert(firstDownloadPayload.versionCount === secondDownloadPayload.versionCount, 'Duplicate download incremented the count'); + +const rateLimitIp = `2001:db8:1::${probeToken.toString(16)}`; +const rateLimitStatuses: number[] = []; +for (let requestNumber = 0; requestNumber < 31; requestNumber++) { + const response = await request('/connect', { headers: { 'CF-Connecting-IP': rateLimitIp } }); + rateLimitStatuses.push(response.status); + await response.arrayBuffer(); +} +assert(rateLimitStatuses.slice(0, 30).every((status) => status === 400), 'Rate limiter rejected a request too early'); +assert(rateLimitStatuses[30] === 429, 'Rate limiter did not reject request 31'); + +console.table(latency); +console.log( + JSON.stringify({ + baseUrl, + functionalProbes: staticProbes.length + 3, + bulkPointOrdering: true, + duplicateDownloadSuppression: true, + rateLimit: { allowed: 30, rejectedStatus: rateLimitStatuses[30] }, + }), +); diff --git a/bun.lock b/bun.lock index 2274fe9..7d34cd6 100644 --- a/bun.lock +++ b/bun.lock @@ -1,5 +1,6 @@ { "lockfileVersion": 1, + "configVersion": 0, "workspaces": { "": { "name": "bars-core", @@ -20,7 +21,7 @@ "ts-node": "^10.9.2", "typescript": "^5.9.3", "typescript-eslint": "^8.53.0", - "wrangler": "^4.59.2", + "wrangler": "^4.112.0", }, }, }, @@ -33,75 +34,75 @@ "@apidevtools/swagger-parser": ["@apidevtools/swagger-parser@10.0.3", "", { "dependencies": { "@apidevtools/json-schema-ref-parser": "^9.0.6", "@apidevtools/openapi-schemas": "^2.0.4", "@apidevtools/swagger-methods": "^3.0.2", "@jsdevtools/ono": "^7.1.3", "call-me-maybe": "^1.0.1", "z-schema": "^5.0.1" }, "peerDependencies": { "openapi-types": ">=7" } }, "sha512-sNiLY51vZOmSPFZA5TF35KZ2HbgYklQnTSDnkghamzLb3EkNtcQnrBQEj5AOCxHpTtXpqMCRM1CrmV2rG6nw4g=="], - "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.4.2", "", {}, "sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ=="], + "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.5.0", "", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="], - "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.10.0", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": "^1.20251221.0" }, "optionalPeers": ["workerd"] }, "sha512-/uII4vLQXhzCAZzEVeYAjFLBNg2nqTJ1JGzd2lRF6ItYe6U2zVoYGfeKpGx/EkBF6euiU+cyBXgMdtJih+nQ6g=="], + "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.1", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw=="], - "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260114.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-HNlsRkfNgardCig2P/5bp/dqDECsZ4+NU5XewqArWxMseqt3C5daSuptI620s4pn7Wr0ZKg7jVLH0PDEBkA+aA=="], + "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260714.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-ZWXqAN8G7Cx9hMRQuk+59ziJhR3j1F4iO+Qs8aHdfKZ3Dq5Yi/57xvkJTgCGBnW1YU/L78r8f6HEy51bwbTpNw=="], - "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260114.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-qyE1UdFnAlxzb+uCfN/d9c8icch7XRiH49/DjoqEa+bCDihTuRS7GL1RmhVIqHJhb3pX3DzxmKgQZBDBL83Inw=="], + "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260714.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-tueWxWC3wyCbMG6zRAxsMXX0YLgrRWbiAPYFQ2uJ7dUH8G+5E7UTWaQS9B1HdJ0bpKFW1NWxhs1o2noKVFSUYg=="], - "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260114.0", "", { "os": "linux", "cpu": "x64" }, "sha512-Z0BLvAj/JPOabzads2ddDEfgExWTlD22pnwsuNbPwZAGTSZeQa3Y47eGUWyHk+rSGngknk++S7zHTGbKuG7RRg=="], + "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260714.1", "", { "os": "linux", "cpu": "x64" }, "sha512-1VChTZRb0l0F7R4e1G5RtLKV4oFi6x+rQgxh2+yu887j3l/3TLgatuv1L8/5zhc9gKEhATTxOh0e52Rtd9dDWQ=="], - "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260114.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-kPUmEtUxUWlr9PQ64kuhdK0qyo8idPe5IIXUgi7xCD7mDd6EOe5J7ugDpbfvfbYKEjx4DpLvN2t45izyI/Sodw=="], + "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260714.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-rMm3G+NirG2UdgHIRDdF1asNC6FqgIzZzkRG+VDhhDGcVxAQwvrMT1E38BivEvHr3G04MB4AfhcOczX0+GtRkQ=="], - "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260114.0", "", { "os": "win32", "cpu": "x64" }, "sha512-MJnKgm6i1jZGyt2ZHQYCnRlpFTEZcK2rv9y7asS3KdVEXaDgGF8kOns5u6YL6/+eMogfZuHRjfDS+UqRTUYIFA=="], + "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260714.1", "", { "os": "win32", "cpu": "x64" }, "sha512-cGqnU3Hg2YZS/k3SAqrMp1DjpdsyFde72tWltdl6ZT9+SFz/Zrk/8gyTU1TcxC4YApXeNVH5TyU5cOGPgUJ0pg=="], "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="], "@emnapi/runtime": ["@emnapi/runtime@1.8.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg=="], - "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.0", "", { "os": "aix", "cpu": "ppc64" }, "sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A=="], + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.1", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ=="], - "@esbuild/android-arm": ["@esbuild/android-arm@0.27.0", "", { "os": "android", "cpu": "arm" }, "sha512-j67aezrPNYWJEOHUNLPj9maeJte7uSMM6gMoxfPC9hOg8N02JuQi/T7ewumf4tNvJadFkvLZMlAq73b9uwdMyQ=="], + "@esbuild/android-arm": ["@esbuild/android-arm@0.28.1", "", { "os": "android", "cpu": "arm" }, "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ=="], - "@esbuild/android-arm64": ["@esbuild/android-arm64@0.27.0", "", { "os": "android", "cpu": "arm64" }, "sha512-CC3vt4+1xZrs97/PKDkl0yN7w8edvU2vZvAFGD16n9F0Cvniy5qvzRXjfO1l94efczkkQE6g1x0i73Qf5uthOQ=="], + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.1", "", { "os": "android", "cpu": "arm64" }, "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg=="], - "@esbuild/android-x64": ["@esbuild/android-x64@0.27.0", "", { "os": "android", "cpu": "x64" }, "sha512-wurMkF1nmQajBO1+0CJmcN17U4BP6GqNSROP8t0X/Jiw2ltYGLHpEksp9MpoBqkrFR3kv2/te6Sha26k3+yZ9Q=="], + "@esbuild/android-x64": ["@esbuild/android-x64@0.28.1", "", { "os": "android", "cpu": "x64" }, "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng=="], - "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.27.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-uJOQKYCcHhg07DL7i8MzjvS2LaP7W7Pn/7uA0B5S1EnqAirJtbyw4yC5jQ5qcFjHK9l6o/MX9QisBg12kNkdHg=="], + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q=="], - "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.27.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-8mG6arH3yB/4ZXiEnXof5MK72dE6zM9cDvUcPtxhUZsDjESl9JipZYW60C3JGreKCEP+p8P/72r69m4AZGJd5g=="], + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ=="], - "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.27.0", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-9FHtyO988CwNMMOE3YIeci+UV+x5Zy8fI2qHNpsEtSF83YPBmE8UWmfYAQg6Ux7Gsmd4FejZqnEUZCMGaNQHQw=="], + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw=="], - "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.27.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-zCMeMXI4HS/tXvJz8vWGexpZj2YVtRAihHLk1imZj4efx1BQzN76YFeKqlDr3bUWI26wHwLWPd3rwh6pe4EV7g=="], + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ=="], - "@esbuild/linux-arm": ["@esbuild/linux-arm@0.27.0", "", { "os": "linux", "cpu": "arm" }, "sha512-t76XLQDpxgmq2cNXKTVEB7O7YMb42atj2Re2Haf45HkaUpjM2J0UuJZDuaGbPbamzZ7bawyGFUkodL+zcE+jvQ=="], + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.1", "", { "os": "linux", "cpu": "arm" }, "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ=="], - "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.27.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-AS18v0V+vZiLJyi/4LphvBE+OIX682Pu7ZYNsdUHyUKSoRwdnOsMf6FDekwoAFKej14WAkOef3zAORJgAtXnlQ=="], + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g=="], - "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.27.0", "", { "os": "linux", "cpu": "ia32" }, "sha512-Mz1jxqm/kfgKkc/KLHC5qIujMvnnarD9ra1cEcrs7qshTUSksPihGrWHVG5+osAIQ68577Zpww7SGapmzSt4Nw=="], + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.1", "", { "os": "linux", "cpu": "ia32" }, "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w=="], - "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.27.0", "", { "os": "linux", "cpu": "none" }, "sha512-QbEREjdJeIreIAbdG2hLU1yXm1uu+LTdzoq1KCo4G4pFOLlvIspBm36QrQOar9LFduavoWX2msNFAAAY9j4BDg=="], + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.1", "", { "os": "linux", "cpu": "none" }, "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg=="], - "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.27.0", "", { "os": "linux", "cpu": "none" }, "sha512-sJz3zRNe4tO2wxvDpH/HYJilb6+2YJxo/ZNbVdtFiKDufzWq4JmKAiHy9iGoLjAV7r/W32VgaHGkk35cUXlNOg=="], + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.1", "", { "os": "linux", "cpu": "none" }, "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ=="], - "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.27.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-z9N10FBD0DCS2dmSABDBb5TLAyF1/ydVb+N4pi88T45efQ/w4ohr/F/QYCkxDPnkhkp6AIpIcQKQ8F0ANoA2JA=="], + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ=="], - "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.27.0", "", { "os": "linux", "cpu": "none" }, "sha512-pQdyAIZ0BWIC5GyvVFn5awDiO14TkT/19FTmFcPdDec94KJ1uZcmFs21Fo8auMXzD4Tt+diXu1LW1gHus9fhFQ=="], + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.1", "", { "os": "linux", "cpu": "none" }, "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ=="], - "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.27.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-hPlRWR4eIDDEci953RI1BLZitgi5uqcsjKMxwYfmi4LcwyWo2IcRP+lThVnKjNtk90pLS8nKdroXYOqW+QQH+w=="], + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag=="], - "@esbuild/linux-x64": ["@esbuild/linux-x64@0.27.0", "", { "os": "linux", "cpu": "x64" }, "sha512-1hBWx4OUJE2cab++aVZ7pObD6s+DK4mPGpemtnAORBvb5l/g5xFGk0vc0PjSkrDs0XaXj9yyob3d14XqvnQ4gw=="], + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.1", "", { "os": "linux", "cpu": "x64" }, "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA=="], - "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.27.0", "", { "os": "none", "cpu": "arm64" }, "sha512-6m0sfQfxfQfy1qRuecMkJlf1cIzTOgyaeXaiVaaki8/v+WB+U4hc6ik15ZW6TAllRlg/WuQXxWj1jx6C+dfy3w=="], + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.1", "", { "os": "none", "cpu": "arm64" }, "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw=="], - "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.27.0", "", { "os": "none", "cpu": "x64" }, "sha512-xbbOdfn06FtcJ9d0ShxxvSn2iUsGd/lgPIO2V3VZIPDbEaIj1/3nBBe1AwuEZKXVXkMmpr6LUAgMkLD/4D2PPA=="], + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.1", "", { "os": "none", "cpu": "x64" }, "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg=="], - "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.27.0", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-fWgqR8uNbCQ/GGv0yhzttj6sU/9Z5/Sv/VGU3F5OuXK6J6SlriONKrQ7tNlwBrJZXRYk5jUhuWvF7GYzGguBZQ=="], + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.1", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q=="], - "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.27.0", "", { "os": "openbsd", "cpu": "x64" }, "sha512-aCwlRdSNMNxkGGqQajMUza6uXzR/U0dIl1QmLjPtRbLOx3Gy3otfFu/VjATy4yQzo9yFDGTxYDo1FfAD9oRD2A=="], + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.1", "", { "os": "openbsd", "cpu": "x64" }, "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw=="], - "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.27.0", "", { "os": "none", "cpu": "arm64" }, "sha512-nyvsBccxNAsNYz2jVFYwEGuRRomqZ149A39SHWk4hV0jWxKM0hjBPm3AmdxcbHiFLbBSwG6SbpIcUbXjgyECfA=="], + "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.1", "", { "os": "none", "cpu": "arm64" }, "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg=="], - "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.27.0", "", { "os": "sunos", "cpu": "x64" }, "sha512-Q1KY1iJafM+UX6CFEL+F4HRTgygmEW568YMqDA5UV97AuZSm21b7SXIrRJDwXWPzr8MGr75fUZPV67FdtMHlHA=="], + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.1", "", { "os": "sunos", "cpu": "x64" }, "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ=="], - "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.27.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-W1eyGNi6d+8kOmZIwi/EDjrL9nxQIQ0MiGqe/AWc6+IaHloxHSGoeRgDRKHFISThLmsewZ5nHFvGFWdBYlgKPg=="], + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA=="], - "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.27.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-30z1aKL9h22kQhilnYkORFYt+3wp7yZsHWus+wSKAJR8JtdfI76LJ4SBdMsCopTR3z/ORqVu5L1vtnHZWVj4cQ=="], + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg=="], - "@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.0", "", { "os": "win32", "cpu": "x64" }, "sha512-aIitBcjQeyOhMTImhLZmtxfdOcuNRpwlPNmlFKPcHQYPhEssw75Cl1TSXJXpMkzaua9FUetx/4OQKq7eJul5Cg=="], + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.1", "", { "os": "win32", "cpu": "x64" }, "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A=="], "@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.9.0", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g=="], @@ -285,7 +286,7 @@ "error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="], - "esbuild": ["esbuild@0.27.0", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.0", "@esbuild/android-arm": "0.27.0", "@esbuild/android-arm64": "0.27.0", "@esbuild/android-x64": "0.27.0", "@esbuild/darwin-arm64": "0.27.0", "@esbuild/darwin-x64": "0.27.0", "@esbuild/freebsd-arm64": "0.27.0", "@esbuild/freebsd-x64": "0.27.0", "@esbuild/linux-arm": "0.27.0", "@esbuild/linux-arm64": "0.27.0", "@esbuild/linux-ia32": "0.27.0", "@esbuild/linux-loong64": "0.27.0", "@esbuild/linux-mips64el": "0.27.0", "@esbuild/linux-ppc64": "0.27.0", "@esbuild/linux-riscv64": "0.27.0", "@esbuild/linux-s390x": "0.27.0", "@esbuild/linux-x64": "0.27.0", "@esbuild/netbsd-arm64": "0.27.0", "@esbuild/netbsd-x64": "0.27.0", "@esbuild/openbsd-arm64": "0.27.0", "@esbuild/openbsd-x64": "0.27.0", "@esbuild/openharmony-arm64": "0.27.0", "@esbuild/sunos-x64": "0.27.0", "@esbuild/win32-arm64": "0.27.0", "@esbuild/win32-ia32": "0.27.0", "@esbuild/win32-x64": "0.27.0" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA=="], + "esbuild": ["esbuild@0.28.1", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.1", "@esbuild/android-arm": "0.28.1", "@esbuild/android-arm64": "0.28.1", "@esbuild/android-x64": "0.28.1", "@esbuild/darwin-arm64": "0.28.1", "@esbuild/darwin-x64": "0.28.1", "@esbuild/freebsd-arm64": "0.28.1", "@esbuild/freebsd-x64": "0.28.1", "@esbuild/linux-arm": "0.28.1", "@esbuild/linux-arm64": "0.28.1", "@esbuild/linux-ia32": "0.28.1", "@esbuild/linux-loong64": "0.28.1", "@esbuild/linux-mips64el": "0.28.1", "@esbuild/linux-ppc64": "0.28.1", "@esbuild/linux-riscv64": "0.28.1", "@esbuild/linux-s390x": "0.28.1", "@esbuild/linux-x64": "0.28.1", "@esbuild/netbsd-arm64": "0.28.1", "@esbuild/netbsd-x64": "0.28.1", "@esbuild/openbsd-arm64": "0.28.1", "@esbuild/openbsd-x64": "0.28.1", "@esbuild/openharmony-arm64": "0.28.1", "@esbuild/sunos-x64": "0.28.1", "@esbuild/win32-arm64": "0.28.1", "@esbuild/win32-ia32": "0.28.1", "@esbuild/win32-x64": "0.28.1" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw=="], "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], @@ -381,7 +382,7 @@ "make-error": ["make-error@1.3.6", "", {}, "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw=="], - "miniflare": ["miniflare@4.20260114.0", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "^0.34.5", "undici": "7.14.0", "workerd": "1.20260114.0", "ws": "8.18.0", "youch": "4.1.0-beta.10", "zod": "^3.25.76" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-QwHT7S6XqGdQxIvql1uirH/7/i3zDEt0B/YBXTYzMfJtVCR4+ue3KPkU+Bl0zMxvpgkvjh9+eCHhJbKEqya70A=="], + "miniflare": ["miniflare@4.20260714.0", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.34.5", "undici": "7.28.0", "workerd": "1.20260714.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-MYlTCLdWCPqvrYY2uLwOjXwmglXuiHE3TGGkbOW4BwjUPa1r07E0iuHwrNDIs/sxK21r+o90Jx58AV2KeNdJZw=="], "minimatch": ["minimatch@3.1.2", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw=="], @@ -453,7 +454,7 @@ "typescript-eslint": ["typescript-eslint@8.53.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.53.0", "@typescript-eslint/parser": "8.53.0", "@typescript-eslint/typescript-estree": "8.53.0", "@typescript-eslint/utils": "8.53.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-xHURCQNxZ1dsWn0sdOaOfCSQG0HKeqSj9OexIxrz6ypU6wHYOdX2I3D2b8s8wFSsSOYJb+6q283cLiLlkEsBYw=="], - "undici": ["undici@7.14.0", "", {}, "sha512-Vqs8HTzjpQXZeXdpsfChQTlafcMQaaIwnGwLam1wudSSjlJeQ3bw1j+TLPePgrCnCpUXx7Ba5Pdpf5OBih62NQ=="], + "undici": ["undici@7.28.0", "", {}, "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA=="], "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="], @@ -469,13 +470,13 @@ "word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="], - "workerd": ["workerd@1.20260114.0", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260114.0", "@cloudflare/workerd-darwin-arm64": "1.20260114.0", "@cloudflare/workerd-linux-64": "1.20260114.0", "@cloudflare/workerd-linux-arm64": "1.20260114.0", "@cloudflare/workerd-windows-64": "1.20260114.0" }, "bin": { "workerd": "bin/workerd" } }, "sha512-kTJ+jNdIllOzWuVA3NRQRvywP0T135zdCjAE2dAUY1BFbxM6fmMZV8BbskEoQ4hAODVQUfZQmyGctcwvVCKxFA=="], + "workerd": ["workerd@1.20260714.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260714.1", "@cloudflare/workerd-darwin-arm64": "1.20260714.1", "@cloudflare/workerd-linux-64": "1.20260714.1", "@cloudflare/workerd-linux-arm64": "1.20260714.1", "@cloudflare/workerd-windows-64": "1.20260714.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-oIbQzfdyl9UQUnG6XLegcSq0Mgt/7WKDbFOoqGgOWCS+/fhyGB460uKEgdAQQ9RHCO/ttcNCX/KiMIQzdoeu3Q=="], - "wrangler": ["wrangler@4.59.2", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.2", "@cloudflare/unenv-preset": "2.10.0", "blake3-wasm": "2.1.5", "esbuild": "0.27.0", "miniflare": "4.20260114.0", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260114.0" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260114.0" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-Z4xn6jFZTaugcOKz42xvRAYKgkVUERHVbuCJ5+f+gK+R6k12L02unakPGOA0L0ejhUl16dqDjKe4tmL9sedHcw=="], + "wrangler": ["wrangler@4.112.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.5.0", "@cloudflare/unenv-preset": "2.16.1", "blake3-wasm": "2.1.5", "esbuild": "0.28.1", "miniflare": "4.20260714.0", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260714.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@cloudflare/workers-types": "^5.20260714.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "cf-wrangler": "bin/cf-wrangler.js", "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-5H+XUD0TySCv1LuktFHDIEOkboH2nTfQs+35L+USt3MtntjDTMVIJprLgQcL2WBjulOyjxpd1vyTiSTJVW5MjQ=="], "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], - "ws": ["ws@8.18.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="], + "ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], "yaml": ["yaml@2.0.0-1", "", {}, "sha512-W7h5dEhywMKenDJh2iX/LABkbFnBxasD27oyXWDS/feDsxiw0dD5ncXdYXgkvAsXIY2MpW/ZKkr9IU30DBdMNQ=="], @@ -489,8 +490,6 @@ "z-schema": ["z-schema@5.0.5", "", { "dependencies": { "lodash.get": "^4.4.2", "lodash.isequal": "^4.5.0", "validator": "^13.7.0" }, "optionalDependencies": { "commander": "^9.4.1" }, "bin": "bin/z-schema" }, "sha512-D7eujBWkLa3p2sIpJA0d1pr7es+a7m0vFAnZLlCEKq/Ij2k0MLi9Br2UPxoxdYystm5K1yeBGzub0FlYUEWj2Q=="], - "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], - "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], "@eslint/eslintrc/globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="], diff --git a/data/openapi.json b/data/openapi.json index 6cebf6a..4292baa 100644 --- a/data/openapi.json +++ b/data/openapi.json @@ -252,7 +252,7 @@ "get": { "summary": "Establish a WebSocket for an airport", "tags": ["RealTime"], - "description": "Performs a WebSocket upgrade to stream real-time airport state. Requires:\n- GET with `Upgrade: websocket`\n- `airport` (ICAO, 4 chars) and an API key via either:\n - `key` query parameter, or\n - `Authorization: Bearer ` header\nThe API key is forwarded as a Bearer token to the airport's Durable Object for auth.\n", + "description": "Performs a WebSocket upgrade to stream real-time airport state. Requires:\n- GET with `Upgrade: websocket`\n- `airport` (ICAO, 4 chars) and an API key via either:\n - `key` query parameter, or\n - `Authorization: Bearer ` header\nThe Durable Object validates the API key from the query parameter or Bearer header.\n", "x-mint": { "content": "## Establish a session\n1. Connect to `/connect` with `airport` and your API key.\n2. Wait for `INITIAL_STATE` (this confirms your role and current airport state).\n3. Keep the connection alive by sending `HEARTBEAT` regularly.\n\nThe server sends `HEARTBEAT` every 60 seconds and closes idle sessions after ~70 seconds without inbound client messages.\n\n## Packet envelope\nEvery packet uses this top-level shape:\n\n```json\n{\n \"type\": \"STATE_UPDATE\",\n \"airport\": \"YSSY\",\n \"data\": {},\n \"timestamp\": 1739400000000\n}\n```\n\n- `type` is required.\n- `airport` is optional on most client packets (server uses your connected airport if omitted).\n- `timestamp` is optional on client packets and server-populated on outbound packets.\n\n## Packet permissions by role\n| Packet type | Who can send | What happens |\n| --- | --- | --- |\n| `HEARTBEAT` | controller, pilot, observer | Server replies with `HEARTBEAT_ACK` |\n| `GET_STATE` | controller, pilot, observer | Server replies with `STATE_SNAPSHOT` |\n| `STATE_UPDATE` | controller only | Broadcast to same-airport clients (except sender) |\n| `MULTI_STATE_UPDATE` | controller only | Broadcast to same-airport clients (except sender) |\n| `SHARED_STATE_UPDATE` | controller only | Broadcast to same-airport clients (including sender) |\n| `STOPBAR_CROSSING` | pilot only | Broadcast to same-airport controllers |\n| `CLOSE` | controller, pilot, observer | Server closes the session gracefully |\n\n## Client packets you send\n### HEARTBEAT\n```json\n{ \"type\": \"HEARTBEAT\" }\n```\n\n### GET_STATE\n```json\n{ \"type\": \"GET_STATE\" }\n```\n\n### STATE_UPDATE (controller only)\n```json\n{\n \"type\": \"STATE_UPDATE\",\n \"data\": {\n \"objectId\": \"BARS_7K2QH\",\n \"state\": false\n }\n}\n```\n\n### MULTI_STATE_UPDATE (controller only)\n```json\n{\n \"type\": \"MULTI_STATE_UPDATE\",\n \"data\": {\n \"updates\": [\n { \"objectId\": \"BARS_7K2QH\", \"state\": false },\n { \"objectId\": \"BARS_8R1LP\", \"state\": true }\n ]\n }\n}\n```\n\n### SHARED_STATE_UPDATE (controller only)\n```json\n{\n \"type\": \"SHARED_STATE_UPDATE\",\n \"data\": {\n \"sharedStatePatch\": {\n \"profile\": \"default\",\n \"nodes\": {\n \"TWY_A1\": true,\n \"TWY_B2\": false,\n \"RWY_09L_HOLD\": true\n },\n \"blocks\": {\n \"BLOCK_A\": \"clear\",\n \"BLOCK_B\": \"relax\",\n \"BLOCK_C\": { \"route\": [\"TWY_A1\", \"TWY_B2\"] }\n }\n }\n }\n}\n```\n\n### STOPBAR_CROSSING (pilot only)\n```json\n{\n \"type\": \"STOPBAR_CROSSING\",\n \"data\": {\n \"objectId\": \"BARS_7K2QH\"\n }\n}\n```\n\n### CLOSE\n```json\n{ \"type\": \"CLOSE\" }\n```\n\n## Server packets you should handle\n- `INITIAL_STATE` immediately after connect\n- `HEARTBEAT` every 60 seconds\n- `HEARTBEAT_ACK` in response to client `HEARTBEAT`\n- `STATE_SNAPSHOT` in response to `GET_STATE`\n- `STATE_UPDATE` when a controller changes one object state\n- `MULTI_STATE_UPDATE` when a controller sends a batch state change\n- `CONTROLLER_CONNECT` / `CONTROLLER_DISCONNECT` for controller presence changes\n- `SHARED_STATE_UPDATE` when shared state changes\n- `STOPBAR_CROSSING` (controllers only) when a pilot crosses a stopbar\n- `ERROR` when validation/processing fails\n\n## Validation and limits (avoid malformed packets)\n- `objectId` must match `^[a-zA-Z0-9_-]+$`.\n- `STATE_UPDATE` must include `data.objectId` and one of `data.state` or `data.patch`.\n- `MULTI_STATE_UPDATE` must include `data.updates` (maximum `200` updates).\n- `SHARED_STATE_UPDATE` must include `data.sharedStatePatch` object (maximum `10,240` serialized characters).\n- Maximum packet size is `50,000` characters.\n- Unknown packet `type` values are rejected.\n" }, diff --git a/package.json b/package.json index bfd2243..29e380a 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,15 @@ "update-db": "wrangler d1 execute bars-db --remote --file schema.sql", "prettify": "prettier --write .", "build": "wrangler build", + "benchmark": "bun run benchmark:routes && bun run benchmark:database && bun run benchmark:compute && bun run benchmark:realtime && bun run benchmark:backend", + "benchmark:routes": "bun benchmarks/routes.ts", + "benchmark:database": "bun benchmarks/database.ts", + "benchmark:compute": "bun benchmarks/compute.ts", + "benchmark:realtime": "bun benchmarks/realtime.ts", + "benchmark:backend": "bun benchmarks/backend.ts", + "test:realtime": "bun benchmarks/realtime-behavior.ts", + "test:backend": "bun benchmarks/backend-behavior.ts", + "benchmark:smoke": "bun benchmarks/smoke.ts", "openapi": "node scripts/generate-openapi.mjs && prettier --write data/openapi.json", "lint": "eslint . --fix" }, @@ -24,7 +33,7 @@ "ts-node": "^10.9.2", "typescript": "^5.9.3", "typescript-eslint": "^8.53.0", - "wrangler": "^4.59.2" + "wrangler": "^4.112.0" }, "dependencies": { "geolib": "^3.3.4", diff --git a/schema.sql b/schema.sql index d714e58..7cbaad9 100644 --- a/schema.sql +++ b/schema.sql @@ -301,10 +301,6 @@ CREATE TABLE IF NOT EXISTS bans ( ); -CREATE INDEX IF NOT EXISTS idx_airports_continent ON airports ( - continent -); - CREATE INDEX IF NOT EXISTS idx_airports_continent_icao ON airports ( continent, icao @@ -324,18 +320,10 @@ CREATE INDEX IF NOT EXISTS idx_runways_idents ON runways ( he_ident ); -CREATE INDEX IF NOT EXISTS idx_vatsim_id ON users ( - vatsim_id -); - CREATE INDEX IF NOT EXISTS idx_api_key ON users ( api_key ); -CREATE INDEX IF NOT EXISTS idx_staff_user_id ON staff ( - user_id -); - CREATE INDEX IF NOT EXISTS idx_staff_role ON staff ( role ); @@ -344,14 +332,6 @@ CREATE INDEX IF NOT EXISTS idx_staff_created_at ON staff ( created_at DESC ); -CREATE INDEX IF NOT EXISTS idx_points_airport_id ON points ( - airport_id -); - -CREATE INDEX IF NOT EXISTS idx_points_type ON points ( - type -); - CREATE INDEX IF NOT EXISTS idx_active_objects_name ON active_objects ( name ); @@ -360,31 +340,15 @@ CREATE INDEX IF NOT EXISTS idx_active_objects_last_updated ON active_objects ( last_updated ); -CREATE INDEX IF NOT EXISTS idx_contributions_status ON contributions ( - status -); - -CREATE INDEX IF NOT EXISTS idx_contributions_user ON contributions ( - user_id -); - CREATE INDEX IF NOT EXISTS idx_contributions_user_submission_date ON contributions ( user_id, submission_date DESC ); -CREATE INDEX IF NOT EXISTS idx_contributions_airport ON contributions ( - airport_icao -); - CREATE INDEX IF NOT EXISTS idx_contributions_submission_date ON contributions ( submission_date ); -CREATE INDEX IF NOT EXISTS idx_contributions_decision_date ON contributions ( - decision_date -); - CREATE INDEX IF NOT EXISTS idx_contributions_status_submission_date ON contributions ( status, submission_date DESC @@ -400,6 +364,17 @@ CREATE INDEX IF NOT EXISTS idx_contributions_status_package ON contributions ( package_name ); +CREATE INDEX IF NOT EXISTS idx_contributions_package_simulator_status ON contributions ( + package_name COLLATE NOCASE, + simulator, + status +); + +CREATE INDEX IF NOT EXISTS idx_contributions_status_user ON contributions ( + status, + user_id +); + CREATE INDEX IF NOT EXISTS idx_contributions_airport_lowerpkg_status_decision ON contributions ( airport_icao, lower(package_name), @@ -420,22 +395,18 @@ CREATE INDEX IF NOT EXISTS idx_users_created_at ON users ( created_at DESC ); -CREATE INDEX IF NOT EXISTS idx_division_members_composite ON division_members ( - division_id, - vatsim_id -); - CREATE INDEX IF NOT EXISTS idx_division_members_vatsim ON division_members ( vatsim_id ); -CREATE INDEX IF NOT EXISTS idx_division_airports_composite ON division_airports ( - division_id, +CREATE INDEX IF NOT EXISTS idx_division_airports_icao ON division_airports ( icao ); -CREATE INDEX IF NOT EXISTS idx_division_airports_icao ON division_airports ( - icao +CREATE INDEX IF NOT EXISTS idx_division_airports_icao_status_division ON division_airports ( + icao, + status, + division_id ); CREATE INDEX IF NOT EXISTS idx_points_airport_type ON points ( @@ -447,12 +418,14 @@ CREATE INDEX IF NOT EXISTS idx_points_linked_to ON points ( linked_to ); -CREATE INDEX IF NOT EXISTS idx_faqs_order ON faqs ( - order_position ASC +CREATE INDEX IF NOT EXISTS idx_points_type_linked_to ON points ( + type, + linked_to ); -CREATE INDEX IF NOT EXISTS idx_installer_releases_product ON installer_releases ( - product +CREATE INDEX IF NOT EXISTS idx_faqs_order_created ON faqs ( + order_position ASC, + created_at ASC ); CREATE INDEX IF NOT EXISTS idx_installer_releases_created_at ON installer_releases ( @@ -481,43 +454,41 @@ CREATE INDEX IF NOT EXISTS idx_contribution_generations_expires_at ON contributi expires_at ); -CREATE INDEX IF NOT EXISTS idx_downloads_product ON downloads ( - product -); - -CREATE INDEX IF NOT EXISTS idx_downloads_product_version ON downloads ( - product, - version -); - CREATE INDEX IF NOT EXISTS idx_downloads_product_created_at ON downloads ( product, created_at DESC ); -CREATE INDEX IF NOT EXISTS idx_download_ip_hits_product_version ON download_ip_hits ( - product, - version -); - CREATE INDEX IF NOT EXISTS idx_download_ip_hits_last_seen ON download_ip_hits ( last_seen ); -CREATE INDEX IF NOT EXISTS idx_download_ip_hits_cleanup ON download_ip_hits ( - last_seen, - product, - version -); - -CREATE INDEX IF NOT EXISTS idx_bans_vatsim_id ON bans ( - vatsim_id -); - CREATE INDEX IF NOT EXISTS idx_bans_expires_at ON bans ( expires_at ); CREATE INDEX IF NOT EXISTS idx_bans_created_at ON bans ( created_at DESC -); \ No newline at end of file +); + +-- Retire indexes now covered by UNIQUE constraints or better composite indexes. +DROP INDEX IF EXISTS idx_airports_continent; +DROP INDEX IF EXISTS idx_vatsim_id; +DROP INDEX IF EXISTS idx_staff_user_id; +DROP INDEX IF EXISTS idx_points_airport_id; +DROP INDEX IF EXISTS idx_points_type; +DROP INDEX IF EXISTS idx_contributions_status; +DROP INDEX IF EXISTS idx_contributions_user; +DROP INDEX IF EXISTS idx_contributions_airport; +DROP INDEX IF EXISTS idx_contributions_decision_date; +DROP INDEX IF EXISTS idx_division_members_composite; +DROP INDEX IF EXISTS idx_division_airports_composite; +DROP INDEX IF EXISTS idx_faqs_order; +DROP INDEX IF EXISTS idx_installer_releases_product; +DROP INDEX IF EXISTS idx_downloads_product; +DROP INDEX IF EXISTS idx_downloads_product_version; +DROP INDEX IF EXISTS idx_download_ip_hits_product_version; +DROP INDEX IF EXISTS idx_download_ip_hits_cleanup; +DROP INDEX IF EXISTS idx_bans_vatsim_id; + +PRAGMA optimize; diff --git a/src/index.ts b/src/index.ts index 96d4ffc..3e11de3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,12 +1,13 @@ import type { Context } from 'hono'; import { Hono } from 'hono'; import { cors } from 'hono/cors'; +import { DurableObject } from 'cloudflare:workers'; import { Connection } from './network/connection'; import { AuthService } from './services/auth'; import { CacheKeys, withCache } from './services/cache'; import { DatabaseContextFactory } from './services/database-context'; import { HttpError } from './services/errors'; -import { cancelResponseBody } from './services/http'; +import { cancelResponseBody, getClientIp } from './services/http'; import { getLightsByObject, type RadarLight } from './services/lights-cache'; import { rateLimit } from './services/rate-limit'; import { InstallerProduct } from './services/releases'; @@ -19,6 +20,37 @@ import { MAX_CONTRIBUTION_XML_BYTES, sanitizeContributionXml } from './services/ import { AirportObject, PointChangeset, PointData, UserRecord, VatsimUser } from './types'; export { RateLimiter } from './services/rate-limit'; const POINT_ID_REGEX = /^[A-Z0-9-_]+$/; +const ICAO_REGEX = /^[A-Z0-9]{4}$/; +const FAVICON_BYTES = Uint8Array.from( + atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMB/axhLZ4AAAAASUVORK5CYII='), + (character) => character.charCodeAt(0), +); +const INSTALLER_PRODUCTS: readonly InstallerProduct[] = [ + 'Pilot-Client', + 'vatSys-Plugin', + 'EuroScope-Plugin', + 'Installer', + 'SimConnect.NET', +]; +const CACHE_NAMESPACES = ['airports', 'points', 'divisions', 'auth', 'state', 'health', 'installer', 'github', 'faq'] as const; +const STATE_ID_INFO = [ + { type: 'Uni-Directional', code: 0, direction2: 'OFF', direction1: 'OFF' }, + { type: 'Uni-Directional', code: 1, direction2: 'OFF', direction1: 'Red' }, + { type: 'Uni-Directional', code: 2, direction2: 'OFF', direction1: 'Green' }, + { type: 'Uni-Directional', code: 3, direction2: 'OFF', direction1: 'Yellow' }, + { type: 'Uni-Directional', code: 4, direction2: 'OFF', direction1: 'Blue' }, + { type: 'Uni-Directional', code: 5, direction2: 'OFF', direction1: 'Orange' }, + { type: 'Uni-Directional', code: 6, direction2: 'OFF', direction1: 'Red' }, + { type: 'Uni-Directional', code: 7, direction2: 'OFF', direction1: 'OFF' }, + { type: 'Bi-Directional', code: 20, direction2: 'Red', direction1: 'Red' }, + { type: 'Bi-Directional', code: 21, direction2: 'Green', direction1: 'Green' }, + { type: 'Bi-Directional', code: 22, direction2: 'Yellow', direction1: 'Yellow' }, + { type: 'Bi-Directional', code: 23, direction2: 'Blue', direction1: 'Blue' }, + { type: 'Bi-Directional', code: 24, direction2: 'Orange', direction1: 'Orange' }, + { type: 'Bi-Directional', code: 25, direction2: 'Green', direction1: 'Yellow' }, + { type: 'Bi-Directional', code: 26, direction2: 'Green', direction1: 'Blue' }, + { type: 'Bi-Directional', code: 27, direction2: 'Green', direction1: 'Orange' }, +] as const; const getHighResTime = typeof performance !== 'undefined' && typeof performance.now === 'function' ? () => performance.now() : () => Date.now(); @@ -91,7 +123,7 @@ const buildOfflineTemplate = async (env: Env, airport: string): Promise => { const normalizedAirport = airport.toUpperCase(); - if (!/^[A-Z0-9]{4}$/.test(normalizedAirport)) { + if (!ICAO_REGEX.test(normalizedAirport)) { return null; } const cacheService = ServicePool.getCache(env); @@ -201,10 +233,11 @@ type VatsimConnectionStatus = { secondary_positions: Array<{ latitude: number; longitude: number }>; }; -export class BARS { +export class BARS extends DurableObject { private connection: Connection; constructor(state: DurableObjectState, env: Env) { + super(state, env); const vatsim = new VatsimService(env.VATSIM_CLIENT_ID, env.VATSIM_CLIENT_SECRET); const auth = new AuthService(env.DB, vatsim); this.connection = new Connection(env, auth, vatsim, state); @@ -213,6 +246,10 @@ export class BARS { async fetch(request: Request) { return this.connection.fetch(request); } + + async getState(airport: string, forceOffline = false) { + return this.connection.getState(airport, forceOffline); + } } const app = new Hono<{ @@ -323,8 +360,7 @@ app.use('*', async (c, next) => { const start = Date.now(); await next(); try { - const url = new URL(c.req.url); - const path = url.pathname; + const path = c.req.path; if (c.req.method === 'OPTIONS') return; if (path === '/favicon.ico') return; if (path.includes('/health')) return; @@ -370,9 +406,7 @@ app.use( ); app.get('/favicon.ico', () => { - const base64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMB/axhLZ4AAAAASUVORK5CYII='; // 1x1 transparent PNG - const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); - return new Response(bytes, { + return new Response(FAVICON_BYTES, { headers: { 'Content-Type': 'image/png', 'Cache-Control': 'public, max-age=604800, immutable', @@ -380,25 +414,6 @@ app.get('/favicon.ico', () => { }); }); -// Extract client IP (best-effort) and attach to context -app.use('*', async (c, next) => { - const cf = c.req.header('CF-Connecting-IP'); - const real = c.req.header('X-Real-IP'); - const fwdFor = c.req.header('X-Forwarded-For'); - const forwarded = c.req.header('Forwarded'); - let ip: string | undefined = cf || real; - if (!ip && fwdFor) { - ip = fwdFor.split(',')[0].trim(); - } - if (!ip && forwarded) { - // Forwarded: for=1.2.3.4; proto=http; by=... - const match = forwarded.match(/for=([^;]+)/i); - if (match) ip = match[1].replace(/"/g, ''); - } - c.set('clientIp', ip || '0.0.0.0'); - await next(); -}); - async function resolveUserFromVatsimOrApi( c: Context<{ Bindings: Env; Variables: { vatsimUser?: VatsimUser; user?: UserRecord } }>, ): Promise<{ user: UserRecord | null; vatsimUser?: VatsimUser }> { @@ -476,7 +491,7 @@ app.post('/contact', async (c) => { const email = typeof b.email === 'string' ? b.email.trim() : ''; const topic = typeof b.topic === 'string' ? b.topic.trim() : ''; const message = typeof b.message === 'string' ? b.message.trim() : ''; - const ip = c.get('clientIp') || '0.0.0.0'; + const ip = getClientIp(c.req.raw); const emailRegex = /^[^@\s]+@[^@\s]+\.[^@\s]+$/; if (!email || !emailRegex.test(email)) { @@ -614,9 +629,8 @@ app.patch('/contact/:id/status', async (c) => { const allowed = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); if (!allowed) return dbContext.textResponse('Forbidden', { status: 403 }); const contact = ServicePool.getContact(c.env); - const existing = await contact.getMessage(id); - if (!existing) return dbContext.textResponse('Not found', { status: 404 }); const updated = await contact.updateStatus(id, status, user.vatsim_id); + if (!updated) return dbContext.textResponse('Not found', { status: 404 }); return dbContext.jsonResponse({ message: updated }); } finally { dbContext.close(); @@ -666,9 +680,7 @@ app.delete('/contact/:id', async (c) => { const allowed = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); if (!allowed) return dbContext.textResponse('Forbidden', { status: 403 }); const contact = ServicePool.getContact(c.env); - const existing = await contact.getMessage(id); - if (!existing) return dbContext.textResponse('Not found', { status: 404 }); - await contact.deleteMessage(id); + if (!(await contact.deleteMessage(id))) return dbContext.textResponse('Not found', { status: 404 }); return dbContext.textResponse('', { status: 204 }); } finally { dbContext.close(); @@ -688,7 +700,7 @@ app.delete('/contact/:id', async (c) => { * - `airport` (ICAO, 4 chars) and an API key via either: * - `key` query parameter, or * - `Authorization: Bearer ` header - * The API key is forwarded as a Bearer token to the airport's Durable Object for auth. + * The Durable Object validates the API key from the query parameter or Bearer header. * x-mint: * content: | * ## Establish a session @@ -873,22 +885,11 @@ app.get('/connect', rateLimit({ maxRequests: 30 }), async (c) => { return c.text('Unauthorized', 401); } - if (airportId === 'ZZZZ' || !/^[A-Z0-9]{4}$/.test(airportId)) { + if (airportId === 'ZZZZ' || !ICAO_REGEX.test(airportId)) { return c.text('Unauthorized', 401); } - const newHeaders = new Headers(c.req.raw.headers); - newHeaders.set('Authorization', `Bearer ${apiKey}`); - - const modifiedRequest = new Request(c.req.raw.url, { - method: c.req.raw.method, - headers: newHeaders, - body: c.req.raw.body, - }); - - const id = c.env.BARS.idFromName(airportId); - const obj = c.env.BARS.get(id); - return obj.fetch(modifiedRequest); + return c.env.BARS.getByName(airportId).fetch(c.req.raw); }); // State endpoint @@ -959,7 +960,7 @@ app.get('/state', withCache(CacheKeys.fromUrl, 1, 'state'), async (c) => { const metadata = parseActiveObjectName(obj.name); const airportIcaoRaw = metadata?.airport ?? obj.name.split('/')[0] ?? ''; const airportIcao = airportIcaoRaw.toUpperCase(); - if (!/^[A-Z0-9]{4}$/.test(airportIcao)) { + if (!ICAO_REGEX.test(airportIcao)) { return null as null; } @@ -987,18 +988,9 @@ app.get('/state', withCache(CacheKeys.fromUrl, 1, 'state'), async (c) => { } } - const id = c.env.BARS.idFromString(obj.id); - const durableObj = c.env.BARS.get(id); - - const stateRequest = new Request(`https://internal/state?airport=${airportIcao}`, { - method: 'GET', - headers: new Headers({ - 'X-Request-Type': 'get_state', - }), - }); + const durableObj = c.env.BARS.get(c.env.BARS.idFromString(obj.id)); try { - const response = await durableObj.fetch(stateRequest); type DOState = { airport: string; controllers: string[]; @@ -1006,7 +998,7 @@ app.get('/state', withCache(CacheKeys.fromUrl, 1, 'state'), async (c) => { objects: DOObject[]; offline?: boolean; }; - const state = (await response.json()) as DOState; + const state = (await durableObj.getState(airportIcao)) as DOState; // Determine online/offline status consistently const controllerCount = Array.isArray(state.controllers) ? state.controllers.length : 0; @@ -1021,13 +1013,13 @@ app.get('/state', withCache(CacheKeys.fromUrl, 1, 'state'), async (c) => { const objects = Array.isArray(state.objects) ? state.objects - .filter((o: DOObject) => allowedIds.has(o.id)) - .map((o: DOObject) => ({ - id: o.id, - state: o.state, - timestamp: o.timestamp, - lights: (lightsByObject as Record)[o.id] || [], - })) + .filter((o: DOObject) => allowedIds.has(o.id)) + .map((o: DOObject) => ({ + id: o.id, + state: o.state, + timestamp: o.timestamp, + lights: (lightsByObject as Record)[o.id] || [], + })) : []; return { @@ -1083,9 +1075,6 @@ app.get('/state', withCache(CacheKeys.fromUrl, 1, 'state'), async (c) => { } } - const id = c.env.BARS.idFromName(airport); - const obj = c.env.BARS.get(id); - if (airport.length !== 4) { return c.json( { @@ -1095,62 +1084,7 @@ app.get('/state', withCache(CacheKeys.fromUrl, 1, 'state'), async (c) => { ); } - const stateUrl = new URL('https://internal/state'); - stateUrl.searchParams.set('airport', airport); - if (offlineRequested) { - stateUrl.searchParams.set('offline', 'true'); - } - const stateRequest = new Request(stateUrl.toString(), { - method: 'GET', - headers: new Headers({ - 'X-Request-Type': 'get_state', - }), - }); - - if (!isVatsimRadar) { - return obj.fetch(stateRequest); - } - - // Transform response for VATSIM Radar variant (filter to XML objects and attach lights) - try { - const resp = await obj.fetch(stateRequest); - type DOObject = { id: string; state: unknown; timestamp: number }; - const state = (await resp.json()) as { - airport: string; - controllers: string[]; - pilots: string[]; - objects: DOObject[]; - offline?: boolean; - }; - const lightsByObject = await getLightsByObject(c.env, state.airport); - const allowedIds = new Set(Object.keys(lightsByObject)); - const objects = Array.isArray(state.objects) - ? state.objects - .filter((o: DOObject) => allowedIds.has(o.id)) - .map((o: DOObject) => ({ - id: o.id, - state: o.state, - timestamp: o.timestamp, - lights: (lightsByObject as Record)[o.id] || [], - })) - : []; - return c.json({ - states: [ - { - airport: state.airport, - controllers: state.controllers, - pilots: state.pilots, - objects, - connections: { - controllers: Array.isArray(state.controllers) ? state.controllers.length : 0, - pilots: Array.isArray(state.pilots) ? state.pilots.length : 0, - }, - }, - ], - }); - } catch { - return c.json({ error: 'Failed to fetch state' }, 500); - } + return c.json(await c.env.BARS.getByName(airport).getState(airport, offlineRequested)); }); // VATSIM auth callback @@ -1763,14 +1697,14 @@ app.get( .split(',') .map((code) => sanitizeIcao(code.trim())) .filter(Boolean); - if (icaos.length === 0 || icaos.some((code) => !/^[A-Z0-9]{4}$/.test(code))) { + if (icaos.length === 0 || icaos.some((code) => !ICAO_REGEX.test(code))) { return c.text('Invalid ICAO format', 400); } data = await airports.getAirports(icaos); } else { // Single airport request const cleanIcao = sanitizeIcao(icao); - if (!/^[A-Z0-9]{4}$/.test(cleanIcao)) { + if (!ICAO_REGEX.test(cleanIcao)) { return c.text('Invalid ICAO format', 400); } data = await airports.getAirport(cleanIcao); @@ -1811,7 +1745,7 @@ app.get( */ app.get('/airports/:icao/contribution-policy', async (c) => { const icao = c.req.param('icao').toUpperCase(); - if (!icao.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(icao)) { return c.text('Invalid airport ICAO format', 400); } @@ -2075,10 +2009,7 @@ divisionsApp.delete('/:id', async (c) => { const allowed = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); if (!allowed) return c.text('Forbidden', 403); - const existing = await divisions.getDivision(id); - if (!existing) return c.text('Division not found', 404); - - await divisions.deleteDivision(id); + if (!(await divisions.deleteDivision(id))) return c.text('Division not found', 404); return c.body(null, 204); }); @@ -2229,11 +2160,10 @@ divisionsApp.post('/:id/members', async (c) => { // Product managers and lead developers can manage any division. const user = await auth.getUserByVatsimId(vatsimUser.id); - const isLeadDev = user ? await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER) : false; - const isPM = user ? await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER) : false; + const isStaffManager = user ? await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER) : false; const userRole = await divisions.getMemberRole(divisionId, vatsimUser.id); - if (userRole !== 'nav_head' && !isLeadDev && !isPM) { + if (userRole !== 'nav_head' && !isStaffManager) { return c.text('Forbidden', 403); } @@ -2287,21 +2217,20 @@ divisionsApp.delete('/:id/members/:vatsimId', async (c) => { // Product managers and lead developers can manage any division. const user = await auth.getUserByVatsimId(vatsimUser.id); - const isLeadDev = user ? await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER) : false; - const isPM = user ? await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER) : false; + const isStaffManager = user ? await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER) : false; const userRole = await divisions.getMemberRole(divisionId, vatsimUser.id); - if (userRole !== 'nav_head' && !isLeadDev && !isPM) { + if (userRole !== 'nav_head' && !isStaffManager) { return c.text('Forbidden', 403); } // Prevent removing yourself (unless you're a lead dev removing yourself from a division you're not heading) - if (targetVatsimId === vatsimUser.id.toString() && !isLeadDev && !isPM) { + if (targetVatsimId === vatsimUser.id.toString() && !isStaffManager) { return c.text('Cannot remove yourself from the division', 400); } const targetRole = await divisions.getMemberRole(divisionId, targetVatsimId); - if (targetRole === 'nav_head' && !isLeadDev && !isPM) { + if (targetRole === 'nav_head' && !isStaffManager) { return c.text('Cannot remove another nav head', 403); } @@ -2613,7 +2542,7 @@ app.get('/airports/:icao/points', async (c) => { const airportId = c.req.param('icao'); // Validate ICAO format (exactly 4 uppercase letters/numbers) - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } @@ -2655,7 +2584,7 @@ app.post('/airports/:icao/points', async (c) => { const airportId = c.req.param('icao'); // Validate ICAO format (exactly 4 uppercase letters/numbers) - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } @@ -2706,7 +2635,7 @@ app.post('/airports/:icao/points/batch', async (c) => { const airportId = c.req.param('icao'); // Validate ICAO format (exactly 4 uppercase letters/numbers) - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } @@ -2757,12 +2686,12 @@ app.put('/airports/:icao/points/:id', async (c) => { const pointId = c.req.param('id'); // Validate ICAO format (exactly 4 uppercase letters/numbers) - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } // Validate point ID format (alphanumeric, dash, underscore) - if (!pointId.match(POINT_ID_REGEX)) { + if (!POINT_ID_REGEX.test(pointId)) { return c.text('Invalid point ID format', 400); } @@ -2807,12 +2736,12 @@ app.delete('/airports/:icao/points/:id', async (c) => { const pointId = c.req.param('id'); // Validate ICAO format (exactly 4 uppercase letters/numbers) - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } // Validate point ID format (alphanumeric, dash, underscore) - if (!pointId.match(POINT_ID_REGEX)) { + if (!POINT_ID_REGEX.test(pointId)) { return c.text('Invalid point ID format', 400); } @@ -2881,11 +2810,11 @@ app.post('/airports/:icao/points/:stopbarId/link', async (c) => { const airportId = c.req.param('icao'); const stopbarId = c.req.param('stopbarId'); - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } - if (!stopbarId.match(POINT_ID_REGEX)) { + if (!POINT_ID_REGEX.test(stopbarId)) { return c.text('Invalid stopbar ID format', 400); } @@ -2895,7 +2824,7 @@ app.post('/airports/:icao/points/:stopbarId/link', async (c) => { } const body = await c.req.json<{ leadOnId: string }>(); - if (!body.leadOnId || !body.leadOnId.match(POINT_ID_REGEX)) { + if (!body.leadOnId || !POINT_ID_REGEX.test(body.leadOnId)) { return c.text('Invalid or missing leadOnId', 400); } @@ -2951,11 +2880,11 @@ app.delete('/airports/:icao/points/:stopbarId/link/:leadOnId', async (c) => { const stopbarId = c.req.param('stopbarId'); const leadOnId = c.req.param('leadOnId'); - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } - if (!stopbarId.match(POINT_ID_REGEX) || !leadOnId.match(POINT_ID_REGEX)) { + if (!POINT_ID_REGEX.test(stopbarId) || !POINT_ID_REGEX.test(leadOnId)) { return c.text('Invalid point ID format', 400); } @@ -3002,11 +2931,11 @@ app.get('/airports/:icao/points/:stopbarId/links', async (c) => { const airportId = c.req.param('icao'); const stopbarId = c.req.param('stopbarId'); - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } - if (!stopbarId.match(POINT_ID_REGEX)) { + if (!POINT_ID_REGEX.test(stopbarId)) { return c.text('Invalid stopbar ID format', 400); } @@ -3035,7 +2964,7 @@ app.get('/airports/:icao/points/:stopbarId/links', async (c) => { app.get('/airports/:icao/links', async (c) => { const airportId = c.req.param('icao'); - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } @@ -3120,7 +3049,7 @@ app.get('/airports/:icao/links', async (c) => { app.post('/airports/:icao/links/bulk', async (c) => { const airportId = c.req.param('icao'); - if (!airportId.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(airportId)) { return c.text('Invalid airport ICAO format', 400); } @@ -3144,7 +3073,7 @@ app.post('/airports/:icao/links/bulk', async (c) => { if (!entry.leadOnId || !entry.stopbarId) { return c.json({ error: 'Each link entry must have leadOnId and stopbarId' }, 400); } - if (!entry.leadOnId.match(POINT_ID_REGEX) || !entry.stopbarId.match(POINT_ID_REGEX)) { + if (!POINT_ID_REGEX.test(entry.leadOnId) || !POINT_ID_REGEX.test(entry.stopbarId)) { return c.json({ error: 'Invalid point ID format in link entry' }, 400); } } @@ -3154,7 +3083,7 @@ app.post('/airports/:icao/links/bulk', async (c) => { if (!entry.leadOnId || !entry.stopbarId) { return c.json({ error: 'Each unlink entry must have leadOnId and stopbarId' }, 400); } - if (!entry.leadOnId.match(POINT_ID_REGEX) || !entry.stopbarId.match(POINT_ID_REGEX)) { + if (!POINT_ID_REGEX.test(entry.leadOnId) || !POINT_ID_REGEX.test(entry.stopbarId)) { return c.json({ error: 'Invalid point ID format in unlink entry' }, 400); } } @@ -3195,7 +3124,7 @@ app.get('/points/:id', withCache(CacheKeys.fromUrl, 3600, 'points'), async (c) = const pointId = c.req.param('id'); // Validate point ID format (alphanumeric, dash, underscore) - if (!pointId.match(POINT_ID_REGEX)) { + if (!POINT_ID_REGEX.test(pointId)) { return c.text('Invalid point ID format', 400); } @@ -3267,7 +3196,7 @@ app.get('/points', withCache(CacheKeys.fromUrl, 3600, 'points'), async (c) => { ); } - const invalidIds = pointIds.filter((id) => !id.match(POINT_ID_REGEX)); + const invalidIds = pointIds.filter((id) => !POINT_ID_REGEX.test(id)); if (invalidIds.length > 0) { return c.json( { @@ -3280,14 +3209,13 @@ app.get('/points', withCache(CacheKeys.fromUrl, 3600, 'points'), async (c) => { const points = ServicePool.getPoints(c.env); - // Fetch all points in parallel - const pointPromises = pointIds.map((id) => points.getPoint(id)); - const pointResults = await Promise.all(pointPromises); + // Preserve input order and missing entries while collapsing up to 100 D1 reads into one query. + const pointResults = await points.getPoints(pointIds); // Filter out null results and create response const foundPoints = pointResults.filter((point) => point !== null); - const foundIds = foundPoints.map((point) => point!.id); - const notFoundIds = pointIds.filter((id) => !foundIds.includes(id)); + const foundIds = new Set(foundPoints.map((point) => point!.id)); + const notFoundIds = pointIds.filter((id) => !foundIds.has(id)); return c.json({ points: foundPoints, @@ -3320,7 +3248,8 @@ const getStoredContributionGenerationResponse = async (c: Context): Promise `supports-gen:${token}`; -const getContributionGenerationExpiresAt = (): string => new Date(Date.now() + CONTRIBUTION_GENERATION_CACHE_TTL_SECONDS * 1000).toISOString(); +const getContributionGenerationExpiresAt = (): string => + new Date(Date.now() + CONTRIBUTION_GENERATION_CACHE_TTL_SECONDS * 1000).toISOString(); const getContributionGenerationTtlSeconds = (expiresAt?: string): number => { if (!expiresAt) { @@ -3599,26 +3528,7 @@ app.get( * description: Mapping returned */ app.get('/stateid/info.json', withCache(CacheKeys.fromUrl, 31536000, 'data'), (c) => { - const states = [ - { type: 'Uni-Directional', code: 0, direction2: 'OFF', direction1: 'OFF' }, - { type: 'Uni-Directional', code: 1, direction2: 'OFF', direction1: 'Red' }, - { type: 'Uni-Directional', code: 2, direction2: 'OFF', direction1: 'Green' }, - { type: 'Uni-Directional', code: 3, direction2: 'OFF', direction1: 'Yellow' }, - { type: 'Uni-Directional', code: 4, direction2: 'OFF', direction1: 'Blue' }, - { type: 'Uni-Directional', code: 5, direction2: 'OFF', direction1: 'Orange' }, - { type: 'Uni-Directional', code: 6, direction2: 'OFF', direction1: 'Red' }, - { type: 'Uni-Directional', code: 7, direction2: 'OFF', direction1: 'OFF' }, - { type: 'Bi-Directional', code: 20, direction2: 'Red', direction1: 'Red' }, - { type: 'Bi-Directional', code: 21, direction2: 'Green', direction1: 'Green' }, - { type: 'Bi-Directional', code: 22, direction2: 'Yellow', direction1: 'Yellow' }, - { type: 'Bi-Directional', code: 23, direction2: 'Blue', direction1: 'Blue' }, - { type: 'Bi-Directional', code: 24, direction2: 'Orange', direction1: 'Orange' }, - { type: 'Bi-Directional', code: 25, direction2: 'Green', direction1: 'Yellow' }, - { type: 'Bi-Directional', code: 26, direction2: 'Green', direction1: 'Blue' }, - { type: 'Bi-Directional', code: 27, direction2: 'Green', direction1: 'Orange' }, - ]; - - return c.json({ states }); + return c.json({ states: STATE_ID_INFO }); }); /** @@ -4470,19 +4380,13 @@ contributionsApp.post('/:id/regenerate', async (c) => { const vatsim = ServicePool.getVatsim(c.env); const auth = ServicePool.getAuth(c.env); - const roles = ServicePool.getRoles(c.env); const vatsimUser = await vatsim.getUser(vatsimToken); const user = await auth.getUserByVatsimId(vatsimUser.id); if (!user) return c.text('User not found', 404); - const isPM = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); - if (!isPM) return c.text('Forbidden', 403); - const id = c.req.param('id'); const contributions = ServicePool.getContributions(c.env); - const existing = await contributions.getContribution(id); - if (!existing) return c.text('Not found', 404); try { const res = await contributions.regenerateContribution(id, user.vatsim_id); @@ -4493,15 +4397,16 @@ contributionsApp.post('/:id/regenerate', async (c) => { return c.json({ success: true, id, - airport: existing.airportIcao, - packageName: existing.packageName, + airport: res.airportIcao, + packageName: res.packageName, maps: { key: res.maps.key, etag: res.maps.etag, url: fileUrl(res.maps.key) }, supports: { key: res.supports.key, etag: res.supports.etag, url: fileUrl(res.supports.key) }, }); } catch (e) { const msg = e instanceof Error ? e.message : 'Failed to regenerate'; - const status = msg.includes('authorized') ? 403 : msg.includes('not found') ? 404 : 400; - return c.json({ error: msg }, status); + if (msg.includes('authorized')) return c.text('Forbidden', 403); + if (msg.includes('not found')) return c.text('Not found', 404); + return c.json({ error: msg }, 400); } }); @@ -4545,11 +4450,6 @@ contributionsApp.delete('/:id', rateLimit({ maxRequests: 1 }), async (c) => { } const id = c.req.param('id'); - const existing = await contributions.getContribution(id); - if (!existing) { - return c.text('Not found', 404); - } - try { const success = await contributions.deleteContribution(id, user.vatsim_id); if (!success) return c.text('Not found', 404); @@ -4601,7 +4501,7 @@ app.get('/maps/:icao/packages/:package/latest', withCache(CacheKeys.fromUrl, 900 const contributions = ServicePool.getContributions(c.env); const storage = ServicePool.getStorage(c.env); - const latest = await contributions.getLatestApprovedContributionForAirportPackage(icao, pkg, simulatorParam); + const latest = await contributions.getLatestApprovedMapDescriptor(icao, pkg, simulatorParam); if (!latest) { return c.text('No approved map found', 404); } @@ -4637,9 +4537,9 @@ app.get('/maps/:icao/packages/:package/latest', withCache(CacheKeys.fromUrl, 900 * 404: * description: Not found */ -cdnApp.get('/files/*', async (c) => { +cdnApp.get('/files/:fileKey{.+}', async (c) => { // Extract the file key from the URL - everything after /cdn/files/ - const fileKey = c.req.param('*'); + const fileKey = c.req.param('fileKey'); if (!fileKey) { return c.text('File not found', 404); @@ -4648,7 +4548,7 @@ cdnApp.get('/files/*', async (c) => { const storage = ServicePool.getStorage(c.env); // Bypass rate limiting for file downloads to ensure fast CDN performance - const fileResponse = await storage.getFile(fileKey); + const fileResponse = await storage.getFile(fileKey, c.req.raw.headers); if (!fileResponse) { return c.text('File not found', 404); @@ -4731,12 +4631,9 @@ cdnApp.post('/upload', async (c) => { const fileName = customKey || file.name; const fileKey = path ? `${path}/${fileName}` : fileName; - // Extract file data - const fileData = await file.arrayBuffer(); - - // Upload file to storage + // Stream directly to R2 instead of duplicating the entire upload in memory. const storage = ServicePool.getStorage(c.env); - const result = await storage.uploadFile(fileKey, fileData, file.type, { + const result = await storage.uploadFile(fileKey, file.stream(), file.type, { uploadedBy: user.vatsim_id, fileName: file.name, size: file.size.toString(), @@ -4858,7 +4755,7 @@ cdnApp.get('/files', async (c) => { * 200: * description: Deletion result */ -cdnApp.delete('/files/*', async (c) => { +cdnApp.delete('/files/:fileKey{.+}', async (c) => { // Require authentication for file deletion const vatsimToken = c.req.header('X-Vatsim-Token'); if (!vatsimToken) { @@ -4883,7 +4780,7 @@ cdnApp.delete('/files/*', async (c) => { } try { - const fileKey = c.req.param('*'); + const fileKey = c.req.param('fileKey'); if (!fileKey) { return c.json( @@ -4945,7 +4842,7 @@ app.get('/euroscope/files/:icao', async (c) => { const icao = c.req.param('icao').toUpperCase(); // Validate ICAO format - if (!icao.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(icao)) { return c.json( { error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', @@ -5054,7 +4951,7 @@ euroscopeApp.post('/upload', async (c) => { } // Validate ICAO format (exactly 4 uppercase letters/numbers) - if (!icao.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(icao)) { return c.json( { error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', @@ -5106,11 +5003,8 @@ euroscopeApp.post('/upload', async (c) => { ); } - // Extract file data - const fileData = await file.arrayBuffer(); - - // Upload file to storage with metadata - const result = await storage.uploadFile(fileKey, fileData, file.type, { + // Stream directly to R2 instead of duplicating the entire upload in memory. + const result = await storage.uploadFile(fileKey, file.stream(), file.type, { uploadedBy: vatsimUser.id.toString(), icao: icao, fileName: file.name, @@ -5172,7 +5066,7 @@ euroscopeApp.delete('/files/:icao/:filename', async (c) => { const vatsimUser = c.get('vatsimUser')!; // Validate ICAO format - if (!icao.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(icao)) { return c.json( { error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', @@ -5251,7 +5145,7 @@ euroscopeApp.get('/:icao/editable', async (c) => { const vatsimUser = c.get('vatsimUser')!; // Validate ICAO format - if (!icao.match(/^[A-Z0-9]{4}$/)) { + if (!ICAO_REGEX.test(icao)) { return c.json( { error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', @@ -5263,12 +5157,11 @@ euroscopeApp.get('/:icao/editable', async (c) => { try { // Check if user has access to edit files for this ICAO const divisions = ServicePool.getDivisions(c.env); - const hasAccess = await divisions.userHasAirportAccess(vatsimUser.id.toString(), icao); const userRole = await divisions.getUserRoleForAirport(vatsimUser.id.toString(), icao); return c.json({ icao: icao, - editable: hasAccess, + editable: userRole !== null, role: userRole, }); } catch (error) { @@ -5748,10 +5641,8 @@ app.put('/releases/:id/changelog', async (c) => { const vatsimUser = await vatsim.getUser(vatsimToken); const user = await auth.getUserByVatsimId(vatsimUser.id); if (!user) return c.text('User not found', 404); - // Allow Lead Developer or Product Manager - const canEdit = - (await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER)) || - (await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER)); + // Product Manager permission also includes Lead Developers via the role hierarchy. + const canEdit = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); if (!canEdit) return c.text('Forbidden', 403); let body: unknown; @@ -5765,17 +5656,6 @@ app.put('/releases/:id/changelog', async (c) => { if (!changelog) return c.json({ error: 'changelog required' }, 400); if (changelog.length > 20000) return c.json({ error: 'changelog too long (max 20000 chars)' }, 400); - // Ensure release exists first (so we differentiate 404 vs silent update) - // Reusing listReleases would be inefficient; perform direct lookup. - const dbContext = DatabaseContextFactory.createRequestContext(c.env.DB, c.req.raw); - try { - const existing = await dbContext.db.executeRead<{ id: number }>('SELECT id FROM installer_releases WHERE id = ?', [id]); - if (!existing.results[0]) return dbContext.textResponse('Release not found', { status: 404 }); - } finally { - // close early; release update uses its own session service - // (ReleaseService internally manages its session.) - } - const updated = await releasesService.updateChangelog(id, changelog); if (!updated) return c.text('Release not found', 404); return c.json({ success: true, release: updated }); @@ -5813,17 +5693,15 @@ app.put('/releases/:id/changelog', async (c) => { app.post('/download', async (c) => { const product = c.req.query('product') as InstallerProduct | undefined; if (!product) return c.json({ error: 'product required' }, 400); - const VALID: InstallerProduct[] = ['Pilot-Client', 'vatSys-Plugin', 'EuroScope-Plugin', 'Installer', 'SimConnect.NET']; - if (!VALID.includes(product)) return c.json({ error: 'invalid product' }, 400); + if (!INSTALLER_PRODUCTS.includes(product)) return c.json({ error: 'invalid product' }, 400); const releases = ServicePool.getReleases(c.env); const latest = await releases.getLatest(product); if (!latest) return c.json({ error: 'No release found for product' }, 404); const version = latest.version; - const ip = c.get('clientIp') || '0.0.0.0'; + const ip = getClientIp(c.req.raw); const downloads = ServicePool.getDownloads(c.env); - const { versionCount, productTotal } = await downloads.recordDownload(product, version, ip); - const stats = await downloads.getStats(product); - return c.json({ product, version, versionCount, productTotal, versions: stats.versions }); + const { versionCount, productTotal, versions } = await downloads.recordDownload(product, version, ip); + return c.json({ product, version, versionCount, productTotal, versions }); }); /** @@ -6031,8 +5909,7 @@ app.get('/downloads/stats', withCache(CacheKeys.fromUrl, 300, 'installer'), asyn const combinedTotal = all.reduce((sum, item) => sum + item.total, 0); return c.json({ products: all, combinedTotal }); } - const VALID: InstallerProduct[] = ['Pilot-Client', 'vatSys-Plugin', 'EuroScope-Plugin', 'Installer', 'SimConnect.NET']; - if (!VALID.includes(product)) return c.json({ error: 'invalid product' }, 400); + if (!INSTALLER_PRODUCTS.includes(product)) return c.json({ error: 'invalid product' }, 400); const stats = await downloads.getStats(product); return c.json(stats); }); @@ -6166,12 +6043,9 @@ app.post('/purge-cache-all', async (c) => { const maybe = body as Record; if (typeof maybe.namespace === 'string') namespace = maybe.namespace; } - const allNamespaces = ['airports', 'points', 'divisions', 'auth', 'state', 'health', 'installer', 'github', 'faq']; - const toPurge = namespace ? [namespace] : allNamespaces; - const results: Record = {}; - for (const ns of toPurge) { - results[ns] = await cache.bumpNamespaceVersion(ns); - } + const toPurge: readonly string[] = namespace ? [namespace] : CACHE_NAMESPACES; + const versions = await Promise.all(toPurge.map((cacheNamespace) => cache.bumpNamespaceVersion(cacheNamespace))); + const results = Object.fromEntries(toPurge.map((cacheNamespace, index) => [cacheNamespace, versions[index]])); return c.json({ success: true, bumped: results }); } catch (e) { return c.json({ error: e instanceof Error ? e.message : 'Failed to purge namespaces' }, 500); @@ -6572,7 +6446,9 @@ export default { }, async scheduled(_controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise { ctx.waitUntil( - Promise.all([cleanupStaleActiveObjects(env), ServicePool.getContributions(env).cleanupExpiredGenerations()]).then(() => undefined), + Promise.all([cleanupStaleActiveObjects(env), ServicePool.getContributions(env).cleanupExpiredGenerations()]).then( + () => undefined, + ), ); }, }; diff --git a/src/network/connection.ts b/src/network/connection.ts index 116276d..6911e47 100644 --- a/src/network/connection.ts +++ b/src/network/connection.ts @@ -1,12 +1,4 @@ -import { - ClientType, - Packet, - AirportState, - AirportObject, - MultiStateUpdateItem, - HEARTBEAT_INTERVAL, - HEARTBEAT_TIMEOUT, -} from '../types'; +import { ClientType, Packet, AirportState, AirportObject, MultiStateUpdateItem, HEARTBEAT_INTERVAL, HEARTBEAT_TIMEOUT } from '../types'; import { AuthService } from '../services/auth'; import { VatsimService } from '../services/vatsim'; import { PointsService } from '../services/points'; @@ -16,17 +8,37 @@ import { DatabaseContextFactory } from '../services/database-context'; import { PostHogService } from '../services/posthog'; const MAX_STATE_SIZE = 1000000; // 1MB limit for persisted payloads +const MAX_MESSAGE_SIZE = 50000; +const MAX_SHARED_PATCH_SIZE = 10240; const MAX_MULTI_STATE_UPDATES = 200; const OBJECT_ID_REGEX = /^[a-zA-Z0-9_-]+$/; -const DISALLOWED_KEYS = new Set(['__proto__', 'constructor', 'prototype']); const STATE_FLUSH_DEBOUNCE_MS = 1500; -const ACTIVE_OBJECT_TOUCH_INTERVAL_MS = 5000; +const ACTIVE_OBJECT_TOUCH_INTERVAL_MS = 60_000; const SOCKET_STATUS_CHECK_INTERVAL_MS = 120000; const MAX_CONSECUTIVE_STATUS_FAILURES = 2; const OFFLINE_STATE_CACHE_TTL_MS = 300000; const SEND_FAILURE_LIMIT = 3; const EFFECTIVE_HEARTBEAT_TIMEOUT = Math.max(HEARTBEAT_TIMEOUT, HEARTBEAT_INTERVAL * 3); +const STALE_STATE_TIMEOUT_MS = 120_000; +const PACKET_DECODER = new TextDecoder(); +const SERIALIZED_HEARTBEAT = JSON.stringify({ type: 'HEARTBEAT' }); +const VALID_PACKET_TYPES = new Set([ + 'HEARTBEAT', + 'HEARTBEAT_ACK', + 'STATE_UPDATE', + 'MULTI_STATE_UPDATE', + 'CLOSE', + 'SHARED_STATE_UPDATE', + 'INITIAL_STATE', + 'CONTROLLER_CONNECT', + 'CONTROLLER_DISCONNECT', + 'ERROR', + 'GET_STATE', + 'STATE_SNAPSHOT', + 'STOPBAR_CROSSING', +]); const createNullObject = (): Record => Object.create(null) as Record; +const isDisallowedKey = (key: string): boolean => key === '__proto__' || key === 'constructor' || key === 'prototype'; type SocketInfo = { controllerId: string; @@ -41,6 +53,38 @@ type SocketInfo = { type OfflineStateTemplate = Array<{ id: string; state: boolean }>; +type ConnectionStatus = { + banned: boolean; + status: { cid: string; callsign: string; type: string } | null; +}; + +export type ConnectionStateSnapshot = { + airport: string; + controllers?: string[]; + pilots?: string[]; + objects: AirportObject[]; + offline: boolean; +}; + +function isSafeNestedValue(value: unknown, maxDepth = 20, maxProperties = 100): boolean { + const seen = new WeakSet(); + const walk = (current: unknown, depth: number): boolean => { + if (current === null || typeof current !== 'object') return true; + if (depth > maxDepth || seen.has(current)) return false; + seen.add(current); + if (Array.isArray(current)) { + return current.length <= 1000 && current.every((item) => walk(item, depth + 1)); + } + const record = current as Record; + const keys = Object.keys(record); + return ( + keys.length <= maxProperties && + keys.every((key) => key.length <= 100 && !isDisallowedKey(key) && walk(record[key], depth + 1)) + ); + }; + return walk(value, 0); +} + function describeErrorForLog(error: unknown): Record | string { if (error instanceof Error) { return { @@ -133,13 +177,7 @@ function recursivelyMergeObjects(target: unknown, source: unknown, depth = 0): u const ensureClone = () => { if (!cloned) { - if (targetRecord) { - const clone = createNullObject(); - for (const [k, v] of Object.entries(targetRecord)) { - clone[k] = v; - } - result = clone; - } + if (targetRecord) result = Object.assign(createNullObject(), targetRecord); cloned = true; } }; @@ -149,7 +187,7 @@ function recursivelyMergeObjects(target: unknown, source: unknown, depth = 0): u throw new Error('Invalid property key'); } - if (DISALLOWED_KEYS.has(key)) { + if (isDisallowedKey(key)) { throw new Error('Prototype pollution key rejected'); } @@ -167,7 +205,7 @@ function recursivelyMergeObjects(target: unknown, source: unknown, depth = 0): u ensureClone(); result[key] = recursivelyMergeObjects(createNullObject(), sv, depth + 1); } - } else { + } else if (sv !== rv) { ensureClone(); result[key] = sv; } @@ -181,7 +219,6 @@ export class Connection { private airportStates = new Map(); private airportSharedStates = new Map>(); // New shared state storage - private readonly TWO_MINUTES = 120000; // Add constant at class level private objectId: string; // Store the DO's ID private lastActiveObjectsUpdate = 0; // Throttle D1 updates private activeObjectTouchInFlight = false; @@ -191,10 +228,13 @@ export class Connection { private dirtySharedStates = new Set(); private socketQueues = new Map>(); private controllerSockets = new Map>>(); + private pilotConnectionCounts = new Map>(); + private pendingConnectionStatusChecks = new Map>(); private offlineStateCache = new Map< string, { template?: OfflineStateTemplate; + defaultStates?: ReadonlyMap; expiresAt: number; inFlight?: Promise; } @@ -220,10 +260,7 @@ export class Connection { }); } - private registerSocket( - socket: WebSocket, - info: { controllerId: string; type: ClientType; airport: string; lastHeartbeat: number }, - ) { + private registerSocket(socket: WebSocket, info: { controllerId: string; type: ClientType; airport: string; lastHeartbeat: number }) { const socketInfo: SocketInfo = { ...info, lastStatusCheck: 0, @@ -236,6 +273,8 @@ export class Connection { this.lastKnownAirport = socketInfo.airport; if (socketInfo.type === 'controller') { this.addControllerSocket(socket, socketInfo); + } else if (socketInfo.type === 'pilot') { + this.adjustPilotConnectionCount(socketInfo.airport, socketInfo.controllerId, 1); } } @@ -250,6 +289,8 @@ export class Connection { this.socketQueues.delete(socket); if (info.type === 'controller') { this.removeControllerSocket(socket, info); + } else if (info.type === 'pilot') { + this.adjustPilotConnectionCount(info.airport, info.controllerId, -1); } if (this.sockets.size === 0) { this.lastKnownAirport = 'unknown'; @@ -317,7 +358,7 @@ export class Connection { const sockets = this.controllerSockets.get(airport)?.get(controllerId); if (!sockets) return false; for (const socket of sockets) { - if (socket !== currentSocket && this.sockets.has(socket)) { + if (socket !== currentSocket) { return true; } } @@ -325,42 +366,60 @@ export class Connection { } private hasLiveControllers(airport: string): boolean { - const airportControllers = this.controllerSockets.get(airport); - if (!airportControllers) return false; - for (const sockets of airportControllers.values()) { - for (const socket of sockets) { - if (this.sockets.has(socket)) { - return true; - } - } - } - return false; + return (this.controllerSockets.get(airport)?.size ?? 0) > 0; } private getLiveControllerIds(airport: string): string[] { const airportControllers = this.controllerSockets.get(airport); - if (!airportControllers) return []; - const controllerIds: string[] = []; - for (const [controllerId, sockets] of airportControllers) { - for (const socket of sockets) { - if (this.sockets.has(socket)) { - controllerIds.push(controllerId); - break; - } - } + return airportControllers ? Array.from(airportControllers.keys()) : []; + } + + private adjustPilotConnectionCount(airport: string, pilotId: string, delta: number) { + let airportPilots = this.pilotConnectionCounts.get(airport); + if (!airportPilots) { + if (delta <= 0) return; + airportPilots = new Map(); + this.pilotConnectionCounts.set(airport, airportPilots); } - return controllerIds; + + const nextCount = (airportPilots.get(pilotId) ?? 0) + delta; + if (nextCount > 0) airportPilots.set(pilotId, nextCount); + else airportPilots.delete(pilotId); + if (airportPilots.size === 0) this.pilotConnectionCounts.delete(airport); + } + + private getLivePilotIds(airport: string): string[] { + const airportPilots = this.pilotConnectionCounts.get(airport); + return airportPilots ? Array.from(airportPilots.keys()) : []; } private emitAnalytics(event: string, properties: Record) { + const filtered = this.filterAnalyticsProperties(properties); + try { + this.posthog.track(event, filtered); + } catch { + // ignore analytics failures + } + } + + private filterAnalyticsProperties(properties: Record): Record { const filtered: Record = {}; for (const [key, value] of Object.entries(properties)) { if (value !== undefined) { filtered[key] = value; } } + return filtered; + } + + private emitAnalyticsBatch(events: readonly { event: string; properties: Record }[]) { try { - this.posthog.track(event, filtered); + this.posthog.trackBatch( + events.map((item) => ({ + event: item.event, + properties: this.filterAnalyticsProperties(item.properties), + })), + ); } catch { // ignore analytics failures } @@ -446,19 +505,19 @@ export class Connection { return; } + const objects: Record = createNullObject() as Record; + for (const [id, object] of state.objects) { + objects[id] = { + id: object.id, + state: object.state, + controllerId: object.controllerId, + timestamp: object.timestamp, + }; + } + const serialized = { airport: state.airport, - objects: Object.fromEntries( - Array.from(state.objects.entries()).map(([id, obj]) => [ - id, - { - id: obj.id, - state: obj.state, - controllerId: obj.controllerId, - timestamp: obj.timestamp, - }, - ]), - ), + objects, lastUpdate: state.lastUpdate, controllers: Array.from(state.controllers), }; @@ -498,12 +557,12 @@ export class Connection { private markAirportStateDirty(airport: string, immediate = false) { this.dirtyAirportStates.add(airport); if (immediate) { - void this.flushAirportState(airport); + this.state.waitUntil(this.flushAirportState(airport)); return; } if (this.airportStateFlushTimers.has(airport)) return; const timer = setTimeout(() => { - void this.flushAirportState(airport); + this.state.waitUntil(this.flushAirportState(airport)); }, STATE_FLUSH_DEBOUNCE_MS); this.airportStateFlushTimers.set(airport, timer); } @@ -511,12 +570,12 @@ export class Connection { private markSharedStateDirty(airport: string, immediate = false) { this.dirtySharedStates.add(airport); if (immediate) { - void this.flushSharedState(airport); + this.state.waitUntil(this.flushSharedState(airport)); return; } if (this.airportSharedStateFlushTimers.has(airport)) return; const timer = setTimeout(() => { - void this.flushSharedState(airport); + this.state.waitUntil(this.flushSharedState(airport)); }, STATE_FLUSH_DEBOUNCE_MS); this.airportSharedStateFlushTimers.set(airport, timer); } @@ -560,11 +619,11 @@ export class Connection { return connectionAirport; } - private async broadcast(packet: Packet, sender?: WebSocket) { + private broadcast(packet: Packet, sender?: WebSocket, trackAnalytics = true): number { const airport = packet.airport; if (!airport) { console.warn('Attempted to broadcast packet without airport identifier'); - return; + return 0; } let packetString: string; @@ -572,19 +631,20 @@ export class Connection { packetString = JSON.stringify(packet); } catch (error) { console.error('Failed to serialize packet for broadcast:', error); - return; + return 0; } let recipients = 0; - this.sockets.forEach((client, socket) => { + for (const [socket, client] of this.sockets) { if (socket !== sender && socket.readyState === WebSocket.OPEN && client.airport === airport) { recipients++; this.sendSerializedPacket(socket, packetString, 'broadcast'); } - }); + } - this.trackBroadcast(packet.type, airport, recipients); + if (trackAnalytics) this.trackBroadcast(packet.type, airport, recipients); + return recipients; } private getOrCreateAirportState(airport: string): AirportState { @@ -641,7 +701,7 @@ export class Connection { if (patch === undefined) { throw new Error(`Missing patch data for object ${objectId}`); } - if (patch !== null && typeof patch !== 'object') { + if (patch !== null && (typeof patch !== 'object' || Array.isArray(patch))) { throw new Error(`Patch data must be an object or null for object ${objectId}`); } @@ -651,19 +711,12 @@ export class Connection { return { objectId, patch: null }; } - const baseState = - typeof existingObject.state === 'object' && existingObject.state !== null ? existingObject.state : {}; + const baseState = typeof existingObject.state === 'object' && existingObject.state !== null ? existingObject.state : {}; const merged = recursivelyMergeObjects(baseState, patch as Record); newState = merged as Record; normalized = { objectId, patch: patch as Record | null }; } else { const stateValue = (update as { state?: unknown }).state; - try { - JSON.stringify(stateValue); - } catch { - throw new Error(`State data is not serializable for object ${objectId}`); - } - if (typeof stateValue === 'boolean') { newState = stateValue; } else if (stateValue && typeof stateValue === 'object' && !Array.isArray(stateValue)) { @@ -697,10 +750,11 @@ export class Connection { throw new Error('Invalid airport identifier'); } + const defaultStates = await this.getOfflineDefaultStates(airport); const now = Date.now(); const state = this.getOrCreateAirportState(airport); const normalized = this.applyStateUpdateToAirport(state, packet.data as Record, controllerId, now); - await this.pruneDefaultStateOverride(airport, state, normalized.objectId); + this.pruneDefaultStateOverride(state, normalized.objectId, defaultStates); this.markAirportStateDirty(airport); return now; @@ -731,6 +785,7 @@ export class Connection { const updates: MultiStateUpdateItem[] = updatesPayload; + const defaultStates = await this.getOfflineDefaultStates(airport); const now = Date.now(); const state = this.getOrCreateAirportState(airport); const normalizedUpdates: MultiStateUpdateItem[] = []; @@ -738,13 +793,8 @@ export class Connection { for (let index = 0; index < updates.length; index++) { const update = updates[index]; try { - const normalized = this.applyStateUpdateToAirport( - state, - update as Record, - controllerId, - now, - ); - await this.pruneDefaultStateOverride(airport, state, normalized.objectId); + const normalized = this.applyStateUpdateToAirport(state, update as Record, controllerId, now); + this.pruneDefaultStateOverride(state, normalized.objectId, defaultStates); normalizedUpdates.push(normalized); } catch (error) { const message = error instanceof Error ? error.message : 'Unknown error'; @@ -778,7 +828,7 @@ export class Connection { this.markAirportStateDirty(socketInfo.airport); await this.flushAirportDurableState(socketInfo.airport); - await this.broadcast( + this.broadcast( { type: 'CONTROLLER_DISCONNECT', airport: socketInfo.airport, @@ -818,15 +868,13 @@ export class Connection { vatsimCheckCounter++; if (vatsimCheckCounter >= VATSIM_CHECK_FREQUENCY) { vatsimCheckCounter = 0; - await this.checkSocketStatus(socket, socketInfo, now); + const statusCheck = this.checkSocketStatus(socket, socketInfo, now); + if (statusCheck) await statusCheck; } // Send heartbeat with error handling try { - this.sendPacket(socket, { - type: 'HEARTBEAT', - // Server will handle timestamp - }); + this.sendSerializedPacket(socket, SERIALIZED_HEARTBEAT, 'heartbeat'); } catch (sendError) { console.error(`Failed to send heartbeat to ${socketInfo.controllerId}:`, sendError); socket.close(1011, 'Failed to send heartbeat'); @@ -851,15 +899,38 @@ export class Connection { }); } - private async checkSocketStatus(socket: WebSocket, socketInfo: SocketInfo, now: number) { + private checkSocketStatus(socket: WebSocket, socketInfo: SocketInfo, now: number): Promise | undefined { if (socketInfo.statusCheckInFlight || now - socketInfo.lastStatusCheck < SOCKET_STATUS_CHECK_INTERVAL_MS) { - return; + return undefined; } socketInfo.statusCheckInFlight = true; socketInfo.lastStatusCheck = now; + return this.runSocketStatusCheck(socket, socketInfo, now); + } + + private getConnectionStatus(controllerId: string): Promise { + const existing = this.pendingConnectionStatusChecks.get(controllerId); + if (existing) return existing; + + const request: Promise = (async () => { + if (await this.auth.isVatsimIdBanned(controllerId)) { + return { banned: true, status: null }; + } + return { banned: false, status: await this.vatsim.getUserStatus(controllerId) }; + })().finally(() => { + if (this.pendingConnectionStatusChecks.get(controllerId) === request) { + this.pendingConnectionStatusChecks.delete(controllerId); + } + }); + this.pendingConnectionStatusChecks.set(controllerId, request); + return request; + } + + private async runSocketStatusCheck(socket: WebSocket, socketInfo: SocketInfo, now: number) { try { - if (await this.auth.isVatsimIdBanned(socketInfo.controllerId)) { + const connectionStatus = await this.getConnectionStatus(socketInfo.controllerId); + if (connectionStatus.banned) { this.sendPacket(socket, { type: 'ERROR', data: { message: 'Account banned' }, @@ -870,7 +941,7 @@ export class Connection { return; } - const status = await this.vatsim.getUserStatus(socketInfo.controllerId); + const status = connectionStatus.status; if (!status) { socketInfo.consecutiveVatsimFailures++; if (socketInfo.consecutiveVatsimFailures >= MAX_CONSECUTIVE_STATUS_FAILURES) { @@ -916,8 +987,7 @@ export class Connection { const now = Date.now(); - // Use class constant - if (now - state.lastUpdate > this.TWO_MINUTES && !this.hasLiveControllers(airport)) { + if (now - state.lastUpdate > STALE_STATE_TIMEOUT_MS && !this.hasLiveControllers(airport)) { // Clear objects but keep the airport state structure state.objects.clear(); state.lastUpdate = now; @@ -957,6 +1027,7 @@ export class Connection { const template = await inFlight; this.offlineStateCache.set(normalizedAirport, { template, + defaultStates: new Map(template.map((point) => [point.id, point.state])), expiresAt: Date.now() + OFFLINE_STATE_CACHE_TTL_MS, }); return template; @@ -967,6 +1038,16 @@ export class Connection { } } + private async getOfflineDefaultStates(airport: string): Promise> { + const normalizedAirport = airport.toUpperCase(); + const template = await this.getOfflineStateTemplate(normalizedAirport); + const cached = this.offlineStateCache.get(normalizedAirport); + if (cached?.template === template && cached.defaultStates) { + return cached.defaultStates; + } + return new Map(template.map((point) => [point.id, point.state])); + } + private async loadOfflineStateTemplate(airport: string): Promise { // Create the necessary services to fetch points const idService = new IDService(); @@ -992,26 +1073,23 @@ export class Connection { } private async getOnlineStateObjects(airport: string, state: AirportState): Promise { - await this.pruneDefaultStateOverrides(airport, state); + const defaultStates = await this.getOfflineDefaultStates(airport); + this.pruneDefaultStateOverrides(state, defaultStates, airport); return Array.from(state.objects.values()); } - private async pruneDefaultStateOverride(airport: string, state: AirportState, objectId: string) { + private pruneDefaultStateOverride(state: AirportState, objectId: string, defaultStates: ReadonlyMap) { const object = state.objects.get(objectId); if (!object || typeof object.state !== 'boolean') { return; } - const template = await this.getOfflineStateTemplate(airport); - const defaultState = template.find((point) => point.id === objectId)?.state; - if (defaultState === object.state) { + if (defaultStates.get(objectId) === object.state) { state.objects.delete(objectId); } } - private async pruneDefaultStateOverrides(airport: string, state: AirportState) { - const template = await this.getOfflineStateTemplate(airport); - const defaultStates = new Map(template.map((point) => [point.id, point.state])); + private pruneDefaultStateOverrides(state: AirportState, defaultStates: ReadonlyMap, airport: string) { let pruned = false; for (const object of state.objects.values()) { @@ -1052,11 +1130,11 @@ export class Connection { if (!apiKey) return await deny(); if (!airport) return await deny(); - const user = await this.auth.getUserByApiKey(apiKey); + const { user, banned } = await this.auth.getConnectionPrincipalByApiKey(apiKey); if (!user) return await deny(); // Ban enforcement: deny connection if banned - if (await this.auth.isVatsimIdBanned(user.vatsim_id)) { + if (banned) { return new Response('Banned', { status: 403 }); } @@ -1088,17 +1166,18 @@ export class Connection { this.startHeartbeat(server); // Track connection in background to avoid blocking WS upgrade on slow D1 - this.trackConnection(clientType, airport).catch((err) => { - console.error('trackConnection failed:', err); - }); + this.state.waitUntil( + this.trackConnection(clientType, airport).catch((err) => { + console.error('trackConnection failed:', err); + }), + ); // Handle controller connection if (clientType === 'controller') { - state.controllers.add(user.vatsim_id); this.markAirportStateDirty(airport, true); // Notify others about new controller - await this.broadcast( + this.broadcast( { type: 'CONTROLLER_CONNECT', airport, @@ -1111,12 +1190,11 @@ export class Connection { const now = Date.now(); const liveControllers = this.getLiveControllerIds(airport); const hasActiveControllers = liveControllers.length > 0; - const hasActiveState = hasActiveControllers; let stateObjects; let isOffline = false; - if (clientType === 'controller' || hasActiveState) { + if (clientType === 'controller' || hasActiveControllers) { stateObjects = await this.getOnlineStateObjects(airport, state); isOffline = false; } else { @@ -1145,297 +1223,274 @@ export class Connection { } server.addEventListener('message', (event) => { - void this.enqueueSocketTask(server, async () => { - const socketInfo = this.sockets.get(server); - if (!socketInfo) { - console.warn('Received message from unregistered socket'); - return; - } - - try { - // Parse and validate message data - let rawData: string; - try { - rawData = typeof event.data === 'string' ? event.data : new TextDecoder().decode(event.data); - } catch { - throw new Error('Failed to decode message data'); - } - - // Validate message size - const MAX_MESSAGE_SIZE = 50000; // 50KB limit - if (rawData.length > MAX_MESSAGE_SIZE) { - throw new Error(`Message size exceeds maximum allowed size of ${MAX_MESSAGE_SIZE} characters`); - } - - // Parse JSON with error handling - let packet: unknown; - try { - packet = JSON.parse(rawData); - } catch { - throw new Error('Invalid JSON format'); - } - - // Validate packet structure - if (!this.validatePacket(packet)) { - throw new Error('Invalid packet structure or type'); - } - - const now = Date.now(); - // Update last heartbeat time for any message received - socketInfo.lastHeartbeat = now; - - // Update object status on each message to keep last_updated current (non-fatal on failure) - this.touchActiveObjectStatus(); - void this.checkSocketStatus(server, socketInfo, now); - - const packetAirport = this.resolvePacketAirport(packet as Packet, socketInfo.airport); - // Handle different packet types - switch ((packet as Packet).type) { - case 'HEARTBEAT': - // Respond to heartbeat with acknowledgment, adding server timestamp - this.sendPacket(server, { - type: 'HEARTBEAT_ACK', - timestamp: now, - }); - break; - - case 'HEARTBEAT_ACK': - // Accept acknowledgments from clients that respond to server heartbeats. - break; - - case 'STOPBAR_CROSSING': { - // Only pilots can send this packet; observers and controllers shouldn't - if (clientType !== 'pilot') { - throw new Error('Only pilot clients can send STOPBAR_CROSSING'); - } - - const p = packet as Packet; - const airport = socketInfo.airport; - if (!p.data || typeof p.data !== 'object' || Array.isArray(p.data)) { - throw new Error('Invalid payload for STOPBAR_CROSSING'); - } - const objectId = (p.data as { objectId?: string }).objectId; - if (!objectId) { - throw new Error('objectId is required'); - } - - // Prepare broadcast packet to controllers only - const broadcastPacket: Packet = { - type: 'STOPBAR_CROSSING', - airport, - data: { - objectId, - controllerId: user.vatsim_id, - }, - timestamp: now, - }; - - await this.broadcastToControllers(broadcastPacket, server); - this.trackMessage({ - clientType, - messageType: 'STOPBAR_CROSSING', - airport, - meta: { - objectId, - }, - }); - break; + this.state.waitUntil( + this.enqueueSocketTask(server, async () => { + const socketInfo = this.sockets.get(server); + if (!socketInfo) { + console.warn('Received message from unregistered socket'); + return; } - case 'GET_STATE': { - // Provide current state snapshot (controllers + pilots can request; observers too) - const airport = packetAirport; - const state = this.airportStates.get(airport); - let offline = false; - let objects: AirportObject[] = []; - - // Determine if controllers currently connected for this airport - const hasControllers = this.hasLiveControllers(airport); - - if (state && hasControllers) { - // If any controller currently connected, treat state as online regardless of recency - objects = await this.getOnlineStateObjects(airport, state); + try { + // Parse and validate message data + let rawData: string; + if (typeof event.data === 'string') { + rawData = event.data; } else { - offline = true; - objects = await this.getOfflineStateFromPoints(airport); + if (event.data.byteLength > MAX_MESSAGE_SIZE) { + throw new Error(`Message size exceeds maximum allowed size of ${MAX_MESSAGE_SIZE} characters`); + } + try { + rawData = PACKET_DECODER.decode(event.data); + } catch { + throw new Error('Failed to decode message data'); + } } - const snapshot: Packet = { - type: 'STATE_SNAPSHOT', - airport, - data: { - objects, - sharedState: this.getSharedStateSnapshot(airport), - controllers: this.getLiveControllerIds(airport), - offline, - requestedAt: (packet as Packet).timestamp || now, - }, - timestamp: Date.now(), - }; - this.sendPacket(server, snapshot, 'state_snapshot'); - break; - } - - case 'MULTI_STATE_UPDATE': - if (clientType === 'pilot') { - throw new Error('Pilots cannot send state updates'); - } - if (clientType === 'observer') { - throw new Error('Observers cannot send state updates'); + // Validate message size + if (rawData.length > MAX_MESSAGE_SIZE) { + throw new Error(`Message size exceeds maximum allowed size of ${MAX_MESSAGE_SIZE} characters`); } + // Parse JSON with error handling + let packet: unknown; try { - const { updates, timestamp, airport } = await this.handleMultiStateUpdate( - packet as Packet, - user.vatsim_id, - packetAirport, - ); - const broadcastPacket: Packet = { - type: 'MULTI_STATE_UPDATE', - airport, - data: { updates }, - timestamp, - }; - await this.broadcast(broadcastPacket, server); - this.trackMessage({ - clientType, - messageType: 'MULTI_STATE_UPDATE', - airport: socketInfo.airport, - meta: { count: updates.length }, - }); - } catch (updateError) { - throw new Error( - `State batch update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`, - ); + packet = JSON.parse(rawData); + } catch { + throw new Error('Invalid JSON format'); } - break; - case 'STATE_UPDATE': - if (clientType === 'pilot') { - throw new Error('Pilots cannot send state updates'); - } - if (clientType === 'observer') { - throw new Error('Observers cannot send state updates'); + // Validate packet structure + if (!this.validatePacket(packet)) { + throw new Error('Invalid packet structure or type'); } - try { - const timestamp = await this.handleStateUpdate(packet as Packet, user.vatsim_id, packetAirport); - const broadcastPacket = { - ...(packet as Packet), - airport: packetAirport, - timestamp, - }; - await this.broadcast(broadcastPacket, server); - const data = ((packet as Packet).data || {}) as Record; - const patchValue = data.patch as unknown; - const meta: Record = { - objectId: typeof data.objectId === 'string' ? data.objectId : undefined, - updateMode: patchValue !== undefined ? 'patch' : 'state', - }; - if (patchValue && typeof patchValue === 'object' && !Array.isArray(patchValue)) { - meta.patchKeys = Object.keys(patchValue as Record).length; + const now = Date.now(); + // Update last heartbeat time for any message received + socketInfo.lastHeartbeat = now; + + // Update object status on each message to keep last_updated current (non-fatal on failure) + this.touchActiveObjectStatus(); + const statusCheck = this.checkSocketStatus(server, socketInfo, now); + if (statusCheck) this.state.waitUntil(statusCheck); + + const packetAirport = this.resolvePacketAirport(packet as Packet, socketInfo.airport); + // Handle different packet types + switch ((packet as Packet).type) { + case 'HEARTBEAT': + // Respond to heartbeat with acknowledgment, adding server timestamp + this.sendPacket(server, { + type: 'HEARTBEAT_ACK', + timestamp: now, + }); + break; + + case 'HEARTBEAT_ACK': + // Accept acknowledgments from clients that respond to server heartbeats. + break; + + case 'STOPBAR_CROSSING': { + // Only pilots can send this packet; observers and controllers shouldn't + if (clientType !== 'pilot') { + throw new Error('Only pilot clients can send STOPBAR_CROSSING'); + } + + const p = packet as Packet; + const airport = socketInfo.airport; + if (!p.data || typeof p.data !== 'object' || Array.isArray(p.data)) { + throw new Error('Invalid payload for STOPBAR_CROSSING'); + } + const objectId = (p.data as { objectId?: string }).objectId; + if (!objectId) { + throw new Error('objectId is required'); + } + + // Prepare broadcast packet to controllers only + const broadcastPacket: Packet = { + type: 'STOPBAR_CROSSING', + airport, + data: { + objectId, + controllerId: user.vatsim_id, + }, + timestamp: now, + }; + + const recipients = this.broadcastToControllers(broadcastPacket, server, false); + this.trackMessage({ + clientType, + messageType: 'STOPBAR_CROSSING', + airport, + meta: { + objectId, + }, + }, recipients); + break; } - this.trackMessage({ - clientType, - messageType: 'STATE_UPDATE', - airport: socketInfo.airport, - meta, - }); - } catch (updateError) { - throw new Error( - `State update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`, - ); - } - break; - case 'CLOSE': { - // Handle graceful disconnection - if (clientType === 'controller') { - await this.handleControllerDisconnect(server); - } - const removed = this.unregisterSocket(server); - if (removed) { - await this.trackDisconnection(removed, 'client_close'); - } - server.close(1000, 'Client requested disconnection'); - break; - } + case 'GET_STATE': { + // Provide current state snapshot (controllers + pilots can request; observers too) + const airport = packetAirport; + const state = this.airportStates.get(airport); + let offline = false; + let objects: AirportObject[] = []; + + // Determine if controllers currently connected for this airport + const hasControllers = this.hasLiveControllers(airport); + + if (state && hasControllers) { + // If any controller currently connected, treat state as online regardless of recency + objects = await this.getOnlineStateObjects(airport, state); + } else { + offline = true; + objects = await this.getOfflineStateFromPoints(airport); + } + + const snapshot: Packet = { + type: 'STATE_SNAPSHOT', + airport, + data: { + objects, + sharedState: this.getSharedStateSnapshot(airport), + controllers: this.getLiveControllerIds(airport), + offline, + requestedAt: (packet as Packet).timestamp || now, + }, + timestamp: Date.now(), + }; + this.sendPacket(server, snapshot, 'state_snapshot'); + break; + } - case 'SHARED_STATE_UPDATE': - // Handle shared state updates - if (clientType === 'pilot' || clientType === 'observer') { - throw new Error('Only controllers can send shared state updates'); - } + case 'MULTI_STATE_UPDATE': + if (clientType === 'pilot') { + throw new Error('Pilots cannot send state updates'); + } + if (clientType === 'observer') { + throw new Error('Observers cannot send state updates'); + } + + try { + const { updates, timestamp, airport } = await this.handleMultiStateUpdate( + packet as Packet, + user.vatsim_id, + packetAirport, + ); + const broadcastPacket: Packet = { + type: 'MULTI_STATE_UPDATE', + airport, + data: { updates }, + timestamp, + }; + const recipients = this.broadcast(broadcastPacket, server, false); + this.trackMessage({ + clientType, + messageType: 'MULTI_STATE_UPDATE', + airport: socketInfo.airport, + meta: { count: updates.length }, + }, recipients); + } catch (updateError) { + throw new Error( + `State batch update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`, + ); + } + break; + + case 'STATE_UPDATE': + if (clientType === 'pilot') { + throw new Error('Pilots cannot send state updates'); + } + if (clientType === 'observer') { + throw new Error('Observers cannot send state updates'); + } + + try { + const timestamp = await this.handleStateUpdate(packet as Packet, user.vatsim_id, packetAirport); + const broadcastPacket = { + ...(packet as Packet), + airport: packetAirport, + timestamp, + }; + const recipients = this.broadcast(broadcastPacket, server, false); + const data = ((packet as Packet).data || {}) as Record; + const patchValue = data.patch as unknown; + const meta: Record = { + objectId: typeof data.objectId === 'string' ? data.objectId : undefined, + updateMode: patchValue !== undefined ? 'patch' : 'state', + }; + if (patchValue && typeof patchValue === 'object' && !Array.isArray(patchValue)) { + meta.patchKeys = Object.keys(patchValue as Record).length; + } + this.trackMessage({ + clientType, + messageType: 'STATE_UPDATE', + airport: socketInfo.airport, + meta, + }, recipients); + } catch (updateError) { + throw new Error( + `State update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`, + ); + } + break; + + case 'CLOSE': { + // Handle graceful disconnection + if (clientType === 'controller') { + await this.handleControllerDisconnect(server); + } + const removed = this.unregisterSocket(server); + if (removed) { + await this.trackDisconnection(removed, 'client_close'); + } + server.close(1000, 'Client requested disconnection'); + break; + } - try { - await this.handleSharedStateUpdate(packet as Packet, user.vatsim_id, packetAirport); - } catch (updateError) { - throw new Error( - `Shared state update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`, - ); + case 'SHARED_STATE_UPDATE': + // Handle shared state updates + if (clientType === 'pilot' || clientType === 'observer') { + throw new Error('Only controllers can send shared state updates'); + } + + try { + await this.handleSharedStateUpdate(packet as Packet, user.vatsim_id, packetAirport); + } catch (updateError) { + throw new Error( + `Shared state update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`, + ); + } + break; + + default: + // Reject unknown packet types + throw new Error(`Unknown packet type: ${packet.type}`); } - break; - - default: - // Reject unknown packet types - throw new Error(`Unknown packet type: ${packet.type}`); - } - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'; - console.error(`Message handling error for ${socketInfo.controllerId}:`, errorMessage); - - // Send error response to client - if ( - !this.sendPacket(server, { - type: 'ERROR', - data: { message: errorMessage }, - timestamp: Date.now(), - }) - ) { - server.close(1011, 'Internal error - unable to communicate'); - } - } - }); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'; + console.error(`Message handling error for ${socketInfo.controllerId}:`, errorMessage); + + // Send error response to client + if ( + !this.sendPacket(server, { + type: 'ERROR', + data: { message: errorMessage }, + timestamp: Date.now(), + }) + ) { + server.close(1011, 'Internal error - unable to communicate'); + } + } + }), + ); }); - server.addEventListener('close', async () => { - const info = this.sockets.get(server); - if (info?.type === 'controller') { - try { - await this.handleControllerDisconnect(server); - } catch (e) { - console.warn('handleControllerDisconnect failed on close (non-fatal):', e); - } - } - const removed = this.unregisterSocket(server); - if (!removed) { - return; - } - try { - await this.trackDisconnection(removed, 'close_event'); - } catch (e) { - console.warn('trackDisconnection failed on close (non-fatal):', e); - } + server.addEventListener('close', () => { + this.state.waitUntil(this.handleSocketTermination(server, 'close_event')); }); - server.addEventListener('error', async () => { - const info = this.sockets.get(server); - if (info?.type === 'controller') { - try { - await this.handleControllerDisconnect(server); - } catch (e) { - console.warn('handleControllerDisconnect failed on error (non-fatal):', e); - } - } - const removed = this.unregisterSocket(server); - if (!removed) { - return; - } - try { - await this.trackDisconnection(removed, 'socket_error'); - } catch (e) { - console.warn('trackDisconnection failed on error (non-fatal):', e); - } + server.addEventListener('error', () => { + this.state.waitUntil(this.handleSocketTermination(server, 'socket_error')); }); return new Response(null, { status: 101, webSocket: client }); @@ -1496,7 +1551,7 @@ export class Connection { info.sendFailures++; if (info.sendFailures >= SEND_FAILURE_LIMIT) { socket.close(1011, 'Repeated send failures'); - void this.cleanupSocket(socket, 'send_failure'); + this.state.waitUntil(this.cleanupSocket(socket, 'send_failure')); } } @@ -1522,15 +1577,35 @@ export class Connection { } } + private async handleSocketTermination(socket: WebSocket, reason: 'close_event' | 'socket_error') { + const info = this.sockets.get(socket); + if (info?.type === 'controller') { + try { + await this.handleControllerDisconnect(socket); + } catch (error) { + console.warn('handleControllerDisconnect failed during socket termination (non-fatal):', error); + } + } + const removed = this.unregisterSocket(socket); + if (!removed) return; + try { + await this.trackDisconnection(removed, reason); + } catch (error) { + console.warn('trackDisconnection failed during socket termination (non-fatal):', error); + } + } + private touchActiveObjectStatus() { if (this.activeObjectTouchInFlight) return; const now = Date.now(); if (now - this.lastActiveObjectsUpdate < ACTIVE_OBJECT_TOUCH_INTERVAL_MS) return; this.activeObjectTouchInFlight = true; - void this.updateObjectStatus().finally(() => { - this.activeObjectTouchInFlight = false; - }); + this.state.waitUntil( + this.updateObjectStatus().finally(() => { + this.activeObjectTouchInFlight = false; + }), + ); } private trackBroadcast(messageType: Packet['type'], airport: string, recipients: number) { @@ -1544,19 +1619,18 @@ export class Connection { } private async trackConnection(clientType: ClientType, airport: string) { - await this.updateActiveConnections(1); - // Add this object to active_objects table when first connection is made if (this.sockets.size === 1) { + const session = DatabaseContextFactory.createSessionService(this.env.DB); try { - const session = DatabaseContextFactory.createSessionService(this.env.DB); await session.executeWrite( "INSERT OR REPLACE INTO active_objects (id, name, last_updated) VALUES (?, ?, datetime('now'))", [this.objectId, this.getObjectName()], ); - session.closeSession(); } catch (e) { console.warn('Failed to upsert active_objects on connect (non-fatal):', e instanceof Error ? e.message : e); + } finally { + session.closeSession(); } } @@ -1572,16 +1646,15 @@ export class Connection { } private async trackDisconnection(info: { controllerId: string; type: ClientType; airport: string }, reason?: string) { - await this.updateActiveConnections(-1); - // If no more connections, remove from active_objects if (this.sockets.size === 0) { + const session = DatabaseContextFactory.createSessionService(this.env.DB); try { - const session = DatabaseContextFactory.createSessionService(this.env.DB); await session.executeWrite('DELETE FROM active_objects WHERE id = ?', [this.objectId]); - session.closeSession(); } catch (e) { console.warn('Failed to delete active_objects on disconnect (non-fatal):', e instanceof Error ? e.message : e); + } finally { + session.closeSession(); } } @@ -1611,16 +1684,17 @@ export class Connection { // Update the object's name and last_updated timestamp const name = this.getObjectName(); + const session = DatabaseContextFactory.createSessionService(this.env.DB); try { - const session = DatabaseContextFactory.createSessionService(this.env.DB); await session.executeWrite("UPDATE active_objects SET name = ?, last_updated = datetime('now') WHERE id = ?", [ name, this.objectId, ]); - session.closeSession(); this.lastActiveObjectsUpdate = now; } catch (e) { console.warn('Failed to update active_objects name (non-fatal):', e instanceof Error ? e.message : e); + } finally { + session.closeSession(); } } } @@ -1630,7 +1704,7 @@ export class Connection { messageType: Packet['type']; airport: string; meta?: Record; - }) { + }, broadcastRecipients = 0) { const props: Record = { airport: details.airport, clientType: details.clientType, @@ -1638,111 +1712,49 @@ export class Connection { socket_count: this.sockets.size, ...details.meta, }; + if (broadcastRecipients > 0) { + this.emitAnalyticsBatch([ + { + event: 'ws_broadcast', + properties: { + airport: details.airport, + messageType: details.messageType, + recipients: broadcastRecipients, + socket_count: this.sockets.size, + }, + }, + { event: 'ws_message', properties: props }, + ]); + return; + } this.emitAnalytics('ws_message', props); } - private async updateActiveConnections(change: number) { - const activeConnectionsKey = 'active_connections'; - const current = ((await this.state.storage.get(activeConnectionsKey)) as number) || 0; - await this.state.storage.put(activeConnectionsKey, Math.max(0, current + change)); + async getState(airport: string, forceOffline = false): Promise { + if (forceOffline) { + return { airport, objects: await this.getOfflineStateFromPoints(airport), offline: true }; + } + + const controllers = this.getLiveControllerIds(airport); + const pilots = this.getLivePilotIds(airport); + + const state = this.airportStates.get(airport); + const online = Boolean(state && this.hasLiveControllers(airport)); + const objects = online ? await this.getOnlineStateObjects(airport, state!) : await this.getOfflineStateFromPoints(airport); + + return { airport, controllers, pilots, objects, offline: !online }; } async fetch(request: Request) { if (request.headers.get('X-Request-Type') === 'get_state') { const url = new URL(request.url); const airport = url.searchParams.get('airport'); - const forceOffline = url.searchParams.get('offline') === 'true'; - if (!airport) { - return new Response( - JSON.stringify({ - error: 'Airport parameter required', - }), - { - status: 400, - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, - }, - ); - } - - if (forceOffline) { - const objects = await this.getOfflineStateFromPoints(airport); - return new Response( - JSON.stringify({ - airport, - objects, - offline: true, - }), - { - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, - }, - ); - } - - // Get connected clients for this airport regardless of state - const connectedClients = Array.from(this.sockets.entries()) - .filter(([, info]) => info.airport === airport) - .reduce( - (acc, [, info]) => { - if (info.type === 'controller') { - // Use Set to prevent duplicates, then convert to array - if (!acc.controllerSet.has(info.controllerId)) { - acc.controllerSet.add(info.controllerId); - acc.controllers.push(info.controllerId); - } - } else if (info.type === 'pilot') { - // Use Set to prevent duplicates, then convert to array - if (!acc.pilotSet.has(info.controllerId)) { - acc.pilotSet.add(info.controllerId); - acc.pilots.push(info.controllerId); - } - } - return acc; - }, - { - controllers: [] as string[], - pilots: [] as string[], - controllerSet: new Set(), - pilotSet: new Set(), - }, - ); - const state = this.airportStates.get(airport); - let isOffline = false; - let objects: AirportObject[] = []; - - // If there are no controllers connected, always use offline mode - const connectedControllers = this.hasLiveControllers(airport); - - if (state && connectedControllers) { - // Return active state with all objects regardless of recency since controllers are connected - objects = await this.getOnlineStateObjects(airport, state); - } else { - // No controllers connected or no state exists, mark as offline - isOffline = true; - objects = await this.getOfflineStateFromPoints(airport); + return Response.json({ error: 'Airport parameter required' }, { status: 400 }); } - - return new Response( - JSON.stringify({ - airport, - controllers: connectedClients.controllers, - pilots: connectedClients.pilots, - objects: objects, - offline: isOffline, - }), - { - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, - }, - ); + return Response.json(await this.getState(airport, url.searchParams.get('offline') === 'true'), { + headers: { 'Access-Control-Allow-Origin': '*' }, + }); } if (request.headers.get('Upgrade') === 'websocket') { @@ -1751,27 +1763,32 @@ export class Connection { return new Response('Expected WebSocket', { status: 400 }); } - private async broadcastToControllers(packet: Packet, sender?: WebSocket) { + private broadcastToControllers(packet: Packet, sender?: WebSocket, trackAnalytics = true): number { const airport = packet.airport; - if (!airport) return; + if (!airport) return 0; + const airportControllers = this.controllerSockets.get(airport); + if (!airportControllers) return 0; let packetString: string; try { packetString = JSON.stringify(packet); } catch (error) { console.error('Failed to serialize controller broadcast packet:', error); - return; + return 0; } let recipients = 0; - this.sockets.forEach((client, socket) => { - if (socket !== sender && socket.readyState === WebSocket.OPEN && client.airport === airport && client.type === 'controller') { - recipients++; - this.sendSerializedPacket(socket, packetString, 'controller_broadcast'); + for (const controllerSocketSet of airportControllers.values()) { + for (const socket of controllerSocketSet) { + if (socket !== sender && socket.readyState === WebSocket.OPEN) { + recipients++; + this.sendSerializedPacket(socket, packetString, 'controller_broadcast'); + } } - }); + } - this.trackBroadcast(packet.type, airport, recipients); + if (trackAnalytics) this.trackBroadcast(packet.type, airport, recipients); + return recipients; } private getOrCreateSharedState(airport: string): Record { @@ -1789,7 +1806,7 @@ export class Connection { throw new Error('Invalid packet data structure'); } - if (!packet.data.sharedStatePatch || typeof packet.data.sharedStatePatch !== 'object') { + if (!packet.data.sharedStatePatch || typeof packet.data.sharedStatePatch !== 'object' || Array.isArray(packet.data.sharedStatePatch)) { throw new Error('Missing or invalid sharedStatePatch'); } @@ -1802,14 +1819,14 @@ export class Connection { const patch = packet.data.sharedStatePatch as Record; const patchKeyCount = Object.keys(patch).length; let patchSize = 0; + let serializedPatch = ''; // Validate patch structure and size try { - const patchString = JSON.stringify(patch); - patchSize = patchString.length; - const MAX_PATCH_SIZE = 10240; // 10KB limit - if (patchSize > MAX_PATCH_SIZE) { - throw new Error(`Patch size exceeds maximum allowed size of ${MAX_PATCH_SIZE} characters`); + serializedPatch = JSON.stringify(patch); + patchSize = serializedPatch.length; + if (patchSize > MAX_SHARED_PATCH_SIZE) { + throw new Error(`Patch size exceeds maximum allowed size of ${MAX_SHARED_PATCH_SIZE} characters`); } } catch { throw new Error('Patch data is not serializable'); @@ -1827,7 +1844,7 @@ export class Connection { this.markSharedStateDirty(airport); // Broadcast to all clients (including sender) - await this.broadcastSharedState(airport, patch, controllerId); + const recipients = this.broadcastSharedState(airport, serializedPatch, controllerId); this.trackMessage({ clientType: 'controller', @@ -1837,7 +1854,7 @@ export class Connection { patchKeys: patchKeyCount, patchSize, }, - }); + }, recipients); return updatedState; } catch (error) { @@ -1846,34 +1863,18 @@ export class Connection { } } - private async broadcastSharedState(airport: string, patch: Record, controllerId: string) { - const packet: Packet = { - type: 'SHARED_STATE_UPDATE', - airport: airport, - data: { - sharedStatePatch: patch, - controllerId: controllerId, - }, - timestamp: Date.now(), - }; - - let packetString: string; - try { - packetString = JSON.stringify(packet); - } catch (error) { - console.error('Failed to serialize shared state packet:', error); - return; - } + private broadcastSharedState(airport: string, serializedPatch: string, controllerId: string): number { + const packetString = `{"type":"SHARED_STATE_UPDATE","airport":${JSON.stringify(airport)},"data":{"sharedStatePatch":${serializedPatch},"controllerId":${JSON.stringify(controllerId)}},"timestamp":${Date.now()}}`; let recipients = 0; - this.sockets.forEach((client, socket) => { + for (const [socket, client] of this.sockets) { if (socket.readyState === WebSocket.OPEN && client.airport === airport) { recipients++; this.sendSerializedPacket(socket, packetString, 'shared_state_broadcast'); } - }); + } - this.trackBroadcast(packet.type, airport, recipients); + return recipients; } private getSharedStateSnapshot(airport: string): Record { @@ -1893,24 +1894,7 @@ export class Connection { return false; } - // Validate known packet types - const validTypes = [ - 'HEARTBEAT', - 'HEARTBEAT_ACK', - 'STATE_UPDATE', - 'MULTI_STATE_UPDATE', - 'CLOSE', - 'SHARED_STATE_UPDATE', - 'INITIAL_STATE', - 'CONTROLLER_CONNECT', - 'CONTROLLER_DISCONNECT', - 'ERROR', - 'GET_STATE', - 'STATE_SNAPSHOT', - 'STOPBAR_CROSSING', - ]; - - if (!validTypes.includes(type)) { + if (!VALID_PACKET_TYPES.has(type as Packet['type'])) { return false; } @@ -1926,15 +1910,7 @@ export class Connection { return false; } - // Type-specific validation - // Global size/depth guard for any packet carrying data - const MAX_PACKET_CHARS = 50000; - try { - const s = JSON.stringify(packet); - if (s.length > MAX_PACKET_CHARS) return false; - } catch { - return false; - } + // The raw message length and JSON parse are checked before this method. switch (type) { case 'STATE_UPDATE': return this.validateStateUpdatePacket(packet); @@ -1957,7 +1933,7 @@ export class Connection { const data = obj.data as Record; // Must have objectId - if (!data.objectId || typeof data.objectId !== 'string') { + if (!data.objectId || typeof data.objectId !== 'string' || !OBJECT_ID_REGEX.test(data.objectId)) { return false; } @@ -1966,27 +1942,24 @@ export class Connection { return false; } - // Guard patch/state size and depth - const guardObject = (val: unknown, maxDepth = 20, maxProps = 100): boolean => { - const seen = new WeakSet(); - const walk = (v: unknown, depth: number): boolean => { - if (v === null) return true; - if (typeof v !== 'object') return true; - if (Array.isArray(v)) { - return v.length <= 1000 && v.every((it) => walk(it, depth + 1)); - } - if (depth > maxDepth) return false; - const o = v as Record; - if (seen.has(o)) return false; - seen.add(o); - const keys = Object.keys(o); - if (keys.length > maxProps) return false; - return keys.every((k) => typeof k === 'string' && k.length <= 100 && walk(o[k], depth + 1)); - }; - return walk(val, 0); - }; - if (data.patch !== undefined && !guardObject(data.patch)) return false; - if (data.state !== undefined && !guardObject(data.state)) return false; + if ( + data.patch !== undefined && + (data.patch === null || (typeof data.patch === 'object' && !Array.isArray(data.patch))) && + !isSafeNestedValue(data.patch) + ) { + return false; + } + if (data.patch !== undefined && data.patch !== null && (typeof data.patch !== 'object' || Array.isArray(data.patch))) { + return false; + } + if ( + data.state !== undefined && + typeof data.state !== 'boolean' && + (typeof data.state !== 'object' || data.state === null || Array.isArray(data.state)) + ) { + return false; + } + if (data.state !== undefined && !isSafeNestedValue(data.state)) return false; return true; } @@ -2005,33 +1978,24 @@ export class Connection { const typedUpdates: MultiStateUpdateItem[] = updates; - const guardObject = (val: unknown, maxDepth = 20, maxProps = 100): boolean => { - const seen = new WeakSet(); - const walk = (v: unknown, depth: number): boolean => { - if (v === null) return true; - if (typeof v !== 'object') return true; - if (Array.isArray(v)) { - return v.length <= 1000 && v.every((it) => walk(it, depth + 1)); - } - if (depth > maxDepth) return false; - const o = v as Record; - if (seen.has(o)) return false; - seen.add(o); - const keys = Object.keys(o); - if (keys.length > maxProps) return false; - return keys.every((k) => typeof k === 'string' && k.length <= 100 && walk(o[k], depth + 1)); - }; - return walk(val, 0); - }; - for (const update of typedUpdates) { if (!update || typeof update !== 'object') return false; const data = update as Record; if (!data.objectId || typeof data.objectId !== 'string') return false; if (!OBJECT_ID_REGEX.test(data.objectId)) return false; if (data.patch === undefined && data.state === undefined) return false; - if (data.patch !== undefined && !guardObject(data.patch)) return false; - if (data.state !== undefined && !guardObject(data.state)) return false; + if (data.patch !== undefined && data.patch !== null && (typeof data.patch !== 'object' || Array.isArray(data.patch))) { + return false; + } + if ( + data.state !== undefined && + typeof data.state !== 'boolean' && + (typeof data.state !== 'object' || data.state === null || Array.isArray(data.state)) + ) { + return false; + } + if (data.patch !== undefined && !isSafeNestedValue(data.patch)) return false; + if (data.state !== undefined && !isSafeNestedValue(data.state)) return false; } return true; @@ -2045,30 +2009,11 @@ export class Connection { const data = obj.data as Record; // Must have sharedStatePatch - if (!data.sharedStatePatch || typeof data.sharedStatePatch !== 'object') { + if (!data.sharedStatePatch || typeof data.sharedStatePatch !== 'object' || Array.isArray(data.sharedStatePatch)) { return false; } - // Size/depth guard - const guardObject = (val: unknown, maxDepth = 20, maxProps = 100): boolean => { - const seen = new WeakSet(); - const walk = (v: unknown, depth: number): boolean => { - if (v === null) return true; - if (typeof v !== 'object') return true; - if (Array.isArray(v)) { - return v.length <= 1000 && v.every((it) => walk(it, depth + 1)); - } - if (depth > maxDepth) return false; - const o = v as Record; - if (seen.has(o)) return false; - seen.add(o); - const keys = Object.keys(o); - if (keys.length > maxProps) return false; - return keys.every((k) => typeof k === 'string' && k.length <= 100 && walk(o[k], depth + 1)); - }; - return walk(val, 0); - }; - if (!guardObject(data.sharedStatePatch)) return false; + if (!isSafeNestedValue(data.sharedStatePatch)) return false; return true; } @@ -2080,18 +2025,13 @@ export class Connection { const data = obj.data as Record; // Must have objectId - if (!data.objectId || typeof data.objectId !== 'string') { + if (!data.objectId || typeof data.objectId !== 'string' || !OBJECT_ID_REGEX.test(data.objectId)) { return false; } return true; } - private sanitizeInput(input: string): string { - // Remove potentially dangerous characters and limit length - return input.replace(/[<>'"&]/g, '').substring(0, 1000); - } - // Extracts a typed updates array from either a bare array payload or an object with `updates` private extractMultiStateUpdates(data: unknown): MultiStateUpdateItem[] | null { if (Array.isArray(data)) { diff --git a/src/services/airport.ts b/src/services/airport.ts index 954351d..e23ed33 100644 --- a/src/services/airport.ts +++ b/src/services/airport.ts @@ -31,6 +31,34 @@ interface AirportData { }>; } +type AirportRecord = { + icao: string; + latitude: number | null; + longitude: number | null; + name: string; + continent: string; + country_code: string | null; + country_name: string | null; + region_name: string | null; + elevation_ft: number | null; + elevation_m: number | null; + bbox_min_lat: number | null; + bbox_min_lon: number | null; + bbox_max_lat: number | null; + bbox_max_lon: number | null; +}; + +type RunwayRecord = { + length_ft: string; + width_ft: string; + le_ident: string; + le_latitude_deg: string; + le_longitude_deg: string; + he_ident: string; + he_latitude_deg: string; + he_longitude_deg: string; +}; + export class AirportService { constructor( private db: D1Database, @@ -57,42 +85,31 @@ export class AirportService { } return this.withDbSession(async (dbSession) => { - const airportResult = await dbSession.executeRead<{ - icao: string; - latitude: number | null; - longitude: number | null; - name: string; - continent: string; - country_code: string | null; - country_name: string | null; - region_name: string | null; - elevation_ft: number | null; - elevation_m: number | null; - bbox_min_lat: number | null; - bbox_min_lon: number | null; - bbox_max_lat: number | null; - bbox_max_lon: number | null; - }>('SELECT * FROM airports WHERE icao = ?', [uppercaseIcao]); - const airportFromDb = airportResult.results[0]; + const [airportResult, runwayResult] = await dbSession.executeReadBatch([ + { + query: `SELECT icao, latitude, longitude, name, continent, country_code, country_name, + region_name, elevation_ft, elevation_m, bbox_min_lat, bbox_min_lon, bbox_max_lat, bbox_max_lon + FROM airports WHERE icao = ? LIMIT 1`, + params: [uppercaseIcao], + }, + { + query: `SELECT length_ft, width_ft, le_ident, le_latitude_deg, le_longitude_deg, + he_ident, he_latitude_deg, he_longitude_deg + FROM runways WHERE airport_icao = ?`, + params: [uppercaseIcao], + }, + ]); + const airportFromDb = (airportResult.results as AirportRecord[])[0]; + const cachedRunways = runwayResult.results as RunwayRecord[]; if (airportFromDb) { - const fetchPromises: Promise[] = []; - let needsReread = false; - - if (airportFromDb.elevation_ft == null) { - needsReread = true; - fetchPromises.push( - this.fetchAndStoreElevation(uppercaseIcao, dbSession) - .then(() => {}) - .catch(() => {}), - ); - } - if (airportFromDb.country_code == null || airportFromDb.country_name == null || airportFromDb.region_name == null) { - needsReread = true; + const fetchPromises: Array | null>> = []; + const needsElevation = airportFromDb.elevation_ft == null; + const needsLocation = + airportFromDb.country_code == null || airportFromDb.country_name == null || airportFromDb.region_name == null; + if (needsElevation || needsLocation) { fetchPromises.push( - this.fetchAndStoreLocationMeta(uppercaseIcao, dbSession) - .then(() => {}) - .catch(() => {}), + this.fetchAndStoreMetadata(uppercaseIcao, dbSession, needsElevation, needsLocation).catch(() => null), ); } if ( @@ -101,70 +118,27 @@ export class AirportService { airportFromDb.bbox_max_lat == null || airportFromDb.bbox_max_lon == null ) { - needsReread = true; fetchPromises.push( - this.fetchAndStoreBoundingBox(uppercaseIcao, dbSession) - .then(() => {}) - .catch((err) => { - try { - this.posthog?.track('Airport Bounding Box Unavailable', { - source: 'db-cache-miss', - icao: uppercaseIcao, - error: err instanceof Error ? err.message : String(err), - }); - } catch { - /* ignore analytics errors */ - } - }), + this.fetchAndStoreBoundingBox(uppercaseIcao, dbSession).catch((err) => { + try { + this.posthog?.track('Airport Bounding Box Unavailable', { + source: 'db-cache-miss', + icao: uppercaseIcao, + error: err instanceof Error ? err.message : String(err), + }); + } catch { + /* ignore analytics errors */ + } + return null; + }), ); } - if (fetchPromises.length > 0) { - await Promise.all(fetchPromises); - } - - if (needsReread) { - const reread = await dbSession.executeRead<{ - icao: string; - latitude: number | null; - longitude: number | null; - name: string; - continent: string; - country_code: string | null; - country_name: string | null; - region_name: string | null; - elevation_ft: number | null; - elevation_m: number | null; - bbox_min_lat: number | null; - bbox_min_lon: number | null; - bbox_max_lat: number | null; - bbox_max_lon: number | null; - }>('SELECT * FROM airports WHERE icao = ?', [uppercaseIcao]); - if (reread.results[0]) Object.assign(airportFromDb, reread.results[0]); + const enrichments = await Promise.all(fetchPromises); + for (const enrichment of enrichments) { + if (enrichment) Object.assign(airportFromDb, enrichment); } - const runwaysResult = await dbSession.executeRead<{ - length_ft: string; - width_ft: string; - le_ident: string; - le_latitude_deg: string; - le_longitude_deg: string; - he_ident: string; - he_latitude_deg: string; - he_longitude_deg: string; - }>( - `SELECT - length_ft, - width_ft, - le_ident, - le_latitude_deg, - le_longitude_deg, - he_ident, - he_latitude_deg, - he_longitude_deg - FROM runways WHERE airport_icao = ?`, - [uppercaseIcao], - ); - return { ...airportFromDb, runways: runwaysResult.results }; + return { ...airportFromDb, runways: cachedRunways }; } try { @@ -191,7 +165,8 @@ export class AirportService { const elevation_ft = airportData.elevation_ft ? parseInt(airportData.elevation_ft, 10) : null; const elevation_m = elevation_ft != null && !Number.isNaN(elevation_ft) ? Math.round(elevation_ft * 0.3048 * 100) / 100 : null; - const country_code = airportData.iso_country?.trim().toUpperCase() || airportData.country?.code?.trim().toUpperCase() || null; + const country_code = + airportData.iso_country?.trim().toUpperCase() || airportData.country?.code?.trim().toUpperCase() || null; const country_name = airportData.country?.name?.trim() || null; const region_name = airportData.region?.name?.trim() || null; @@ -224,8 +199,9 @@ export class AirportService { ], ); + let storedBoundingBox: Partial | null = null; try { - await this.fetchAndStoreBoundingBox(uppercaseIcao, dbSession); + storedBoundingBox = await this.fetchAndStoreBoundingBox(uppercaseIcao, dbSession); } catch (err) { try { this.posthog?.track('Airport Bounding Box Unavailable', { @@ -238,26 +214,10 @@ export class AirportService { } } - const reread = await dbSession.executeRead<{ - icao: string; - latitude: number | null; - longitude: number | null; - name: string; - continent: string; - country_code: string | null; - country_name: string | null; - region_name: string | null; - elevation_ft: number | null; - elevation_m: number | null; - bbox_min_lat: number | null; - bbox_min_lon: number | null; - bbox_max_lat: number | null; - bbox_max_lon: number | null; - }>('SELECT * FROM airports WHERE icao = ?', [uppercaseIcao]); - const mergedAirport = { ...airport, ...reread.results[0] }; + const mergedAirport = { ...airport, ...storedBoundingBox }; if (airportData.runways && airportData.runways.length > 0) { - const openRunways = airportData.runways.filter((r) => r.closed !== '1'); + const openRunways = airportData.runways.filter((runway) => runway.closed !== '1'); const runwayStatements = openRunways.map((runway) => ({ query: ` INSERT INTO runways ( @@ -281,29 +241,6 @@ export class AirportService { await dbSession.executeBatch(runwayStatements); - const runwaysResult = await dbSession.executeRead<{ - length_ft: string; - width_ft: string; - le_ident: string; - le_latitude_deg: string; - le_longitude_deg: string; - he_ident: string; - he_latitude_deg: string; - he_longitude_deg: string; - }>( - `SELECT - length_ft, - width_ft, - le_ident, - le_latitude_deg, - le_longitude_deg, - he_ident, - he_latitude_deg, - he_longitude_deg - FROM runways WHERE airport_icao = ?`, - [uppercaseIcao], - ); - try { this.posthog?.track('Airport Fetched From External API', { icao: uppercaseIcao, @@ -313,7 +250,30 @@ export class AirportService { } catch (e) { console.warn('Posthog track failed (Airport Fetched From External API)', e); } - return { ...mergedAirport, runways: runwaysResult.results }; + return { + ...mergedAirport, + runways: openRunways.map( + ({ + length_ft, + width_ft, + le_ident, + le_latitude_deg, + le_longitude_deg, + he_ident, + he_latitude_deg, + he_longitude_deg, + }) => ({ + length_ft, + width_ft, + le_ident, + le_latitude_deg, + le_longitude_deg, + he_ident, + he_latitude_deg, + he_longitude_deg, + }), + ), + }; } try { @@ -338,22 +298,88 @@ export class AirportService { } async getAirports(icaos: string[]) { - const results = new Map(); - - const batchSize = 5; - for (let i = 0; i < icaos.length; i += batchSize) { - const batch = icaos.slice(i, i + batchSize); - const airportPromises = batch.map(async (icao) => { - const airport = await this.getAirport(icao); - if (airport) { - results.set(icao.toUpperCase(), airport); + const normalized = icaos.map((icao) => icao.toUpperCase().replace(/[^A-Z0-9]/g, '')); + const unique = [...new Set(normalized.filter((icao) => /^[A-Z0-9]{4}$/.test(icao)))]; + if (unique.length === 0) return {}; + + const cachedAirports = new Map(); + const cachedRunways = new Map(); + await this.withDbSession(async (dbSession) => { + const statements: Array<{ query: string; params: string[] }> = []; + const chunkSize = 64; + for (let offset = 0; offset < unique.length; offset += chunkSize) { + const chunk = unique.slice(offset, offset + chunkSize); + const placeholders = chunk.map(() => '?').join(', '); + statements.push( + { + query: `SELECT icao, latitude, longitude, name, continent, country_code, country_name, + region_name, elevation_ft, elevation_m, bbox_min_lat, bbox_min_lon, bbox_max_lat, bbox_max_lon + FROM airports WHERE icao IN (${placeholders})`, + params: chunk, + }, + { + query: `SELECT airport_icao, length_ft, width_ft, le_ident, le_latitude_deg, le_longitude_deg, + he_ident, he_latitude_deg, he_longitude_deg + FROM runways WHERE airport_icao IN (${placeholders})`, + params: chunk, + }, + ); + } + + const batchResults = await dbSession.executeReadBatch(statements); + for (let index = 0; index < batchResults.length; index += 2) { + for (const airport of batchResults[index].results as AirportRecord[]) cachedAirports.set(airport.icao, airport); + for (const runway of batchResults[index + 1].results as Array) { + const list = cachedRunways.get(runway.airport_icao) ?? []; + list.push({ + length_ft: runway.length_ft, + width_ft: runway.width_ft, + le_ident: runway.le_ident, + le_latitude_deg: runway.le_latitude_deg, + le_longitude_deg: runway.le_longitude_deg, + he_ident: runway.he_ident, + he_latitude_deg: runway.he_latitude_deg, + he_longitude_deg: runway.he_longitude_deg, + }); + cachedRunways.set(runway.airport_icao, list); } - }); + } + }); - await Promise.all(airportPromises); + const results = new Map(); + const needsLookup: string[] = []; + for (const icao of unique) { + const airport = cachedAirports.get(icao); + const complete = + airport && + airport.elevation_ft != null && + airport.country_code != null && + airport.country_name != null && + airport.region_name != null && + airport.bbox_min_lat != null && + airport.bbox_min_lon != null && + airport.bbox_max_lat != null && + airport.bbox_max_lon != null; + if (complete) results.set(icao, { ...airport, runways: cachedRunways.get(icao) ?? [] }); + else needsLookup.push(icao); } - return Object.fromEntries(results); + const externalBatchSize = 5; + for (let offset = 0; offset < needsLookup.length; offset += externalBatchSize) { + await Promise.all( + needsLookup.slice(offset, offset + externalBatchSize).map(async (icao) => { + const airport = await this.getAirport(icao); + if (airport) results.set(icao, airport); + }), + ); + } + + const orderedResults = new Map(); + for (const [index, icao] of normalized.entries()) { + const airport = results.get(icao); + if (airport) orderedResults.set(icaos[index].toUpperCase(), airport); + } + return Object.fromEntries(orderedResults); } async getAirportsByContinent(continent: string) { @@ -557,14 +583,13 @@ export class AirportService { throw new HttpError(503, 'Bounding box unavailable'); } - /** - * Fetch country and region info from AirportDB and store in database. - * Returns the data if successful, null otherwise. - */ - private async fetchAndStoreLocationMeta( + /** Fetch missing AirportDB metadata once and persist it with one update. */ + private async fetchAndStoreMetadata( icao: string, dbSession: DatabaseSessionService, - ): Promise<{ country_code: string | null; country_name: string | null; region_name: string | null } | null> { + needsElevation: boolean, + needsLocation: boolean, + ): Promise | null> { try { const response = await fetch(`https://airportdb.io/api/v1/airport/${icao}?apiToken=${this.apiToken}`, { method: 'GET' }); if (!response.ok) { @@ -572,55 +597,35 @@ export class AirportService { return null; } const data = (await response.json()) as AirportData; - - const country_code = data.iso_country?.trim().toUpperCase() || data.country?.code?.trim().toUpperCase() || null; - const country_name = data.country?.name?.trim() || null; - const region_name = data.region?.name?.trim() || null; - - if (!country_code && !country_name && !region_name) return null; - - await dbSession.executeWrite('UPDATE airports SET country_code = ?, country_name = ?, region_name = ? WHERE icao = ?', [ - country_code, - country_name, - region_name, - icao, - ]); - - return { country_code, country_name, region_name }; - } catch { - return null; - } - } - - /** - * Fetch elevation from AirportDB and store in database. - * Returns the elevation data if successful, null otherwise. - */ - private async fetchAndStoreElevation( - icao: string, - dbSession: DatabaseSessionService, - ): Promise<{ elevation_ft: number; elevation_m: number } | null> { - try { - const response = await fetch(`https://airportdb.io/api/v1/airport/${icao}?apiToken=${this.apiToken}`, { method: 'GET' }); - if (!response.ok) { - await cancelResponseBody(response); - return null; + const updates: Partial = {}; + const setFragments: string[] = []; + const params: Array = []; + + if (needsLocation) { + const country_code = data.iso_country?.trim().toUpperCase() || data.country?.code?.trim().toUpperCase() || null; + const country_name = data.country?.name?.trim() || null; + const region_name = data.region?.name?.trim() || null; + if (country_code || country_name || region_name) { + Object.assign(updates, { country_code, country_name, region_name }); + setFragments.push('country_code = ?', 'country_name = ?', 'region_name = ?'); + params.push(country_code, country_name, region_name); + } } - const data = (await response.json()) as AirportData; - if (!data.elevation_ft) return null; - - const elevation_ft = parseInt(data.elevation_ft, 10); - if (Number.isNaN(elevation_ft)) return null; - const elevation_m = Math.round(elevation_ft * 0.3048 * 100) / 100; - - await dbSession.executeWrite('UPDATE airports SET elevation_ft = ?, elevation_m = ? WHERE icao = ?', [ - elevation_ft, - elevation_m, - icao, - ]); + if (needsElevation && data.elevation_ft) { + const elevation_ft = parseInt(data.elevation_ft, 10); + if (!Number.isNaN(elevation_ft)) { + const elevation_m = Math.round(elevation_ft * 0.3048 * 100) / 100; + Object.assign(updates, { elevation_ft, elevation_m }); + setFragments.push('elevation_ft = ?', 'elevation_m = ?'); + params.push(elevation_ft, elevation_m); + } + } - return { elevation_ft, elevation_m }; + if (setFragments.length === 0) return null; + params.push(icao); + await dbSession.executeWrite(`UPDATE airports SET ${setFragments.join(', ')} WHERE icao = ?`, params); + return updates; } catch { return null; } diff --git a/src/services/auth.ts b/src/services/auth.ts index b647560..c98cff5 100644 --- a/src/services/auth.ts +++ b/src/services/auth.ts @@ -10,6 +10,10 @@ interface ExistingUserLookup { bookmark: string | null; } +interface WaitUntilContext { + waitUntil(promise: Promise): void; +} + export class AuthService { constructor( private db: D1Database, @@ -17,10 +21,7 @@ export class AuthService { private posthog?: PostHogService, ) {} - private async withDbSession( - operation: (dbSession: DatabaseSessionService) => Promise, - options?: SessionOptions, - ): Promise { + private async withDbSession(operation: (dbSession: DatabaseSessionService) => Promise, options?: SessionOptions): Promise { const dbSession = new DatabaseSessionService(this.db); if (options) { dbSession.startSession(options); @@ -32,13 +33,13 @@ export class AuthService { } } - async handleCallback(code: string, executionCtx?: ExecutionContext): Promise<{ vatsimToken: string }> { + async handleCallback(code: string, executionCtx?: WaitUntilContext): Promise<{ vatsimToken: string }> { const auth = await this.vatsim.getToken(code); const vatsimUser = await this.vatsim.getUser(auth.access_token); if (!vatsimUser.id || !vatsimUser.email) { throw new Error('Invalid VATSIM user data'); } - const [existingUser, banRecord] = await Promise.all([this.fetchExistingUser(vatsimUser.id), this.fetchBanRecord(vatsimUser.id)]); + const { existingUser, banRecord } = await this.fetchLoginState(vatsimUser.id); const backgroundTasks: Promise[] = []; const banned = this.isBanRecordActive(banRecord); @@ -108,9 +109,8 @@ export class AuthService { private generateApiKey(): string { const randomBytes = new Uint8Array(32); crypto.getRandomValues(randomBytes); - const key = Array.from(randomBytes) - .map((b) => b.toString(16).padStart(2, '0')) - .join(''); + let key = ''; + for (const byte of randomBytes) key += byte.toString(16).padStart(2, '0'); return `BARS_${key}`; } @@ -201,16 +201,17 @@ export class AuthService { } async deleteUserAccount(vatsimId: string): Promise { - const deleted = await this.withDbSession(async (dbSession) => { - await dbSession.executeBatch([ - { query: 'DELETE FROM division_members WHERE vatsim_id = ?', params: [vatsimId] }, - { query: 'DELETE FROM staff WHERE user_id IN (SELECT id FROM users WHERE vatsim_id = ?)', params: [vatsimId] }, - { query: 'DELETE FROM users WHERE vatsim_id = ?', params: [vatsimId] }, - ]); - - const userResult = await dbSession.executeRead<{ id: number }>('SELECT id FROM users WHERE vatsim_id = ? LIMIT 1', [vatsimId]); - return !userResult.results[0]; - }, { mode: 'first-primary' }); + const deleted = await this.withDbSession( + async (dbSession) => { + await dbSession.executeBatch([ + { query: 'DELETE FROM division_members WHERE vatsim_id = ?', params: [vatsimId] }, + { query: 'DELETE FROM staff WHERE user_id IN (SELECT id FROM users WHERE vatsim_id = ?)', params: [vatsimId] }, + { query: 'DELETE FROM users WHERE vatsim_id = ?', params: [vatsimId] }, + ]); + return true; + }, + { mode: 'first-primary' }, + ); if (deleted) { try { @@ -239,6 +240,27 @@ export class AuthService { }); } + /** Resolve the real-time connection principal and ban state in one D1 query. */ + async getConnectionPrincipalByApiKey(apiKey: string): Promise<{ user: UserRecord | null; banned: boolean }> { + return this.withDbSession(async (dbSession) => { + const result = await dbSession.executeRead( + `SELECT u.*, + CASE WHEN b.vatsim_id IS NOT NULL + AND (b.expires_at IS NULL OR datetime(b.expires_at) >= datetime('now')) + THEN 1 ELSE 0 END AS is_banned + FROM users u + LEFT JOIN bans b ON b.vatsim_id = u.vatsim_id + WHERE u.api_key = ? + LIMIT 1`, + [apiKey], + ); + const row = result.results[0]; + if (!row) return { user: null, banned: false }; + const { is_banned, ...user } = row; + return { user: user as UserRecord, banned: is_banned === 1 }; + }); + } + async getUserByVatsimId(vatsimId: string): Promise { return this.withDbSession(async (dbSession) => { const result = await dbSession.executeRead( @@ -282,44 +304,53 @@ export class AuthService { async updateDisplayMode(userId: number, mode: number, existing?: DisplayModeUser) { if (![0, 1, 2].includes(mode)) throw new Error('Invalid display mode'); - await this.withDbSession(async (dbSession) => { - let user: DisplayModeUser | null = null; - if (existing && existing.id === userId) { - user = existing; - } else { - const current = await dbSession.executeRead( - 'SELECT id, vatsim_id, full_name, display_mode, display_name FROM users WHERE id = ?', - [userId], - ); - user = current.results[0] ?? null; - } - if (!user) return; - - if (user.display_mode === mode) return; // nothing to do - - const displayName = this.computeDisplayName({ ...user, display_mode: mode } as UserRecord); - - await dbSession.executeWrite('UPDATE users SET display_mode = ?, display_name = ? WHERE id = ?', [mode, displayName, userId]); - }, { mode: 'first-primary' }); + await this.withDbSession( + async (dbSession) => { + let user: DisplayModeUser | null = null; + if (existing && existing.id === userId) { + user = existing; + } else { + const current = await dbSession.executeRead( + 'SELECT id, vatsim_id, full_name, display_mode, display_name FROM users WHERE id = ?', + [userId], + ); + user = current.results[0] ?? null; + } + if (!user) return; + + if (user.display_mode === mode) return; // nothing to do + + const displayName = this.computeDisplayName({ ...user, display_mode: mode } as UserRecord); + + await dbSession.executeWrite('UPDATE users SET display_mode = ?, display_name = ? WHERE id = ?', [ + mode, + displayName, + userId, + ]); + }, + { mode: 'first-primary' }, + ); } async updateFullName(userId: number, fullName: string) { - await this.withDbSession(async (dbSession) => { - await dbSession.executeWrite('UPDATE users SET full_name = ? WHERE id = ?', [fullName, userId]); - // Recompute display_name after updating full_name using existing display_mode - const current = await dbSession.executeRead('SELECT * FROM users WHERE id = ?', [userId]); - const user = current.results[0]; - if (user) { - const vatsimUser: VatsimUser = { - id: user.vatsim_id, - email: user.email, - first_name: fullName.split(' ')[0], - last_name: fullName.split(' ').slice(1).join(' '), - }; - const displayName = this.computeDisplayName(user, vatsimUser); - await dbSession.executeWrite('UPDATE users SET display_name = ? WHERE id = ?', [displayName, userId]); - } - }, { mode: 'first-primary' }); + await this.withDbSession( + async (dbSession) => { + const current = await dbSession.executeLatest( + 'SELECT id, vatsim_id, full_name, display_mode, display_name FROM users WHERE id = ?', + [userId], + ); + const user = current.results[0]; + if (user) { + const displayName = this.computeDisplayName({ ...user, full_name: fullName } as UserRecord); + await dbSession.executeWrite('UPDATE users SET full_name = ?, display_name = ? WHERE id = ?', [ + fullName, + displayName, + userId, + ]); + } + }, + { mode: 'first-primary' }, + ); } private async refreshLoginMetadata(userId: number, vatsimUser: VatsimUser): Promise { @@ -368,30 +399,35 @@ export class AuthService { } async regenerateApiKey(userId: number): Promise { - const apiKey = await this.withDbSession(async (dbSession) => { - let newApiKey = this.generateApiKey(); - - // Make sure the new API key is unique - while (true) { - const existingKeyResult = await dbSession.executeRead('SELECT id FROM users WHERE api_key = ?', [newApiKey]); - - if (!existingKeyResult.results[0]) break; - newApiKey = this.generateApiKey(); - } - - // Update the user's API key in the database - const result = await dbSession.executeWrite('UPDATE users SET api_key = ? WHERE id = ? RETURNING api_key', [ - newApiKey, - userId, - ]); - - const rows = result.results as unknown as Array<{ api_key: string }> | null; - if (!rows || !rows[0]) { - throw new Error('Failed to update API key'); - } - - return rows[0].api_key; - }, { mode: 'first-primary' }); + const apiKey = await this.withDbSession( + async (dbSession) => { + let newApiKey = this.generateApiKey(); + + // Make sure the new API key is unique + while (true) { + const existingKeyResult = await dbSession.executeRead('SELECT id FROM users WHERE api_key = ?', [ + newApiKey, + ]); + + if (!existingKeyResult.results[0]) break; + newApiKey = this.generateApiKey(); + } + + // Update the user's API key in the database + const result = await dbSession.executeWrite('UPDATE users SET api_key = ? WHERE id = ? RETURNING api_key', [ + newApiKey, + userId, + ]); + + const rows = result.results as unknown as Array<{ api_key: string }> | null; + if (!rows || !rows[0]) { + throw new Error('Failed to update API key'); + } + + return rows[0].api_key; + }, + { mode: 'first-primary' }, + ); try { this.posthog?.track('User API Key Regenerated', { userId }); @@ -407,24 +443,30 @@ export class AuthService { /** Create or update a ban for a vatsim id. Account is kept so UI can surface ban. */ async banUser(vatsimId: string, reason: string | null, issuedBy: string, expiresAt?: string | null): Promise { - await this.withDbSession(async (dbSession) => { - const nowIso = new Date().toISOString(); - const cid = String(vatsimId).trim(); - if (!/^\d{3,10}$/.test(cid)) throw new Error('Invalid VATSIM ID format'); - await dbSession.executeWrite( - `INSERT INTO bans (vatsim_id, reason, issued_by, created_at, expires_at) + await this.withDbSession( + async (dbSession) => { + const nowIso = new Date().toISOString(); + const cid = String(vatsimId).trim(); + if (!/^\d{3,10}$/.test(cid)) throw new Error('Invalid VATSIM ID format'); + await dbSession.executeWrite( + `INSERT INTO bans (vatsim_id, reason, issued_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(vatsim_id) DO UPDATE SET reason=excluded.reason, issued_by=excluded.issued_by, created_at=?, expires_at=excluded.expires_at`, - [cid, reason ?? null, issuedBy, nowIso, expiresAt ?? null, nowIso], - ); - }, { mode: 'first-primary' }); + [cid, reason ?? null, issuedBy, nowIso, expiresAt ?? null, nowIso], + ); + }, + { mode: 'first-primary' }, + ); } /** Remove a ban for a vatsim id */ async unbanUser(vatsimId: string): Promise { - await this.withDbSession(async (dbSession) => { - await dbSession.executeWrite('DELETE FROM bans WHERE vatsim_id = ?', [vatsimId]); - }, { mode: 'first-primary' }); + await this.withDbSession( + async (dbSession) => { + await dbSession.executeWrite('DELETE FROM bans WHERE vatsim_id = ?', [vatsimId]); + }, + { mode: 'first-primary' }, + ); } /** List bans */ @@ -463,12 +505,31 @@ export class AuthService { }); } - private async fetchExistingUser(vatsimId: string): Promise { - return this.withDbSession(async (dbSession) => { - const result = await dbSession.executeRead('SELECT * FROM users WHERE vatsim_id = ?', [vatsimId]); - const bookmark = dbSession.getSessionInfo().bookmark; - return { user: result.results[0] ?? null, bookmark }; - }, { mode: 'first-primary' }); + private async fetchLoginState(vatsimId: string): Promise<{ + existingUser: ExistingUserLookup; + banRecord: { vatsim_id: string; expires_at: string | null } | null; + }> { + return this.withDbSession( + async (dbSession) => { + const result = await dbSession.executeRead( + `SELECT u.*, b.vatsim_id AS ban_vatsim_id, b.expires_at AS ban_expires_at + FROM (SELECT 1) anchor + LEFT JOIN users u ON u.vatsim_id = ? + LEFT JOIN bans b ON b.vatsim_id = ? + LIMIT 1`, + [vatsimId, vatsimId], + ); + const row = result.results[0]; + if (!row) throw new Error('Failed to load login state'); + const { ban_vatsim_id, ban_expires_at, ...userFields } = row; + const bookmark = dbSession.getSessionInfo().bookmark; + return { + existingUser: { user: userFields.id == null ? null : (userFields as UserRecord), bookmark }, + banRecord: ban_vatsim_id ? { vatsim_id: ban_vatsim_id, expires_at: ban_expires_at } : null, + }; + }, + { mode: 'first-primary' }, + ); } private async fetchBanRecord(vatsimId: string): Promise<{ vatsim_id: string; expires_at: string | null } | null> { @@ -487,7 +548,7 @@ export class AuthService { return Date.now() <= new Date(record.expires_at).getTime(); } - private dispatchBackgroundTasks(tasks: Promise[], executionCtx?: ExecutionContext) { + private dispatchBackgroundTasks(tasks: Promise[], executionCtx?: WaitUntilContext) { if (tasks.length === 0) return; const combined = Promise.allSettled(tasks).then(() => undefined); if (executionCtx) { diff --git a/src/services/bars/geoUtils.ts b/src/services/bars/geoUtils.ts index 844fe99..c033b5e 100644 --- a/src/services/bars/geoUtils.ts +++ b/src/services/bars/geoUtils.ts @@ -109,28 +109,10 @@ export function generateEquidistantPoints( let startOffset = (totalPathLength - totalSpan) / 2; if (startOffset < 0) startOffset = 0; - const getPointAtDistance = (distance: number): GeoPoint => { - if (distance <= 0) { - return { ...points[0] }; - } - - let remaining = distance; - let segmentIndex = 0; - - while (segmentIndex < segmentLengths.length) { - const length = segmentLengths[segmentIndex]; - if (remaining <= length) { - return calculateDestinationPoint(points[segmentIndex], remaining, segmentBearings[segmentIndex]); - } - remaining -= length; - segmentIndex++; - } - - return { ...points[points.length - 1] }; - }; - const result: GeoPoint[] = []; const EPSILON = 1e-6; + let segmentIndex = 0; + let segmentStartDistance = 0; for (let i = 0; i < pointCount; i++) { const targetDistance = startOffset + i * interval; @@ -139,7 +121,15 @@ export function generateEquidistantPoints( } const clampedDistance = Math.min(targetDistance, totalPathLength); - result.push(getPointAtDistance(clampedDistance)); + if (clampedDistance <= 0) { + result.push({ ...points[0] }); + continue; + } + while (segmentIndex < segmentLengths.length - 1 && clampedDistance - segmentStartDistance > segmentLengths[segmentIndex]) { + segmentStartDistance += segmentLengths[segmentIndex]; + segmentIndex++; + } + result.push(calculateDestinationPoint(points[segmentIndex], clampedDistance - segmentStartDistance, segmentBearings[segmentIndex])); } if (result.length === 0) { diff --git a/src/services/cache.ts b/src/services/cache.ts index 6acabbd..edcbac6 100644 --- a/src/services/cache.ts +++ b/src/services/cache.ts @@ -1,4 +1,13 @@ -const namespaceVersionHints = new Map(); +interface NamespaceVersionHint { + version: number; + checkedAt: number; +} + +// Revalidate periodically so a namespace bump from another isolate cannot leave +// a hot cached entry on an old version indefinitely. +const NAMESPACE_VERSION_FRESH_MS = 5_000; +const namespaceVersionHints = new Map(); +const pendingNamespaceVersionReads = new Map>(); interface CacheOptions { ttl?: number; // Time to live in seconds @@ -10,29 +19,24 @@ interface CacheOptions { * More efficient than KV for short-lived cached data */ export class CacheService { - private namespaceVersionCache = new Map(); - - constructor(private env: Env) {} + constructor(env: Env) { + void env; + } private versionMetaKey(namespace: string): Request { return new Request(`https://cache.stopbars/__version/${namespace}`); } private getCachedNamespaceVersion(namespace: string): number | undefined { - const local = this.namespaceVersionCache.get(namespace); - if (local !== undefined) { - return local; - } const hinted = namespaceVersionHints.get(namespace); - if (hinted !== undefined) { - this.namespaceVersionCache.set(namespace, hinted); + if (hinted && Date.now() - hinted.checkedAt < NAMESPACE_VERSION_FRESH_MS) { + return hinted.version; } - return hinted; + return undefined; } private rememberNamespaceVersion(namespace: string, version: number): number { - this.namespaceVersionCache.set(namespace, version); - namespaceVersionHints.set(namespace, version); + namespaceVersionHints.set(namespace, { version, checkedAt: Date.now() }); return version; } @@ -56,8 +60,21 @@ export class CacheService { return cached; } } - const fresh = await this.fetchNamespaceVersion(namespace); - return this.rememberNamespaceVersion(namespace, fresh); + + const pending = pendingNamespaceVersionReads.get(namespace); + if (pending) { + return pending; + } + + const request = this.fetchNamespaceVersion(namespace).then((fresh) => this.rememberNamespaceVersion(namespace, fresh)); + pendingNamespaceVersionReads.set(namespace, request); + try { + return await request; + } finally { + if (pendingNamespaceVersionReads.get(namespace) === request) { + pendingNamespaceVersionReads.delete(namespace); + } + } } private async setNamespaceVersion(namespace: string, version: number): Promise { @@ -74,6 +91,14 @@ export class CacheService { this.rememberNamespaceVersion(namespace, version); } + private dataKey(key: string, namespace: string, version: number): Request { + return new Request(`https://cache.stopbars/${namespace}/v${version}/${key}`); + } + + private async matchResponse(key: string, namespace: string, version: number): Promise { + return (await caches.default.match(this.dataKey(key, namespace, version))) ?? null; + } + /** Bump and return the new version for a namespace. */ async bumpNamespaceVersion(namespace: string): Promise { const current = await this.resolveNamespaceVersion(namespace, true); @@ -87,40 +112,19 @@ export class CacheService { * @param key - Cache key * @returns Cached data or null if not found */ - async get(key: string, namespace = 'default'): Promise { - const cache = caches.default; - const matchWithVersion = async (version: number): Promise => { - const cacheKey = new Request(`https://cache.stopbars/${namespace}/v${version}/${key}`); - const cachedResponse = await cache.match(cacheKey); - - if (!cachedResponse) { - return null; - } - - try { - return await cachedResponse.json(); - } catch { - return null; - } - }; - - const hintedVersion = this.getCachedNamespaceVersion(namespace); - if (hintedVersion !== undefined) { - const hintedHit = await matchWithVersion(hintedVersion); - if (hintedHit !== null) { - return hintedHit; - } - - const refreshedVersion = await this.resolveNamespaceVersion(namespace, true); - if (refreshedVersion !== hintedVersion) { - return await matchWithVersion(refreshedVersion); - } + async getResponse(key: string, namespace = 'default'): Promise { + const version = await this.resolveNamespaceVersion(namespace); + return this.matchResponse(key, namespace, version); + } + async get(key: string, namespace = 'default'): Promise { + const cachedResponse = await this.getResponse(key, namespace); + if (!cachedResponse) return null; + try { + return await cachedResponse.json(); + } catch { return null; } - - const ver = await this.resolveNamespaceVersion(namespace); - return await matchWithVersion(ver); } /** @@ -134,7 +138,7 @@ export class CacheService { // Versioned cache key with namespace const ver = await this.resolveNamespaceVersion(namespace); - const cacheKey = new Request(`https://cache.stopbars/${namespace}/v${ver}/${key}`); + const cacheKey = this.dataKey(key, namespace, ver); // Create response with the data const response = new Response(JSON.stringify(data), { @@ -149,6 +153,24 @@ export class CacheService { await cache.put(cacheKey, response); } + /** Store an existing response without parsing and serializing its body. */ + async setResponse(key: string, response: Response, options: CacheOptions = {}): Promise { + const { ttl = 60, namespace = 'default' } = options; + const ver = await this.resolveNamespaceVersion(namespace); + const headers = new Headers(response.headers); + headers.set('Cache-Control', `max-age=${ttl}`); + headers.delete('Set-Cookie'); + headers.delete('X-Cache'); + await caches.default.put( + this.dataKey(key, namespace, ver), + new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }), + ); + } + /** * Delete data from cache * @param key - Cache key @@ -156,7 +178,7 @@ export class CacheService { */ async delete(key: string, namespace = 'default'): Promise { const ver = await this.resolveNamespaceVersion(namespace); - const cacheKey = new Request(`https://cache.stopbars/${namespace}/v${ver}/${key}`); + const cacheKey = this.dataKey(key, namespace, ver); const cache = caches.default; await cache.delete(cacheKey); } @@ -175,6 +197,7 @@ export function withCache( namespace: string = 'default', shouldBypass?: (req: Request) => boolean, ) { + let cacheService: CacheService | undefined; return async (c: import('hono').Context<{ Bindings: Env }>, next: () => Promise) => { // Skip caching for non-GET requests if (c.req.method !== 'GET') { @@ -185,15 +208,18 @@ export function withCache( return next(); } - const cacheService = new CacheService(c.env); + cacheService ??= new CacheService(c.env); const cacheKey = cacheKeyFn(c.req.raw); // Try to get from cache - const cachedData = await cacheService.get(cacheKey, namespace); - if (cachedData) { - // Set header to indicate cache hit - c.header('X-Cache', 'HIT'); - return c.json(cachedData); + const cachedResponse = await cacheService.getResponse(cacheKey, namespace); + if (cachedResponse) { + const response = new Response(cachedResponse.body, cachedResponse); + // Cache-Control governs the internal Cache API entry. Do not expose it to + // browser caches, which cannot vary user-scoped entries by our private key. + response.headers.delete('Cache-Control'); + response.headers.set('X-Cache', 'HIT'); + return response; } // Cache miss, proceed to handler @@ -204,15 +230,18 @@ export function withCache( // Don't cache error responses (4xx, 5xx) including 404 Not Found if (c.res && c.res.status >= 200 && c.res.status < 300) { try { - // Clone the response to read it without consuming the original - const clonedRes = c.res.clone(); - const contentType = clonedRes.headers.get('content-type'); - - // Only cache JSON responses - if (contentType && contentType.includes('application/json')) { - const data = await clonedRes.json(); - // Cache the data - await cacheService.set(cacheKey, data, { ttl, namespace }); + const contentType = c.res.headers.get('content-type'); + if ( + contentType?.includes('application/json') || + contentType?.includes('application/xml') || + contentType?.includes('text/xml') + ) { + const cacheWrite = cacheService.setResponse(cacheKey, c.res.clone(), { ttl, namespace }); + try { + c.executionCtx.waitUntil(cacheWrite); + } catch { + await cacheWrite; + } } } catch { // Silently fail if we can't cache @@ -233,11 +262,16 @@ export const CacheKeys = { const url = new URL(req.url); // Normalize path and sort params to avoid cache key ambiguity/poisoning const path = url.pathname.replace(/[^A-Za-z0-9/_-]/g, ''); - const params = Array.from(url.searchParams.entries()) - .filter(([k]) => !/^auth(orization)?$/i.test(k)) - .sort(([a], [b]) => a.localeCompare(b)) - .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) - .join('&'); + const entries: Array<[string, string]> = []; + for (const [key, value] of url.searchParams) { + if (!/^auth(orization)?$/i.test(key)) entries.push([key, value]); + } + entries.sort(([left], [right]) => left.localeCompare(right)); + let params = ''; + for (const [key, value] of entries) { + if (params) params += '&'; + params += `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } return params ? `${path}?${params}` : path; }, diff --git a/src/services/contact.ts b/src/services/contact.ts index 379f0c7..1690645 100644 --- a/src/services/contact.ts +++ b/src/services/contact.ts @@ -22,9 +22,9 @@ export class ContactService { try { const data = new TextEncoder().encode(ip || '0.0.0.0'); const digest = await crypto.subtle.digest('SHA-256', data); - return Array.from(new Uint8Array(digest)) - .map((b) => b.toString(16).padStart(2, '0')) - .join(''); + let hex = ''; + for (const byte of new Uint8Array(digest)) hex += byte.toString(16).padStart(2, '0'); + return hex; } catch { return (ip || '0.0.0.0').slice(0, 128); } @@ -33,26 +33,20 @@ export class ContactService { async createMessage(email: string, topic: string, message: string, ip: string): Promise { const id = crypto.randomUUID(); const ipHash = await this.hashIp(ip); - await this.dbSession.executeWrite( - `INSERT INTO contact_messages (id, email, topic, message, ip_address, status, created_at) VALUES (?, ?, ?, ?, ?, 'pending', datetime('now'))`, + const result = await this.dbSession.executeWrite( + `INSERT INTO contact_messages (id, email, topic, message, ip_address, status, created_at) + VALUES (?, ?, ?, ?, ?, 'pending', datetime('now')) + RETURNING id, email, topic, message, ip_address, status, handled_by, handled_at, created_at`, [id, email, topic, message, ipHash], ); - const created = await this.getMessage(id); + const created = (result.results as unknown as ContactMessageRecord[] | null)?.[0]; if (!created) throw new Error('Failed to create contact message'); return created; } - async getMessage(id: string): Promise { - const res = await this.dbSession.executeRead( - `SELECT id, email, topic, message, ip_address, status, handled_by, handled_at, created_at FROM contact_messages WHERE id = ?`, - [id], - ); - return res.results[0] || null; - } - async listMessages(): Promise { const res = await this.dbSession.executeRead( - `SELECT id, email, topic, message, ip_address, status, handled_by, handled_at, created_at FROM contact_messages ORDER BY datetime(created_at) DESC`, + `SELECT id, email, topic, message, ip_address, status, handled_by, handled_at, created_at FROM contact_messages ORDER BY created_at DESC`, [], ); return res.results; @@ -64,26 +58,31 @@ export class ContactService { handlerVatsimId: string, ): Promise { // handled_by/handled_at only set when moving to handled, if returning to pending/handling clear handled_at but keep who last handled - if (status === 'handled') { - await this.dbSession.executeWrite( - `UPDATE contact_messages SET status = ?, handled_by = ?, handled_at = datetime('now') WHERE id = ?`, - [status, handlerVatsimId, id], - ); - } else { - await this.dbSession.executeWrite(`UPDATE contact_messages SET status = ?, handled_at = NULL WHERE id = ?`, [status, id]); - } - return this.getMessage(id); + const result = await this.dbSession.executeWrite( + `UPDATE contact_messages + SET status = ?, + handled_by = CASE WHEN ? = 'handled' THEN ? ELSE handled_by END, + handled_at = CASE WHEN ? = 'handled' THEN datetime('now') ELSE NULL END + WHERE id = ? + RETURNING id, email, topic, message, ip_address, status, handled_by, handled_at, created_at`, + [status, status, handlerVatsimId, status, id], + ); + return (result.results as unknown as ContactMessageRecord[] | null)?.[0] ?? null; } async deleteMessage(id: string): Promise { - const res = await this.dbSession.executeWrite(`DELETE FROM contact_messages WHERE id = ?`, [id]); - return !!res.success; + const result = await this.dbSession.executeWrite(`DELETE FROM contact_messages WHERE id = ? RETURNING id`, [id]); + return Boolean((result.results as unknown as Array<{ id: string }> | null)?.[0]); } async hasRecentSubmissionFromIp(ip: string, withinHours = 24): Promise { const ipHash = await this.hashIp(ip); const res = await this.dbSession.executeRead<{ cnt: number }>( - `SELECT COUNT(*) as cnt FROM contact_messages WHERE ip_address IN (?, ?) AND datetime(created_at) >= datetime('now', ?)`, + `SELECT EXISTS( + SELECT 1 FROM contact_messages + WHERE ip_address IN (?, ?) AND created_at >= datetime('now', ?) + LIMIT 1 + ) AS cnt`, [ip, ipHash, `-${withinHours} hours`], ); return (res.results[0]?.cnt || 0) > 0; diff --git a/src/services/contributions.ts b/src/services/contributions.ts index a510ff4..4d7ddd1 100644 --- a/src/services/contributions.ts +++ b/src/services/contributions.ts @@ -1,4 +1,4 @@ -import { RoleService, StaffRole } from './roles'; +import { RoleService } from './roles'; import { AirportService } from './airport'; import { StorageService } from './storage'; import { SupportService } from './support'; @@ -53,6 +53,11 @@ export interface ContributionListResult { total: number; } +export interface LatestApprovedMapDescriptor { + packageName: string; + simulator: Simulator; +} + import { DatabaseSessionService } from './database-session'; export const MAX_CONTRIBUTION_NOTES_CHARS = 1000; @@ -89,13 +94,13 @@ interface StoredContributionGenerationRow { export type ContributionGenerationLookupResult = | { - status: 'ok'; - token: string; - icao: string; - supportsXml: string; - barsXml: string; - expiresAt: string; - } + status: 'ok'; + token: string; + icao: string; + supportsXml: string; + barsXml: string; + expiresAt: string; + } | { status: 'invalid-token' } | { status: 'not-found' } | { status: 'payload-not-found' }; @@ -110,7 +115,7 @@ export class ContributionService { constructor( private db: D1Database, - private roleService: RoleService, + _roleService: RoleService, apiKey: string, private storage: R2Bucket, private posthog?: PostHogService, @@ -123,6 +128,64 @@ export class ContributionService { this.dbSession = new DatabaseSessionService(db); } + private async getContributionActionContext( + vatsimId: string, + contributionId: string, + ): Promise<{ isProductManager: boolean; contribution: Contribution | null } | null> { + const result = await this.dbSession.executeLatest( + `SELECT + c.id, c.user_id AS userId, submitter.display_name AS userDisplayName, + c.airport_icao AS airportIcao, c.package_name AS packageName, + c.submitted_xml AS submittedXml, c.notes, c.simulator, + c.submission_date AS submissionDate, c.status, + c.rejection_reason AS rejectionReason, c.decision_date AS decisionDate, + CASE WHEN staff.role IN ('LEAD_DEVELOPER', 'PRODUCT_MANAGER') THEN 1 ELSE 0 END AS actorIsProductManager + FROM users actor + LEFT JOIN staff ON staff.user_id = actor.id + LEFT JOIN contributions c ON c.id = ? + LEFT JOIN users submitter ON submitter.vatsim_id = c.user_id + WHERE actor.vatsim_id = ? + LIMIT 1`, + [contributionId, vatsimId], + ); + const row = result.results[0]; + if (!row) return null; + const { actorIsProductManager, ...contribution } = row; + return { + isProductManager: actorIsProductManager === 1, + contribution: contribution.id ? contribution : null, + }; + } + + private async getContributionDeleteContext( + vatsimId: string, + contributionId: string, + ): Promise<{ + isProductManager: boolean; + contribution: Pick | null; + } | null> { + const result = await this.dbSession.executeLatest< + Pick & { actorIsProductManager: number } + >( + `SELECT + c.id, c.user_id AS userId, c.status, c.simulator, + CASE WHEN staff.role IN ('LEAD_DEVELOPER', 'PRODUCT_MANAGER') THEN 1 ELSE 0 END AS actorIsProductManager + FROM users actor + LEFT JOIN staff ON staff.user_id = actor.id + LEFT JOIN contributions c ON c.id = ? + WHERE actor.vatsim_id = ? + LIMIT 1`, + [contributionId, vatsimId], + ); + const row = result.results[0]; + if (!row) return null; + const { actorIsProductManager, ...contribution } = row; + return { + isProductManager: actorIsProductManager === 1, + contribution: contribution.id ? contribution : null, + }; + } + private async insertContributionGenerationRow( session: ReturnType, token: string, @@ -172,24 +235,30 @@ export class ContributionService { try { let expiredKeys: string[] = []; try { - const expired = await session.executeLatest>( - "SELECT supports_key, bars_key FROM contribution_generations WHERE expires_at <= datetime('now')", + const [expired] = await session.executeBatch([ + { query: "SELECT supports_key, bars_key FROM contribution_generations WHERE expires_at <= datetime('now')" }, + { query: "DELETE FROM contribution_generations WHERE expires_at <= datetime('now')" }, + ]); + expiredKeys = (expired.results as Array>).flatMap( + (row) => [row.supports_key, row.bars_key].filter((key): key is string => Boolean(key)), ); - expiredKeys = expired.results.flatMap((row) => [row.supports_key, row.bars_key].filter((key): key is string => Boolean(key))); } catch (error) { const message = error instanceof Error ? error.message.toLowerCase() : ''; if (!message.includes('no such column')) { throw error; } - const expired = await session.executeLatest>( - "SELECT supports_xml, bars_xml FROM contribution_generations WHERE expires_at <= datetime('now')", + const [expired] = await session.executeBatch([ + { query: "SELECT supports_xml, bars_xml FROM contribution_generations WHERE expires_at <= datetime('now')" }, + { query: "DELETE FROM contribution_generations WHERE expires_at <= datetime('now')" }, + ]); + expiredKeys = (expired.results as Array>).flatMap( + (row) => [row.supports_xml, row.bars_xml].filter((key): key is string => Boolean(key)), ); - expiredKeys = expired.results.flatMap((row) => [row.supports_xml, row.bars_xml].filter((key): key is string => Boolean(key))); } - - await session.executeWrite("DELETE FROM contribution_generations WHERE expires_at <= datetime('now')"); - await Promise.all(expiredKeys.filter((key) => key.startsWith('contribution-generations/')).map((key) => this.storage.delete(key))); + await Promise.all( + expiredKeys.filter((key) => key.startsWith('contribution-generations/')).map((key) => this.storage.delete(key)), + ); } catch (error) { try { console.warn('[Cron] Failed to clean up contribution_generations:', error instanceof Error ? error.message : error); @@ -207,17 +276,19 @@ export class ContributionService { const session = DatabaseContextFactory.createSessionService(this.db); try { - await session.executeWrite("DELETE FROM contribution_generations WHERE token = ? AND expires_at <= datetime('now')", [token]); - - const existing = await session.executeLatest<{ one: number }>( - ` - SELECT 1 AS one FROM contribution_generations - WHERE token = ? AND expires_at > datetime('now') - LIMIT 1 - `, - [token], - ); - if (existing.results[0]) { + const [, existing] = await session.executeBatch([ + { + query: "DELETE FROM contribution_generations WHERE token = ? AND expires_at <= datetime('now')", + params: [token], + }, + { + query: `SELECT 1 AS one FROM contribution_generations + WHERE token = ? AND expires_at > datetime('now') + LIMIT 1`, + params: [token], + }, + ]); + if ((existing.results as Array<{ one: number }> | undefined)?.[0]) { return token; } @@ -477,29 +548,23 @@ export class ContributionService { * @param packageName Package name (case-insensitive) * @param simulator Optional simulator filter - if not provided, returns latest across all simulators */ - async getLatestApprovedContributionForAirportPackage( + async getLatestApprovedMapDescriptor( airportIcao: string, packageName: string, simulator?: Simulator, - ): Promise { + ): Promise { const params: string[] = [airportIcao, packageName]; let simulatorClause = ''; if (simulator) { simulatorClause = ' AND c.simulator = ?'; params.push(simulator); } - const result = await this.dbSession.executeRead( + const result = await this.dbSession.executeRead( ` - SELECT - c.id, c.user_id as userId, u.display_name as userDisplayName, - c.airport_icao as airportIcao, c.package_name as packageName, - c.submitted_xml as submittedXml, c.notes, c.simulator, - c.submission_date as submissionDate, c.status, - c.rejection_reason as rejectionReason, c.decision_date as decisionDate + SELECT c.package_name AS packageName, c.simulator FROM contributions c - LEFT JOIN users u ON u.vatsim_id = c.user_id WHERE c.airport_icao = ? AND lower(c.package_name) = lower(?) AND c.status = 'approved'${simulatorClause} - ORDER BY datetime(c.decision_date) DESC + ORDER BY c.decision_date DESC LIMIT 1 `, params, @@ -603,21 +668,18 @@ export class ContributionService { } async processDecision(id: string, userId: string, decision: ContributionDecision): Promise { - const userInfoResult = await this.dbSession.executeRead<{ id: number }>('SELECT id FROM users WHERE vatsim_id = ?', [userId]); - const userInfo = userInfoResult.results[0]; + const context = await this.getContributionActionContext(userId, id); - if (!userInfo) { + if (!context) { throw new Error('User not found'); } - const hasPermission = await this.roleService.hasPermission(userInfo.id, StaffRole.PRODUCT_MANAGER); - - if (!hasPermission) { + if (!context.isProductManager) { throw new Error('Not authorized to make decisions on contributions'); } // Get the contribution to make sure it exists and is pending - const contribution = await this.getContribution(id); + const contribution = context.contribution; if (!contribution) { throw new Error('Contribution not found'); @@ -635,20 +697,30 @@ export class ContributionService { // Update contribution with decision const now = new Date().toISOString(); - const status = decision.approved ? 'approved' : 'rejected'; // If approving, mark any existing approved contributions for the same airport, package, and simulator as outdated + const status = decision.approved ? 'approved' : 'rejected'; + const rejectionReason = decision.approved ? null : decision.rejectionReason || 'No reason provided'; + const updateCurrent = { + query: `UPDATE contributions + SET status = ?, rejection_reason = ?, decision_date = ?, package_name = ? + WHERE id = ?`, + params: [status, rejectionReason, now, packageName, id], + }; + + // If approving, atomically outdate older approvals and publish this one. if (decision.approved) { - await this.dbSession.executeWrite( - ` - UPDATE contributions - SET status = 'outdated', decision_date = ? - WHERE airport_icao = ? - AND package_name = ? - AND simulator = ? - AND status = 'approved' - AND id != ? - `, - [now, contribution.airportIcao, packageName, contribution.simulator, id], - ); + await this.dbSession.executeBatch([ + { + query: `UPDATE contributions + SET status = 'outdated', decision_date = ? + WHERE airport_icao = ? + AND package_name = ? + AND simulator = ? + AND status = 'approved' + AND id != ?`, + params: [now, contribution.airportIcao, packageName, contribution.simulator, id], + }, + updateCurrent, + ]); // Generate and upload the XML files to CDN try { @@ -690,21 +762,15 @@ export class ContributionService { } catch { // Don't throw the error, as we still want to update the contribution status } + } else { + await this.dbSession.executeWrite(updateCurrent.query, updateCurrent.params); } - await this.dbSession.executeWrite( - ` - UPDATE contributions - SET status = ?, rejection_reason = ?, decision_date = ?, package_name = ? - WHERE id = ? - `, - [status, decision.approved ? null : decision.rejectionReason || 'No reason provided', now, packageName, id], - ); const updated: Contribution = { ...contribution, packageName, status, - rejectionReason: decision.approved ? null : decision.rejectionReason || 'No reason provided', + rejectionReason, decisionDate: now, }; try { @@ -766,17 +832,16 @@ export class ContributionService { }; } async deleteContribution(id: string, userId: string): Promise { - const userInfoResult = await this.dbSession.executeRead<{ id: number }>('SELECT id FROM users WHERE vatsim_id = ?', [userId]); - const userInfo = userInfoResult.results[0]; - if (!userInfo) { + const context = await this.getContributionDeleteContext(userId, id); + if (!context) { throw new Error('User not found'); } // Fetch contribution to validate existence/ownership - const existing = await this.getContribution(id); + const existing = context.contribution; if (!existing) { return false; // not found } - const isStaff = await this.roleService.hasPermission(userInfo.id, StaffRole.PRODUCT_MANAGER); + const isStaff = context.isProductManager; const isOwner = existing.userId === userId; const isDeletableStatus = existing.status === 'pending' || existing.status === 'rejected'; const canDelete = isDeletableStatus && (isStaff || isOwner); @@ -804,24 +869,22 @@ export class ContributionService { id: string, requestedByVatsimId: string, ): Promise<{ + airportIcao: string; + packageName: string; maps: { key: string; etag: string }; supports: { key: string; etag: string }; }> { // Resolve local user and permissions - const userInfoResult = await this.dbSession.executeRead<{ id: number }>('SELECT id FROM users WHERE vatsim_id = ?', [ - requestedByVatsimId, - ]); - const userInfo = userInfoResult.results[0]; - if (!userInfo) { + const context = await this.getContributionActionContext(requestedByVatsimId, id); + if (!context) { throw new Error('User not found'); } - const allowed = await this.roleService.hasPermission(userInfo.id, StaffRole.PRODUCT_MANAGER); - if (!allowed) { + if (!context.isProductManager) { throw new Error('Not authorized to regenerate contributions'); } // Load contribution - const contribution = await this.getContribution(id); + const contribution = context.contribution; if (!contribution) { throw new Error('Contribution not found'); } @@ -872,6 +935,8 @@ export class ContributionService { } return { + airportIcao: contribution.airportIcao, + packageName: contribution.packageName, maps: { key: barsRes.key, etag: barsRes.etag }, supports: { key: supportsRes.key, etag: supportsRes.etag }, }; diff --git a/src/services/database-session.ts b/src/services/database-session.ts index ee19d11..5d3be89 100644 --- a/src/services/database-session.ts +++ b/src/services/database-session.ts @@ -18,11 +18,16 @@ export interface SessionOptions { export interface DatabaseMeta { served_by_region?: string; served_by_primary?: boolean; + served_by_colo?: string; duration?: number; + rows_read?: number; + rows_written?: number; changes?: number; last_row_id?: number; changed_db?: boolean; size_after?: number; + timings?: { sql_duration_ms: number }; + total_attempts?: number; } export interface DatabaseResult { @@ -255,6 +260,38 @@ export class DatabaseSessionService { } } + /** + * Execute independent read statements in one D1 round trip. Unlike the + * write-oriented executeBatch(), a new session may start on the nearest + * unconstrained replica unless a bookmark is supplied. + */ + public async executeReadBatch( + statements: Array<{ query: string; params?: DatabaseSerializable[] }>, + bookmark?: string, + ): Promise[]> { + if (statements.length === 0) return []; + if (!this.session) { + this.startSession(bookmark ? { bookmark } : { mode: 'first-unconstrained' }); + } + + try { + const preparedStatements = statements.map(({ query, params = [] }) => { + const stmt = this.session!.prepare(query); + return params.length > 0 ? stmt.bind(...params) : stmt; + }); + const results = await this.session!.batch(preparedStatements); + this.getBookmark(); + return results.map((result) => ({ + results: result.results ?? [], + success: result.success, + meta: result.meta ?? {}, + })); + } catch (error) { + console.error('Database read batch error:', error); + throw error; + } + } + /** * Execute a read-only query optimized for performance * Uses unconstrained mode for best performance @@ -275,7 +312,11 @@ export class DatabaseSessionService { * Uses primary mode to ensure fresh data */ public async executeLatest(query: string, params: DatabaseSerializable[] = []): Promise> { - return this.executeAll(query, params, { mode: 'first-primary' }); + // A prior unconstrained read may already have opened this service's session. + // Start a fresh primary-anchored session so this method keeps its freshness + // guarantee regardless of which operation ran first. + this.startSession({ mode: 'first-primary' }); + return this.executeAll(query, params); } /** diff --git a/src/services/divisions.ts b/src/services/divisions.ts index 82b6e23..bae29ef 100644 --- a/src/services/divisions.ts +++ b/src/services/divisions.ts @@ -105,17 +105,11 @@ export class DivisionService { da.status, da.requested_by, da.approved_by, - CASE - WHEN po.airport_id IS NOT NULL THEN 1 - ELSE 0 - END AS has_objects, + EXISTS(SELECT 1 FROM points p WHERE p.airport_id = da.icao LIMIT 1) AS has_objects, da.contributions_enabled, da.created_at, da.updated_at FROM division_airports da - LEFT JOIN ( - SELECT DISTINCT airport_id FROM points - ) po ON po.airport_id = da.icao WHERE da.division_id = ? AND da.id = ? LIMIT 1`, [divisionId, airportId], @@ -209,11 +203,6 @@ export class DivisionService { } async addMember(divisionId: number, vatsimId: string, role: 'nav_head' | 'nav_member'): Promise { - const existingRole = await this.getMemberRole(divisionId, vatsimId); - if (existingRole) { - throw new HttpError(409, 'User is already a member of this division'); - } - try { const result = await this.dbSession.executeWrite( 'INSERT INTO division_members (division_id, vatsim_id, role) VALUES (?, ?, ?) RETURNING *', @@ -456,18 +445,12 @@ export class DivisionService { da.status, da.requested_by, da.approved_by, - CASE - WHEN po.airport_id IS NOT NULL THEN 1 - ELSE 0 - END AS has_objects, + EXISTS(SELECT 1 FROM points p WHERE p.airport_id = da.icao LIMIT 1) AS has_objects, da.contributions_enabled, da.created_at, da.updated_at FROM divisions d LEFT JOIN division_airports da ON da.division_id = d.id - LEFT JOIN ( - SELECT DISTINCT airport_id FROM points - ) po ON po.airport_id = da.icao WHERE d.id = ? ORDER BY da.created_at DESC`, [divisionId], @@ -477,9 +460,7 @@ export class DivisionService { return null; } - return result.results - .map((row) => this.mapDivisionAirportRow(row)) - .filter((row): row is DivisionAirport => row !== null); + return result.results.map((row) => this.mapDivisionAirportRow(row)).filter((row): row is DivisionAirport => row !== null); } async getAllDivisionAirports(): Promise { @@ -496,18 +477,12 @@ export class DivisionService { da.status, da.requested_by, da.approved_by, - CASE - WHEN po.airport_id IS NOT NULL THEN 1 - ELSE 0 - END AS has_objects, + EXISTS(SELECT 1 FROM points p WHERE p.airport_id = da.icao LIMIT 1) AS has_objects, da.contributions_enabled, da.created_at, da.updated_at FROM division_airports da JOIN divisions d ON d.id = da.division_id - LEFT JOIN ( - SELECT DISTINCT airport_id FROM points - ) po ON po.airport_id = da.icao ORDER BY d.name ASC, da.created_at DESC`, ); @@ -638,7 +613,8 @@ export class DivisionService { SELECT da.id FROM division_airports da JOIN division_members dm ON da.division_id = dm.division_id - WHERE dm.vatsim_id = ? AND da.icao = ? AND da.status = 'approved' + WHERE dm.vatsim_id = ? AND da.icao = ? AND da.status = 'approved' + LIMIT 1 `, [userId, airportIcao], ); diff --git a/src/services/downloads.ts b/src/services/downloads.ts index 658d953..b96a154 100644 --- a/src/services/downloads.ts +++ b/src/services/downloads.ts @@ -33,129 +33,89 @@ export class DownloadsService { try { const data = new TextEncoder().encode(ip); const digest = await crypto.subtle.digest('SHA-256', data); - return Array.from(new Uint8Array(digest)) - .map((b) => b.toString(16).padStart(2, '0')) - .join(''); + let hex = ''; + for (const byte of new Uint8Array(digest)) hex += byte.toString(16).padStart(2, '0'); + return hex; } catch { return ip.slice(0, 128); } } - private async ensureDownloadRow(product: InstallerProduct, version: string): Promise { - const insertRes = await this.dbSession.executeWrite( - `INSERT INTO downloads (product, version, total_count) - VALUES (?, ?, 0) - ON CONFLICT(product, version) DO UPDATE SET total_count = total_count - RETURNING id, product, version, total_count, created_at, updated_at`, - [product, version], - ); - const rows = insertRes.results as unknown as DownloadRow[] | null; - if (rows && rows[0]) return rows[0]; - const fallback = await this.dbSession.executeRead( - 'SELECT * FROM downloads WHERE product = ? AND version = ? LIMIT 1', - [product, version], - ); - return fallback.results[0]; - } - /** * Records a download if this IP hasn't been counted for the product/version in the last 24h. * Uses separate download_ip_hits table for per-IP tracking with automatic cleanup. */ - async recordDownload(product: InstallerProduct, version: string, ip: string): Promise<{ versionCount: number; productTotal: number }> { - const row = await this.ensureDownloadRow(product, version); + async recordDownload( + product: InstallerProduct, + version: string, + ip: string, + ): Promise<{ versionCount: number; productTotal: number; versions: VersionDownloadStats[] }> { const ipHash = await this.hashIp(ip || '0.0.0.0'); - - // Fetch existing hit - const hitRes = await this.dbSession.executeRead<{ last_seen: string }>( - 'SELECT last_seen FROM download_ip_hits WHERE product = ? AND version = ? AND ip_hash = ? LIMIT 1', - [product, version, ipHash], - ); - const existingHit = hitRes.results[0]; - let shouldIncrement = false; - if (!existingHit) { - shouldIncrement = true; - await this.dbSession.executeWrite( - `INSERT INTO download_ip_hits (product, version, ip_hash, last_seen) VALUES (?,?,?,CURRENT_TIMESTAMP)`, - [product, version, ipHash], - ); - } else { - // Check if older than window - const lastSeen = Date.parse(existingHit.last_seen); - if (Number.isFinite(lastSeen)) { - const ageMs = Date.now() - lastSeen; - if (ageMs > DownloadsService.IP_UNIQUENESS_WINDOW_HOURS * 3600 * 1000) { - shouldIncrement = true; - } - } - if (shouldIncrement) { - await this.dbSession.executeWrite( - `UPDATE download_ip_hits SET last_seen = CURRENT_TIMESTAMP WHERE product = ? AND version = ? AND ip_hash = ?`, - [product, version, ipHash], - ); - } - } - - if (shouldIncrement) { - const updated = await this.dbSession.executeWrite( - `UPDATE downloads - SET total_count = total_count + 1, updated_at = CURRENT_TIMESTAMP - WHERE id = ? - RETURNING total_count AS version_count, - (SELECT SUM(total_count) FROM downloads WHERE product = ?) AS product_total`, - [row.id, product], - ); - const updatedRows = updated.results as unknown as Array<{ version_count: number; product_total: number | null }> | null; - const newCounts = updatedRows && updatedRows[0]; - // Best-effort cleanup (remove outdated hits > 24h). Lightweight single statement. - try { - await this.dbSession.executeWrite( - `DELETE FROM download_ip_hits WHERE last_seen <= datetime('now', '-${DownloadsService.IP_UNIQUENESS_WINDOW_HOURS} hour')`, - ); - } catch { - /* ignore cleanup errors */ - } - if (newCounts) { - return { - versionCount: newCounts.version_count, - productTotal: newCounts.product_total ?? newCounts.version_count, - }; - } - return this.fetchCounts(product, version); - } else { - // No increment; return existing counts - return this.fetchCounts(product, version); - } - } - - private async fetchCounts(product: InstallerProduct, version: string): Promise<{ versionCount: number; productTotal: number }> { - const statsRes = await this.dbSession.executeRead<{ - version_count: number; - product_total: number | null; - }>( - `WITH product_totals AS ( - SELECT product, SUM(total_count) AS product_total - FROM downloads - WHERE product = ? - GROUP BY product - ) - SELECT d.total_count AS version_count, product_totals.product_total - FROM downloads d - LEFT JOIN product_totals ON product_totals.product = d.product - WHERE d.product = ? AND d.version = ? - LIMIT 1`, - [product, product, version], - ); - const row = statsRes.results[0]; - if (row) { - const fallbackTotal = row.product_total ?? row.version_count; + const initial = await this.dbSession.executeBatch([ + { + query: `INSERT INTO downloads (product, version, total_count) + VALUES (?, ?, 0) + ON CONFLICT(product, version) DO UPDATE SET product = excluded.product + RETURNING id`, + params: [product, version], + }, + { + query: `INSERT INTO download_ip_hits (product, version, ip_hash, last_seen) + VALUES (?, ?, ?, CURRENT_TIMESTAMP) + ON CONFLICT(product, version, ip_hash) DO UPDATE SET last_seen = CURRENT_TIMESTAMP + WHERE download_ip_hits.last_seen <= datetime('now', '-${DownloadsService.IP_UNIQUENESS_WINDOW_HOURS} hour') + RETURNING 1 AS should_increment`, + params: [product, version, ipHash], + }, + { + query: `SELECT version, total_count + FROM downloads + WHERE product = ? + ORDER BY created_at DESC`, + params: [product], + }, + ]); + const shouldIncrement = Boolean((initial[1]?.results as Array<{ should_increment: number }> | undefined)?.[0]); + const initialVersions = (initial[2]?.results as Array<{ version: string; total_count: number }> | undefined) ?? []; + const mapVersions = (rows: Array<{ version: string; total_count: number }>): VersionDownloadStats[] => + rows.map((row) => ({ version: row.version, count: row.total_count })); + if (!shouldIncrement) { + const versions = mapVersions(initialVersions); return { - versionCount: row.version_count, - productTotal: fallbackTotal, + versionCount: versions.find((item) => item.version === version)?.count ?? 0, + productTotal: versions.reduce((sum, item) => sum + item.count, 0), + versions, }; } - const ensured = await this.ensureDownloadRow(product, version); - return { versionCount: ensured.total_count, productTotal: ensured.total_count }; + + const [, , updatedVersionRows] = await this.dbSession.executeBatch([ + { + query: `UPDATE downloads + SET total_count = total_count + 1, updated_at = CURRENT_TIMESTAMP + WHERE product = ? AND version = ? + RETURNING total_count AS version_count`, + params: [product, version], + }, + { + query: `DELETE FROM download_ip_hits + WHERE last_seen <= datetime('now', '-${DownloadsService.IP_UNIQUENESS_WINDOW_HOURS} hour')`, + }, + { + query: `SELECT version, total_count + FROM downloads + WHERE product = ? + ORDER BY created_at DESC`, + params: [product], + }, + ]); + const versions = mapVersions( + (updatedVersionRows.results as Array<{ version: string; total_count: number }> | undefined) ?? initialVersions, + ); + return { + versionCount: versions.find((item) => item.version === version)?.count ?? 0, + productTotal: versions.reduce((sum, item) => sum + item.count, 0), + versions, + }; } async getStats(product: InstallerProduct): Promise { diff --git a/src/services/faqs.ts b/src/services/faqs.ts index 3b577ff..e555268 100644 --- a/src/services/faqs.ts +++ b/src/services/faqs.ts @@ -17,7 +17,7 @@ export class FAQService { async list(): Promise<{ faqs: FAQRecord[]; total: number }> { const result = await this.dbSession.executeRead( - `SELECT id, question, answer, order_position, created_at, updated_at FROM faqs ORDER BY order_position ASC, datetime(created_at) ASC`, + `SELECT id, question, answer, order_position, created_at, updated_at FROM faqs ORDER BY order_position ASC, created_at ASC`, [], ); return { faqs: result.results, total: result.results.length }; @@ -33,26 +33,37 @@ export class FAQService { async create(data: { question: string; answer: string; order_position: number }): Promise { const id = crypto.randomUUID(); - await this.dbSession.executeWrite( - `INSERT INTO faqs (id, question, answer, order_position, created_at, updated_at) VALUES (?, ?, ?, ?, datetime('now'), datetime('now'))`, + const result = await this.dbSession.executeWrite( + `INSERT INTO faqs (id, question, answer, order_position, created_at, updated_at) + VALUES (?, ?, ?, ?, datetime('now'), datetime('now')) + RETURNING id, question, answer, order_position, created_at, updated_at`, [id, data.question, data.answer, data.order_position], ); - const created = await this.get(id); + const created = (result.results as unknown as FAQRecord[] | null)?.[0]; if (!created) throw new Error('Failed to create FAQ'); return created; } async update(id: string, data: Partial<{ question: string; answer: string; order_position: number }>): Promise { - const existing = await this.get(id); - if (!existing) return null; - const question = data.question ?? existing.question; - const answer = data.answer ?? existing.answer; - const order_position = data.order_position ?? existing.order_position; - await this.dbSession.executeWrite( - `UPDATE faqs SET question = ?, answer = ?, order_position = ?, updated_at = datetime('now') WHERE id = ?`, - [question, answer, order_position, id], + const result = await this.dbSession.executeWrite( + `UPDATE faqs + SET question = CASE WHEN ? THEN ? ELSE question END, + answer = CASE WHEN ? THEN ? ELSE answer END, + order_position = CASE WHEN ? THEN ? ELSE order_position END, + updated_at = datetime('now') + WHERE id = ? + RETURNING id, question, answer, order_position, created_at, updated_at`, + [ + data.question != null ? 1 : 0, + data.question ?? null, + data.answer != null ? 1 : 0, + data.answer ?? null, + data.order_position != null ? 1 : 0, + data.order_position ?? null, + id, + ], ); - return this.get(id); + return (result.results as unknown as FAQRecord[] | null)?.[0] ?? null; } async delete(id: string): Promise { @@ -61,12 +72,11 @@ export class FAQService { } async reorder(updates: { id: string; order_position: number }[]): Promise { - // Simple transactional reorder - for (const u of updates) { - await this.dbSession.executeWrite(`UPDATE faqs SET order_position = ?, updated_at = datetime('now') WHERE id = ?`, [ - u.order_position, - u.id, - ]); - } + await this.dbSession.executeBatch( + updates.map((update) => ({ + query: `UPDATE faqs SET order_position = ?, updated_at = datetime('now') WHERE id = ?`, + params: [update.order_position, update.id], + })), + ); } } diff --git a/src/services/http.ts b/src/services/http.ts index 41277b7..0e7c689 100644 --- a/src/services/http.ts +++ b/src/services/http.ts @@ -5,3 +5,20 @@ export async function cancelResponseBody(response: Response): Promise { // Best-effort cleanup for response bodies we intentionally do not read. } } + +/** Resolve the originating client address only on endpoints that need it. */ +export function getClientIp(request: Request): string { + const headers = request.headers; + const direct = headers.get('CF-Connecting-IP') || headers.get('X-Real-IP'); + if (direct) return direct; + + const forwardedFor = headers.get('X-Forwarded-For'); + if (forwardedFor) { + const comma = forwardedFor.indexOf(','); + return (comma === -1 ? forwardedFor : forwardedFor.slice(0, comma)).trim() || '0.0.0.0'; + } + + const forwarded = headers.get('Forwarded'); + const match = forwarded?.match(/for=([^;]+)/i); + return match ? match[1].replace(/"/g, '') : '0.0.0.0'; +} diff --git a/src/services/lights-cache.ts b/src/services/lights-cache.ts index aeb4e5e..6c03001 100644 --- a/src/services/lights-cache.ts +++ b/src/services/lights-cache.ts @@ -1,8 +1,12 @@ -import { CacheService } from './cache'; import { ServicePool } from './service-pool'; export type RadarLight = { stateId: number | null; offStateId: number | null; position: [number, number]; heading: number }; +const LIGHT_STATE_ID_PATTERN = /stateId\s*=\s*"(\d+)"/i; +const LIGHT_OFF_STATE_ID_PATTERN = /offStateId\s*=\s*"(\d+)"/i; +const LIGHT_POSITION_PATTERN = /\s*([^<]+)\s*<\/Position>/i; +const LIGHT_HEADING_PATTERN = /\s*([^<]+)\s*<\/Heading>/i; + // Parse BARS Lights XML into objectId -> lights[] mapping export function parseBarsLightsXml(xml: string): Record { const result: Record = {}; @@ -19,14 +23,15 @@ export function parseBarsLightsXml(xml: string): Record { while ((lightMatch = lightRegex.exec(body)) !== null) { const attrs = lightMatch[1] || ''; const inner = lightMatch[2] || ''; - const stateIdMatch = attrs.match(/stateId\s*=\s*"(\d+)"/i); - const offStateIdMatch = attrs.match(/offStateId\s*=\s*"(\d+)"/i); - const posMatch = inner.match(/\s*([^<]+)\s*<\/Position>/i); - const headingMatch = inner.match(/\s*([^<]+)\s*<\/Heading>/i); + const stateIdMatch = LIGHT_STATE_ID_PATTERN.exec(attrs); + const offStateIdMatch = LIGHT_OFF_STATE_ID_PATTERN.exec(attrs); + const posMatch = LIGHT_POSITION_PATTERN.exec(inner); + const headingMatch = LIGHT_HEADING_PATTERN.exec(inner); if (!posMatch || !headingMatch) continue; - const [latStr, lonStr] = posMatch[1].split(',').map((s) => s.trim()); - const lat = parseFloat(latStr); - const lon = parseFloat(lonStr); + const commaIndex = posMatch[1].indexOf(','); + if (commaIndex < 0) continue; + const lat = parseFloat(posMatch[1].slice(0, commaIndex)); + const lon = parseFloat(posMatch[1].slice(commaIndex + 1)); const heading = parseFloat(headingMatch[1]); if (Number.isNaN(lat) || Number.isNaN(lon) || Number.isNaN(heading)) continue; const stateId = stateIdMatch ? parseInt(stateIdMatch[1], 10) : null; @@ -42,27 +47,25 @@ export function parseBarsLightsXml(xml: string): Record { // Fetch and cache latest lights mapping for an airport (15 minutes TTL) export async function getLightsByObject(env: Env, icao: string): Promise> { - const cache = new CacheService(env); - const cacheKey = `lights-map-${icao.toUpperCase()}`; + const normalizedIcao = icao.toUpperCase(); + const cache = ServicePool.getCache(env); + const cacheKey = `lights-map-${normalizedIcao}`; const cached = await cache.get>(cacheKey, 'airports'); if (cached) return cached; const storage = ServicePool.getStorage(env); try { - const list = await storage.listFiles(`Maps/${icao}_`, 50); + const list = await storage.listFiles(`Maps/${normalizedIcao}_`, 50); if (!list.objects || list.objects.length === 0) { await cache.set(cacheKey, {}, { ttl: 300, namespace: 'airports' }); return {}; } let latest = list.objects[0]; - for (const obj of list.objects) { - const objUploaded = (obj as unknown as { uploaded?: number }).uploaded; - const latestUploaded = (latest as unknown as { uploaded?: number }).uploaded; - if (objUploaded && latestUploaded && objUploaded > latestUploaded) { - latest = obj as typeof latest; - } + for (let index = 1; index < list.objects.length; index++) { + const object = list.objects[index]; + if (object.uploaded > latest.uploaded) latest = object; } - const fileResp = await storage.getFile((latest as unknown as { key: string }).key); + const fileResp = await storage.getFile(latest.key); if (!fileResp) { await cache.set(cacheKey, {}, { ttl: 300, namespace: 'airports' }); return {}; diff --git a/src/services/points.ts b/src/services/points.ts index 37d4fd8..a0d7a9e 100644 --- a/src/services/points.ts +++ b/src/services/points.ts @@ -74,9 +74,6 @@ export class PointsService { private stmtCheckPointId: PreparedStatement<{ id: string; }>; - private stmtGetLinkedLeadOns: PreparedStatement<{ - stopbarId: string; - }>; constructor( private db: D1Database, @@ -94,7 +91,6 @@ export class PointsService { ['id', 'airportId'], ); this.stmtCheckPointId = this.dbSession.prepare('SELECT id FROM points WHERE id = ? LIMIT 1;', ['id']); - this.stmtGetLinkedLeadOns = this.dbSession.prepare('SELECT id FROM points WHERE linked_to = ? AND type = ?', ['stopbarId']); } async createPoint(airportId: string, userId: string, point: PointData): Promise { @@ -196,16 +192,20 @@ export class PointsService { .map((field) => `${fieldMappings[field]} = ?`) .join(', '); - await this.dbSession.executeWrite( + const result = await this.dbSession.executeWrite( ` UPDATE points SET ${updateFields}, updated_at = ? WHERE id = ? + RETURNING id, airport_id, type, name, coordinates, directionality, orientation, + color, elevated, ihp, linked_to, created_at, updated_at, created_by `, [...Object.values(processedUpdates), new Date().toISOString(), pointId], ); - const finalPoint = (await this.getPoint(pointId)) as Point; + const updatedRow = (result.results as unknown as PointRow[] | null)?.[0]; + if (!updatedRow) throw new HttpError(404, 'Point not found'); + const finalPoint = this.mapPointFromDb(updatedRow); try { this.posthog?.track('Point Updated', { pointId, @@ -417,6 +417,26 @@ export class PointsService { return this.mapPointFromDb(row); } + /** + * Fetch points in one D1 query while preserving the caller's order, duplicate + * IDs, and null entries for missing rows. + */ + async getPoints(pointIds: string[]): Promise> { + if (pointIds.length === 0) return []; + + const uniqueIds = [...new Set(pointIds)]; + const placeholders = uniqueIds.map(() => '?').join(', '); + const result = await this.dbSession.executeRead( + `SELECT id, airport_id, type, name, coordinates, directionality, orientation, + color, elevated, ihp, linked_to, created_at, updated_at, created_by + FROM points + WHERE id IN (${placeholders})`, + uniqueIds, + ); + const pointsById = new Map(result.results.map((row) => [row.id, this.mapPointFromDb(row)])); + return pointIds.map((id) => pointsById.get(id) ?? null); + } + async getAirportPoints(airportId: string): Promise { const results = await this.dbSession.executeRead('SELECT * FROM points WHERE airport_id = ?', [airportId]); return results.results.map((r) => this.mapPointFromDb(r)); @@ -589,9 +609,7 @@ export class PointsService { * A lead-on can be linked to multiple stopbars. */ async linkLeadOnToStopbar(leadOnId: string, stopbarId: string, userId: string): Promise { - // Get both points - const leadOn = await this.getPoint(leadOnId); - const stopbar = await this.getPoint(stopbarId); + const [leadOn, stopbar] = await this.getPoints([leadOnId, stopbarId]); if (!leadOn) { throw new HttpError(404, 'Lead-on point not found'); @@ -704,27 +722,22 @@ export class PointsService { * Get all lead-ons linked to a specific stopbar */ async getLinkedLeadOns(stopbarId: string): Promise { - // Need to check if stopbarId is in the JSON array or equals the legacy single value - const results = await this.dbSession.executeRead<{ id: string; linked_to: string }>( - "SELECT id, linked_to FROM points WHERE type = 'lead_on' AND linked_to IS NOT NULL", - [], + const results = await this.dbSession.executeRead<{ id: string }>( + `SELECT id + FROM points + WHERE type = 'lead_on' + AND linked_to IS NOT NULL + AND ( + linked_to = ? + OR EXISTS ( + SELECT 1 + FROM json_each(CASE WHEN json_valid(linked_to) THEN linked_to ELSE json_array(linked_to) END) + WHERE value = ? + ) + )`, + [stopbarId, stopbarId], ); - - const linkedIds: string[] = []; - for (const row of results.results) { - try { - const parsed = JSON.parse(row.linked_to); - if (Array.isArray(parsed) && parsed.includes(stopbarId)) { - linkedIds.push(row.id); - } - } catch { - // Legacy single ID format - if (row.linked_to === stopbarId) { - linkedIds.push(row.id); - } - } - } - return linkedIds; + return results.results.map(({ id }) => id); } /** diff --git a/src/services/polygons.ts b/src/services/polygons.ts index 48d4a2a..f89cd2d 100644 --- a/src/services/polygons.ts +++ b/src/services/polygons.ts @@ -88,17 +88,21 @@ export class PolygonService { const baseQuery = 'SELECT id, type, airport_id, directionality, orientation, color, elevated, ihp, name, coordinates FROM points WHERE id IN ('; + const statements: Array<{ query: string; params: string[] }> = []; for (let i = 0; i < unique.length; i += chunkSize) { const chunk = unique.slice(i, i + chunkSize); const placeholders = chunk.map(() => '?').join(', '); - try { - const result = await this.dbSession.executeRead(`${baseQuery}${placeholders})`, chunk); - for (const row of result.results) { + statements.push({ query: `${baseQuery}${placeholders})`, params: chunk }); + } + try { + const results = await this.dbSession.executeReadBatch(statements); + for (const result of results) { + for (const row of result.results as PointRow[]) { records.set(row.id, this.mapBarsRecordFromDb(row)); } - } catch { - // Ignore chunk failures to mirror legacy behaviour } + } catch { + // Ignore lookup failures to mirror legacy behaviour. } return records; diff --git a/src/services/posthog.ts b/src/services/posthog.ts index 3274a64..faf7d76 100644 --- a/src/services/posthog.ts +++ b/src/services/posthog.ts @@ -18,42 +18,39 @@ export interface TrackOptions { inline?: boolean; // if true, don't background } +export interface BatchTrackEvent { + event: string; + properties?: Record; + distinctId?: string; + timestamp?: Date | string; +} + +const PII_KEYS = new Set(['userid', 'vatsimid', 'requestedby', 'approvedby', 'decidedby', 'createdby', 'email', 'cid', 'callsign']); +const UTF8_ENCODER = new TextEncoder(); +const BYTE_TO_HEX = Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, '0')); + export class PostHogService { private readonly apiKey: string | undefined; private readonly host: string; private readonly enabled: boolean; - private readonly piiKeyMatchers: Array<(k: string) => boolean> = [ - (k) => k === 'userId', - (k) => k === 'vatsimId', - (k) => k === 'requestedBy', - (k) => k === 'approvedBy', - (k) => k === 'decidedBy', - (k) => k === 'createdBy', - (k) => k === 'email', - (k) => k === 'cid', - (k) => k === 'callsign', - (k) => k.includes('vatsim'), - ]; - constructor(env: Env) { - this.apiKey = (env as unknown as { POSTHOG_API_KEY?: string }).POSTHOG_API_KEY; - this.host = (env as unknown as { POSTHOG_HOST?: string }).POSTHOG_HOST || 'https://a.stopbars.com'; + this.apiKey = env.POSTHOG_API_KEY; + this.host = (env.POSTHOG_HOST || 'https://a.stopbars.com').replace(/\/$/, ''); this.enabled = !!this.apiKey; } private isPIIKey(key: string): boolean { const lk = key.toLowerCase(); - return this.piiKeyMatchers.some((fn) => fn(lk)); + return PII_KEYS.has(lk) || lk.includes('vatsim'); } private async hashValue(value: unknown): Promise { try { - const encoder = new TextEncoder(); - const data = encoder.encode(String(value)); + const data = UTF8_ENCODER.encode(String(value)); const digest = await crypto.subtle.digest('SHA-256', data); - return Array.from(new Uint8Array(digest)) - .map((b) => b.toString(16).padStart(2, '0')) - .join(''); + let hex = ''; + for (const byte of new Uint8Array(digest)) hex += BYTE_TO_HEX[byte]; + return hex; } catch { // Fallback simple hash (non-crypto) if subtle fails const s = String(value); @@ -66,16 +63,53 @@ export class PostHogService { } private async sanitizeProperties(props: Record): Promise> { - const entries = await Promise.all( - Object.entries(props).map(async ([k, v]) => { - if (v == null) return [k, v]; - if (this.isPIIKey(k)) { - return [k, await this.hashValue(v)]; - } - return [k, v]; - }), - ); - return Object.fromEntries(entries); + const sanitized: Record = {}; + const pendingHashes: Promise[] = []; + for (const [key, value] of Object.entries(props)) { + sanitized[key] = value; + if (value != null && this.isPIIKey(key)) { + pendingHashes.push(this.hashValue(value).then((hash) => void (sanitized[key] = hash))); + } + } + await Promise.all(pendingHashes); + return sanitized; + } + + private async prepareProperties( + properties: Record, + distinctId: string, + options: Pick, + ): Promise> { + const mergedProps: Record = { ...properties }; + if (!options.omitProduct && mergedProps.product === undefined) { + mergedProps.product = options.product || 'Core'; + } + try { + if (JSON.stringify(mergedProps).length > 45_000) mergedProps._truncated = true; + } catch { + /* ignore */ + } + return { + distinct_id: distinctId, + ...(await this.sanitizeProperties(mergedProps)), + }; + } + + private dispatch(doFetch: () => Promise, inline = false): void | Promise { + if (inline) return doFetch(); + try { + if (typeof (cfWaitUntil as unknown) === 'function') { + cfWaitUntil(doFetch()); + return; + } + } catch { + /* ignore */ + } + try { + (globalThis as unknown as { waitUntil?: (p: Promise) => void }).waitUntil?.(doFetch()); + } catch { + /* ignore */ + } } track( @@ -85,29 +119,11 @@ export class PostHogService { options: TrackOptions = {}, ): void | Promise { if (!this.enabled) return; - const mergedProps: Record = { - ...properties, - }; - if (!options.omitProduct) { - if (mergedProps.product === undefined) mergedProps.product = options.product || 'Core'; - } - try { - const approxSize = JSON.stringify(mergedProps).length; - if (approxSize > 45_000) { - mergedProps._truncated = true; - } - } catch { - /* ignore */ - } const buildBody = async () => { - const sanitized = await this.sanitizeProperties(mergedProps); const payload: PostHogCapturePayload = { api_key: this.apiKey!, event, - properties: { - distinct_id: distinctId, - ...sanitized, - }, + properties: await this.prepareProperties(properties, distinctId, options), $process_person_profile: false, }; if (options.timestamp) { @@ -119,7 +135,7 @@ export class PostHogService { const doFetch = () => buildBody() .then((body) => - fetch(`${this.host.replace(/\/$/, '')}/capture/`, { + fetch(`${this.host}/capture/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body, @@ -134,20 +150,41 @@ export class PostHogService { .catch((err) => { console.warn('[PostHog] Track failed', err instanceof Error ? err.message : err); }); - if (options.inline) return doFetch(); - try { - if (typeof (cfWaitUntil as unknown) === 'function') { - cfWaitUntil(doFetch()); - return; - } - } catch { - /* ignore */ - } - try { - (globalThis as unknown as { waitUntil?: (p: Promise) => void }).waitUntil?.(doFetch()); - } catch { - /* ignore */ - } - return; + return this.dispatch(doFetch, options.inline); + } + + trackBatch( + events: readonly BatchTrackEvent[], + options: Pick = {}, + ): void | Promise { + if (!this.enabled || events.length === 0) return; + + const doFetch = async () => { + const batch = await Promise.all( + events.map(async (item) => ({ + event: item.event, + properties: await this.prepareProperties(item.properties ?? {}, item.distinctId ?? 'anonymous', options), + ...(item.timestamp + ? { timestamp: typeof item.timestamp === 'string' ? item.timestamp : item.timestamp.toISOString() } + : {}), + $process_person_profile: false, + })), + ); + + return fetch(`${this.host}/batch/`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ api_key: this.apiKey!, batch }), + }) + .then((res) => { + if (!res.ok) console.warn('[PostHog] Non-OK batch response', res.status); + return cancelResponseBody(res); + }) + .catch((err) => { + console.warn('[PostHog] Batch track failed', err instanceof Error ? err.message : err); + }); + }; + + return this.dispatch(doFetch, options.inline); } } diff --git a/src/services/rate-limit.ts b/src/services/rate-limit.ts index de7e71b..f24139f 100644 --- a/src/services/rate-limit.ts +++ b/src/services/rate-limit.ts @@ -1,16 +1,31 @@ import type { Context, Next } from 'hono'; -import { cancelResponseBody } from './http'; +import { DurableObject } from 'cloudflare:workers'; +import { getClientIp } from './http'; -export class RateLimiter implements DurableObject { - private buckets: Record = {}; - private readonly state: DurableObjectState; - private readonly env: Env; +export class RateLimiter extends DurableObject { + private count = 0; + private resetAt = 0; static readonly defaultMaxRequests = 20; static readonly defaultIntervalMs = 60_000; constructor(state: DurableObjectState, env: Env) { - this.state = state; - this.env = env; + super(state, env); + } + + /** Fast typed RPC path. Each limiter object is already sharded by key. */ + check(maxRequests = RateLimiter.defaultMaxRequests, intervalMs = RateLimiter.defaultIntervalMs): number { + const now = Date.now(); + if (now >= this.resetAt) { + this.count = 0; + this.resetAt = now + intervalMs; + } + + if (this.count >= maxRequests) { + return this.resetAt - now; + } + + this.count += 1; + return 0; } async fetch(request: Request): Promise { @@ -18,25 +33,10 @@ export class RateLimiter implements DurableObject { type RLBody = Partial<{ key: string; maxRequests: number; intervalMs: number }>; const body = await request.json().catch(() => ({}) as RLBody); const { key, maxRequests, intervalMs } = body; - const now = Date.now(); - if (!key) return new Response('Missing key', { status: 400 }); - - const bucket = this.buckets[key] || { count: 0, resetAt: now + (intervalMs ?? RateLimiter.defaultIntervalMs) }; - - if (now >= bucket.resetAt) { - bucket.count = 0; - bucket.resetAt = now + (intervalMs ?? RateLimiter.defaultIntervalMs); - } - - if (bucket.count >= (maxRequests ?? RateLimiter.defaultMaxRequests)) { - const wait = bucket.resetAt - now; - return Response.json({ wait }); - } - - bucket.count += 1; - this.buckets[key] = bucket; - return Response.json({ wait: 0 }); + return Response.json({ + wait: this.check(maxRequests ?? RateLimiter.defaultMaxRequests, intervalMs ?? RateLimiter.defaultIntervalMs), + }); } catch { return new Response('Bad Request', { status: 400 }); } @@ -66,10 +66,10 @@ export const rateLimit = (opts: RateLimitOptions = {}) => { }>, next: Next, ) => { - const url = new URL(c.req.url); - const path = url.pathname; + const path = c.req.path; const method = c.req.method; - const ip = c.get('clientIp') || '0.0.0.0'; + const ip = c.get('clientIp') || getClientIp(c.req.raw); + c.set('clientIp', ip); const baseKey = `${method}:${path}:${ip}` + (opts.tags?.length ? `:${opts.tags.join(':')}` : ''); const key = opts.key ? opts.key(c) : baseKey; @@ -78,26 +78,18 @@ export const rateLimit = (opts: RateLimitOptions = {}) => { return c.text('Rate limiter unavailable', 502); } - const id = c.env.BARS_RATE_LIMITER.idFromName(key); - const stub = c.env.BARS_RATE_LIMITER.get(id); - - const resp = await stub.fetch('https://stopbars.local/rl', { - method: 'POST', - body: JSON.stringify({ key, maxRequests, intervalMs }), - }); - - if (!resp.ok) { - await cancelResponseBody(resp); + let wait: number; + try { + wait = await c.env.BARS_RATE_LIMITER.getByName(key).check(maxRequests, intervalMs); + } catch { return c.text('Rate limiter unavailable', 502); } - const data = (await resp.json().catch(() => ({ wait: 0 }))) as { wait: number }; - - if (data.wait > 0) { - const retry = Math.ceil(data.wait / 1000); + if (wait > 0) { + const retry = Math.ceil(wait / 1000); return c.text(message, 429, { 'Retry-After': String(retry), - 'X-RateLimit-Wait': String(data.wait), + 'X-RateLimit-Wait': String(wait), }); } diff --git a/src/services/roles.ts b/src/services/roles.ts index 5af738f..f24ca38 100644 --- a/src/services/roles.ts +++ b/src/services/roles.ts @@ -31,7 +31,10 @@ export class RoleService { } private async fetchStaffRecord(userId: number): Promise { - const staffResult = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); + const staffResult = await this.dbSession.executeRead( + 'SELECT id, user_id, role, created_at FROM staff WHERE user_id = ? LIMIT 1', + [userId], + ); return staffResult.results[0] ?? null; } @@ -80,56 +83,59 @@ export class RoleService { `, [userId], ); - return rolesResult.results.reduce( - (acc, { role }) => ({ - ...acc, - [role]: 1, - }), - {} as DivisionRoles, - ); + const roles: DivisionRoles = {}; + for (const { role } of rolesResult.results) { + if (role === 'nav_head' || role === 'nav_member') roles[role] = 1; + } + return roles; } // --- Staff management helpers (write) --- - private async getRoleCount(role: StaffRole): Promise { - const res = await this.dbSession.executeRead<{ cnt: number }>('SELECT COUNT(*) as cnt FROM staff WHERE role = ?', [role]); - return res.results[0]?.cnt || 0; + private async getRoleChangeState(userId: number): Promise<(StaffRecord & { lead_count: number }) | null> { + const result = await this.dbSession.executeLatest( + `SELECT id, user_id, role, created_at, + (SELECT COUNT(*) FROM staff WHERE role = ?) AS lead_count + FROM staff + WHERE user_id = ? + LIMIT 1`, + [StaffRole.LEAD_DEVELOPER, userId], + ); + return result.results[0] ?? null; } - private async ensureNotLastLeadDeveloper(userId: number, changingToRole?: StaffRole | null) { - const existing = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); - const current = existing.results[0]; - if (!current) return; // not staff + private ensureNotLastLeadDeveloper(current: (StaffRecord & { lead_count: number }) | null, changingToRole?: StaffRole | null) { + if (!current) return; if ( (current.role as StaffRole) === StaffRole.LEAD_DEVELOPER && (changingToRole == null || changingToRole !== StaffRole.LEAD_DEVELOPER) ) { - const count = await this.getRoleCount(StaffRole.LEAD_DEVELOPER); - if (count <= 1) throw new Error('Cannot modify or remove the last remaining lead developer'); + if (current.lead_count <= 1) throw new Error('Cannot modify or remove the last remaining lead developer'); } } async addStaff(userId: number, role: StaffRole): Promise<{ user_id: number; role: StaffRole; created_at: string }> { - const existing = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); - if (existing.results[0]) { - await this.ensureNotLastLeadDeveloper(userId, role); - await this.dbSession.executeWrite('UPDATE staff SET role = ? WHERE user_id = ?', [role, userId]); - const updated = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); - const row = updated.results[0]!; - return { user_id: row.user_id, role: row.role as StaffRole, created_at: row.created_at }; - } + const existing = await this.getRoleChangeState(userId); + this.ensureNotLastLeadDeveloper(existing, role); const createdAt = new Date().toISOString(); - await this.dbSession.executeWrite('INSERT INTO staff (user_id, role, created_at) VALUES (?, ?, ?)', [userId, role, createdAt]); - return { user_id: userId, role, created_at: createdAt }; + const result = await this.dbSession.executeWrite( + `INSERT INTO staff (user_id, role, created_at) VALUES (?, ?, ?) + ON CONFLICT(user_id) DO UPDATE SET role = excluded.role + RETURNING user_id, role, created_at`, + [userId, role, createdAt], + ); + const row = (result.results as unknown as StaffRecord[] | null)?.[0]; + if (!row) throw new Error('Failed to add staff member'); + return { user_id: row.user_id, role: row.role as StaffRole, created_at: row.created_at }; } async updateStaffRole(userId: number, role: StaffRole): Promise { - await this.ensureNotLastLeadDeveloper(userId, role); + this.ensureNotLastLeadDeveloper(await this.getRoleChangeState(userId), role); const result = await this.dbSession.executeWrite('UPDATE staff SET role = ? WHERE user_id = ?', [role, userId]); return !!result.success; } async removeStaff(userId: number): Promise { - await this.ensureNotLastLeadDeveloper(userId, null); + this.ensureNotLastLeadDeveloper(await this.getRoleChangeState(userId), null); const result = await this.dbSession.executeWrite('DELETE FROM staff WHERE user_id = ?', [userId]); return !!result.success; } diff --git a/src/services/storage.ts b/src/services/storage.ts index 0f5feed..39b0298 100644 --- a/src/services/storage.ts +++ b/src/services/storage.ts @@ -61,11 +61,13 @@ export class StorageService { * @param key The object key * @returns The file as a Response or null if not found */ - async getFile(key: string): Promise { + async getFile(key: string, requestHeaders?: Headers): Promise { const normalizedKey = this.normalizeKey(key); - // Get the object from R2 - const object = await this.bucket.get(normalizedKey); + // Let R2 read only the requested byte range instead of fetching the full + // object and slicing it inside the Worker. + const rangeHeaders = requestHeaders?.has('range') ? requestHeaders : undefined; + const object = await this.bucket.get(normalizedKey, rangeHeaders ? { range: rangeHeaders } : undefined); if (!object) { return null; @@ -74,15 +76,31 @@ export class StorageService { // Create headers const headers = new Headers(); object.writeHttpMetadata(headers); - headers.set('etag', object.etag); + headers.set('etag', object.httpEtag); headers.set('Accept-Ranges', 'bytes'); + let status = 200; + if (object.range) { + // Miniflare may expose all union members with undefined values, so narrow + // by value rather than using the `in` operator. + const suffix = 'suffix' in object.range && typeof object.range.suffix === 'number' ? object.range.suffix : undefined; + const rangeOffset = 'offset' in object.range && typeof object.range.offset === 'number' ? object.range.offset : 0; + const offset = suffix === undefined ? rangeOffset : Math.max(0, object.size - suffix); + const rangeLength = 'length' in object.range && typeof object.range.length === 'number' ? object.range.length : undefined; + const length = + suffix === undefined ? (rangeLength ?? Math.max(0, object.size - offset)) : Math.min(object.size, suffix); + headers.set('Content-Range', `bytes ${offset}-${offset + length - 1}/${object.size}`); + headers.set('Content-Length', String(length)); + status = 206; + } + // Add CORS headers Object.entries(this.CORS_HEADERS).forEach(([key, value]) => { headers.set(key, value); }); return new Response(object.body, { + status, headers, }); } diff --git a/src/services/users.ts b/src/services/users.ts index 0aed971..bf28f96 100644 --- a/src/services/users.ts +++ b/src/services/users.ts @@ -44,41 +44,41 @@ export class UserService { const offset = (page - 1) * limit; try { - const [usersResult, countResult] = await Promise.all([ - this.dbSession.executeRead<{ - id: number; - vatsim_id: string; - email: string; - full_name: string | null; - display_mode: number | null; - display_name: string | null; - region_id: string | null; - region_name: string | null; - division_id: string | null; - division_name: string | null; - subdivision_id: string | null; - subdivision_name: string | null; - created_at: string; - last_login: string; - is_staff: number; - }>( - ` - SELECT u.id, u.vatsim_id, u.email, u.full_name, u.display_mode, u.display_name, u.region_id, u.region_name, u.division_id, u.division_name, u.subdivision_id, u.subdivision_name, u.created_at, u.last_login, - CASE WHEN s.id IS NOT NULL THEN 1 ELSE 0 END as is_staff - FROM users u - LEFT JOIN staff s ON u.id = s.user_id - ORDER BY u.created_at DESC - LIMIT ? OFFSET ? - `, - [limit, offset], - ), - this.dbSession.executeRead<{ count: number }>('SELECT COUNT(*) as count FROM users'), + const [usersResult, countResult] = await this.dbSession.executeReadBatch([ + { + query: ` + SELECT u.id, u.vatsim_id, u.email, u.full_name, u.display_mode, u.display_name, + u.region_id, u.region_name, u.division_id, u.division_name, + u.subdivision_id, u.subdivision_name, u.created_at, u.last_login, + CASE WHEN s.user_id IS NOT NULL THEN 1 ELSE 0 END AS is_staff + FROM users u + LEFT JOIN staff s ON s.user_id = u.id + ORDER BY u.created_at DESC + LIMIT ? OFFSET ?`, + params: [limit, offset], + }, + { query: 'SELECT COUNT(*) AS count FROM users' }, ]); - if (!usersResult || !countResult) { - throw new Error('Failed to fetch users'); - } + const users = usersResult.results as Array<{ + id: number; + vatsim_id: string; + email: string; + full_name: string | null; + display_mode: number | null; + display_name: string | null; + region_id: string | null; + region_name: string | null; + division_id: string | null; + division_name: string | null; + subdivision_id: string | null; + subdivision_name: string | null; + created_at: string; + last_login: string; + is_staff: number; + }>; + const count = countResult.results as Array<{ count: number }>; return { - users: usersResult.results.map((u) => ({ + users: users.map((u) => ({ id: u.id, vatsim_id: u.vatsim_id, email: u.email, @@ -92,7 +92,7 @@ export class UserService { last_login: u.last_login, is_staff: u.is_staff === 1, })), - total: countResult.results[0]?.count || 0, + total: count[0]?.count || 0, }; } catch { throw new HttpError(500, 'Failed to fetch users'); diff --git a/src/services/vatsim.ts b/src/services/vatsim.ts index ae2c4fb..716e616 100644 --- a/src/services/vatsim.ts +++ b/src/services/vatsim.ts @@ -4,6 +4,8 @@ import { cancelResponseBody } from './http'; export class VatsimService { private userCache = new Map(); + private pendingUserRequests = new Map>(); + private pendingConnectionRequests = new Map>(); private readonly userCacheTtlMs: number; constructor( @@ -45,7 +47,21 @@ export class VatsimService { this.userCache.delete(token); } } + const pending = this.pendingUserRequests.get(token); + if (pending) return pending; + const request = this.fetchAndCacheUser(token); + this.pendingUserRequests.set(token, request); + try { + return await request; + } finally { + if (this.pendingUserRequests.get(token) === request) { + this.pendingUserRequests.delete(token); + } + } + } + + private async fetchAndCacheUser(token: string): Promise { const res = await fetch('https://auth.vatsim.net/api/user', { headers: { Authorization: `Bearer ${token}` }, }); @@ -88,13 +104,20 @@ export class VatsimService { }; if (this.userCacheTtlMs > 0) { - if (this.userCache.size > 1024) { + if (this.userCache.size >= 1024) { const now = Date.now(); for (const [cacheToken, entry] of this.userCache) { if (entry.expiresAt <= now) { this.userCache.delete(cacheToken); } - if (this.userCache.size <= 512) break; + } + if (this.userCache.size >= 1024) { + const entriesToEvict = this.userCache.size - 511; + let evicted = 0; + for (const cacheToken of this.userCache.keys()) { + this.userCache.delete(cacheToken); + if (++evicted >= entriesToEvict) break; + } } } this.userCache.set(token, { user, expiresAt: Date.now() + this.userCacheTtlMs }); @@ -104,28 +127,14 @@ export class VatsimService { } async getUserStatus(userId: string): Promise<{ cid: string; callsign: string; type: string } | null> { try { - if (!/^\d+$/.test(userId)) { - return null; - } - - const params = new URLSearchParams({ CID: userId }); - const url = `https://slurper.vatsim.net/users/info?${params.toString()}`; - - const response = await fetch(url, { - signal: AbortSignal.timeout(5000), - }); - - if (!response.ok) { - await cancelResponseBody(response); + const text = await this.getUserConnectionsCsv(userId); + if (text === null) return null; + const trimmed = text.trim(); + if (!trimmed) { return null; } - const text = await response.text(); - if (!text.trim()) { - return null; - } - - const parts = text.trim().split(','); + const parts = trimmed.split(','); if (parts.length < 3) { return null; } @@ -142,11 +151,26 @@ export class VatsimService { } async getUserConnectionsCsv(userId: string): Promise { + if (!/^\d+$/.test(userId)) { + return null; + } + + const pending = this.pendingConnectionRequests.get(userId); + if (pending) return pending; + + const request = this.fetchUserConnectionsCsv(userId); + this.pendingConnectionRequests.set(userId, request); try { - if (!/^\d+$/.test(userId)) { - return null; + return await request; + } finally { + if (this.pendingConnectionRequests.get(userId) === request) { + this.pendingConnectionRequests.delete(userId); } + } + } + private async fetchUserConnectionsCsv(userId: string): Promise { + try { const params = new URLSearchParams({ cid: userId }); const url = `https://slurper.vatsim.net/users/info?${params.toString()}`; @@ -164,26 +188,14 @@ export class VatsimService { return null; } } - private readonly ControllerSuffixes = new Set([ - 'DEL', - 'RMP', - 'GND', - 'TWR', - 'DEP', - 'APP', - 'CTR', - 'FSS', - 'RDO', - 'TMU', - 'FMP', - ]); + private readonly ControllerSuffixes = new Set(['DEL', 'RMP', 'GND', 'TWR', 'DEP', 'APP', 'CTR', 'FSS', 'RDO', 'TMU', 'FMP']); private getCallsignSuffix(callsign?: string | null): string | null { if (!callsign) return null; const upper = callsign.toUpperCase(); - const parts = upper.split('_'); - if (parts.length < 2) return null; - return parts[parts.length - 1] || null; + const separator = upper.lastIndexOf('_'); + if (separator < 0 || separator === upper.length - 1) return null; + return upper.slice(separator + 1); } private isControllerCallsign(callsign?: string | null): boolean { diff --git a/src/services/vatsys-profile-generator.ts b/src/services/vatsys-profile-generator.ts index 9aa3515..1879110 100644 --- a/src/services/vatsys-profile-generator.ts +++ b/src/services/vatsys-profile-generator.ts @@ -146,6 +146,13 @@ type IntasOsmData = { windsocks: GeoPoint[]; }; +type GenerationInputs = { + configRecord: VatSysConfigRecord; + points: ParsedPoint[]; + runways: RunwayRow[]; + airportBounds: AirportBounds | undefined; +}; + export class VatSysProfileGeneratorService { private static readonly ICAO_REGEX = /^[A-Z0-9]{4}$/; private static readonly MAX_STOPBARS_PER_SIDE = 16; @@ -166,7 +173,7 @@ export class VatSysProfileGeneratorService { private readonly axisProjectionCache = new WeakMap(); - constructor(private db: D1Database) { } + constructor(private db: D1Database) {} async generate(icao: string): Promise { const normalizedIcao = icao.toUpperCase().replace(/[^A-Z0-9]/g, ''); @@ -176,19 +183,28 @@ export class VatSysProfileGeneratorService { const session = new DatabaseSessionService(this.db); try { - const configRecord = await this.getVatSysConfig(session, normalizedIcao); + const { configRecord, points, runways, airportBounds } = await this.getGenerationInputs(session, normalizedIcao); const format = this.resolveFormat(configRecord.config, normalizedIcao); - const points = await this.getPoints(session, normalizedIcao); - const stopbars = points.filter((point) => point.type === 'stopbar'); - const leadOns = points.filter((point) => point.type === 'lead_on'); + const stopbars: ParsedPoint[] = []; + const leadOns: ParsedPoint[] = []; + for (const point of points) { + (point.type === 'stopbar' ? stopbars : leadOns).push(point); + } if (stopbars.length === 0) { throw new HttpError(422, `No stopbars found for ${normalizedIcao}`); } if (format === 'intas') { - const runways = await this.getRunways(session, normalizedIcao); - const profile = await this.generateIntasProfile(session, normalizedIcao, configRecord, stopbars, leadOns, runways); + const profile = await this.generateIntasProfile( + session, + normalizedIcao, + configRecord, + stopbars, + leadOns, + runways, + airportBounds, + ); return { format, icao: normalizedIcao, @@ -197,7 +213,6 @@ export class VatSysProfileGeneratorService { }; } - const runways = await this.getRunways(session, normalizedIcao); if (runways.length === 0) { throw new HttpError(422, `No runways found for ${normalizedIcao}`); } @@ -207,7 +222,16 @@ export class VatSysProfileGeneratorService { const linkedLeadOns = this.buildLeadOnLookup(leadOns); const bestRunwayMatches = this.buildBestRunwayMatchLookup(stopbars, runways, towerPosition, runwayAxes); const profiles = runways.map((runway) => - this.generateLegacyProfile(normalizedIcao, runway, runways, towerPosition, stopbars, linkedLeadOns, runwayAxes, bestRunwayMatches), + this.generateLegacyProfile( + normalizedIcao, + runway, + runways, + towerPosition, + stopbars, + linkedLeadOns, + runwayAxes, + bestRunwayMatches, + ), ); const warnings = profiles.flatMap((profile) => profile.warnings.map((warning) => `${profile.filename}: ${warning}`)); @@ -222,31 +246,75 @@ export class VatSysProfileGeneratorService { } } - private async getVatSysConfig(session: DatabaseSessionService, icao: string): Promise { - const result = await session.executeRead<{ id: number; vatsys: string }>( - ` - SELECT id, vatsys - FROM division_airports - WHERE icao = ? AND status = 'approved' - ORDER BY updated_at DESC, id DESC - LIMIT 1 - `, - [icao], - ); - const row = result.results[0]; + private async getGenerationInputs(session: DatabaseSessionService, icao: string): Promise { + const [configResult, pointsResult, runwaysResult, boundsResult] = await session.executeReadBatch([ + { + query: ` + SELECT id, vatsys + FROM division_airports + WHERE icao = ? AND status = 'approved' + ORDER BY updated_at DESC, id DESC + LIMIT 1 + `, + params: [icao], + }, + { + query: ` + SELECT id, type, name, coordinates, linked_to + FROM points + WHERE airport_id = ? AND type IN ('stopbar', 'lead_on') + ORDER BY name ASC, id ASC + `, + params: [icao], + }, + { + query: ` + SELECT id, length_ft, width_ft, le_ident, le_latitude_deg, le_longitude_deg, he_ident, he_latitude_deg, he_longitude_deg + FROM runways + WHERE airport_icao = ? + ORDER BY id ASC + `, + params: [icao], + }, + { + query: ` + SELECT bbox_min_lat, bbox_min_lon, bbox_max_lat, bbox_max_lon + FROM airports + WHERE icao = ? + LIMIT 1 + `, + params: [icao], + }, + ]); + + const row = configResult.results[0] as { id: number; vatsys: string } | undefined; if (!row) { throw new HttpError(404, `No approved division airport found for ${icao}`); } + let config: VatSysConfig; try { - const parsed = JSON.parse(row.vatsys) as VatSysConfig; - if (!parsed || typeof parsed !== 'object') { + config = JSON.parse(row.vatsys) as VatSysConfig; + if (!config || typeof config !== 'object') { throw new Error('Invalid vatSys flags'); } - return { id: row.id, config: parsed }; } catch { throw new HttpError(422, `Invalid vatSys configuration for ${icao}`); } + + const points: ParsedPoint[] = []; + for (const rawRow of pointsResult.results) { + const point = this.parsePoint(rawRow as PointRow); + if (point) points.push(point); + } + const runways = (runwaysResult.results as RunwayRow[]).filter((runway) => this.getRunwayAxis(runway) !== null); + + return { + configRecord: { id: row.id, config }, + points, + runways, + airportBounds: boundsResult.results[0] as AirportBounds | undefined, + }; } private resolveFormat(config: VatSysConfig, icao: string): VatSysFormat { @@ -259,35 +327,6 @@ export class VatSysProfileGeneratorService { return config.is_intas === true ? 'intas' : 'legacy'; } - private async getRunways(session: DatabaseSessionService, icao: string): Promise { - const result = await session.executeRead( - ` - SELECT id, length_ft, width_ft, le_ident, le_latitude_deg, le_longitude_deg, he_ident, he_latitude_deg, he_longitude_deg - FROM runways - WHERE airport_icao = ? - ORDER BY id ASC - `, - [icao], - ); - return result.results.filter((runway) => this.getRunwayAxis(runway) !== null); - } - - private async getPoints(session: DatabaseSessionService, icao: string): Promise { - const result = await session.executeRead( - ` - SELECT id, type, name, coordinates, linked_to - FROM points - WHERE airport_id = ? AND type IN ('stopbar', 'lead_on') - ORDER BY name ASC, id ASC - `, - [icao], - ); - - return result.results - .map((row) => this.parsePoint(row)) - .filter((point): point is ParsedPoint => point !== null); - } - private generateLegacyProfile( icao: string, runway: RunwayRow, @@ -322,7 +361,9 @@ export class VatSysProfileGeneratorService { } const top = projectedStopbars.filter((stopbar) => stopbar.y >= 0).sort((a, b) => a.x - b.x || a.point.id.localeCompare(b.point.id)); - const bottom = projectedStopbars.filter((stopbar) => stopbar.y < 0).sort((a, b) => a.x - b.x || a.point.id.localeCompare(b.point.id)); + const bottom = projectedStopbars + .filter((stopbar) => stopbar.y < 0) + .sort((a, b) => a.x - b.x || a.point.id.localeCompare(b.point.id)); if (top.length > VatSysProfileGeneratorService.MAX_STOPBARS_PER_SIDE) { throw new HttpError(422, `Runway ${rightEndName}-${leftEndName} has more than 16 stopbars on the top side`); @@ -351,9 +392,19 @@ export class VatSysProfileGeneratorService { stopbars: ParsedPoint[], leadOns: ParsedPoint[], runways: RunwayRow[], + airportBounds: AirportBounds | undefined, ): Promise { const warnings: string[] = []; - const taxiwayCache = await this.getIntasTaxiwayCache(session, icao, configRecord, stopbars, leadOns, runways, warnings); + const taxiwayCache = await this.getIntasTaxiwayCache( + session, + icao, + configRecord, + stopbars, + leadOns, + runways, + airportBounds, + warnings, + ); const filename = `${icao}.xml`; return { @@ -370,9 +421,10 @@ export class VatSysProfileGeneratorService { stopbars: ParsedPoint[], leadOns: ParsedPoint[], runways: RunwayRow[], + airportBounds: AirportBounds | undefined, warnings: string[], ): Promise { - const bbox = await this.getAirportBounds(session, icao); + const bbox = this.validateAirportBounds(airportBounds, icao); const sourceSignature = this.buildIntasTaxiwayCacheSignature(bbox, stopbars, leadOns, runways); const cached = this.parseIntasTaxiwayCache(configRecord.config, sourceSignature); if (cached) { @@ -411,16 +463,12 @@ export class VatSysProfileGeneratorService { return null; } - const lines = cache.lines - .map((line) => this.normalizeTaxiwayLine(line)) - .filter((line): line is GeoPoint[] => line !== null); + const lines = cache.lines.map((line) => this.normalizeTaxiwayLine(line)).filter((line): line is GeoPoint[] => line !== null); if (lines.length === 0) { return null; } const windsocks = Array.isArray(cache.windsocks) - ? cache.windsocks - .map((point) => this.normalizeGeoPoint(point)) - .filter((point): point is GeoPoint => point !== null) + ? cache.windsocks.map((point) => this.normalizeGeoPoint(point)).filter((point): point is GeoPoint => point !== null) : []; return { @@ -537,20 +585,10 @@ export class VatSysProfileGeneratorService { ); } - private async getAirportBounds( - session: DatabaseSessionService, + private validateAirportBounds( + row: AirportBounds | undefined, icao: string, - ): Promise<{ south: number; west: number; north: number; east: number }> { - const result = await session.executeRead( - ` - SELECT bbox_min_lat, bbox_min_lon, bbox_max_lat, bbox_max_lon - FROM airports - WHERE icao = ? - LIMIT 1 - `, - [icao], - ); - const row = result.results[0]; + ): { south: number; west: number; north: number; east: number } { if (!row) { throw new HttpError(422, `No airport metadata found for ${icao}`); } @@ -698,14 +736,17 @@ export class VatSysProfileGeneratorService { const indent = ' '.repeat(baseIndent); lines.push(`${indent}`); for (const point of points) { - lines.push( - `${indent} `, - ); + lines.push(`${indent} `); } lines.push(`${indent}`); } - private filterAndSplitTaxiways(lines: GeoPoint[][], stopbars: ParsedPoint[], leadOns: ParsedPoint[], runways: RunwayRow[]): GeoPoint[][] { + private filterAndSplitTaxiways( + lines: GeoPoint[][], + stopbars: ParsedPoint[], + leadOns: ParsedPoint[], + runways: RunwayRow[], + ): GeoPoint[][] { const filtered: GeoPoint[][] = []; const runwayExclusionAreas = this.getStopbarRunwayExclusionAreas(runways, stopbars, leadOns); @@ -776,8 +817,7 @@ export class VatSysProfileGeneratorService { this.isPointWithinBounds(endpoint, allBounds[candidateIndex]) && candidateLine.some( (candidatePoint) => - calculateDistance(endpoint, candidatePoint) <= - VatSysProfileGeneratorService.INTAS_TAXIWAY_CONNECTION_METERS, + calculateDistance(endpoint, candidatePoint) <= VatSysProfileGeneratorService.INTAS_TAXIWAY_CONNECTION_METERS, ), ), ); @@ -916,9 +956,7 @@ export class VatSysProfileGeneratorService { const midpointProjection = this.projectToAxis(stopbar.midpoint, axis); const runwaySideY = midpointProjection.y >= 0 ? -halfWidthMeters - padding : halfWidthMeters + padding; const stopbarBoundary = stopbar.coordinates.map((point) => this.projectToAxis(point, axis)); - const runwaySideBoundary = stopbarBoundary - .map((point) => ({ x: point.x, y: runwaySideY })) - .reverse(); + const runwaySideBoundary = stopbarBoundary.map((point) => ({ x: point.x, y: runwaySideY })).reverse(); return [...stopbarBoundary, ...runwaySideBoundary]; } @@ -935,9 +973,7 @@ export class VatSysProfileGeneratorService { continue; } const endExtensionMeters = - index === leadOn.coordinates.length - 2 - ? VatSysProfileGeneratorService.INTAS_LEAD_ON_END_EXCLUSION_METERS - : 0; + index === leadOn.coordinates.length - 2 ? VatSysProfileGeneratorService.INTAS_LEAD_ON_END_EXCLUSION_METERS : 0; areas.push({ axis: { @@ -984,8 +1020,7 @@ export class VatSysProfileGeneratorService { const projectedStart = projected.start; const projectedEnd = projected.end; const intersections = this.getLinePolygonIntersectionTs(projectedStart, projectedEnd, runway.polygon); - const splitTs = [...new Set([0, 1, ...intersections].map((value) => Number(value.toFixed(6))))] - .sort((a, b) => a - b); + const splitTs = [...new Set([0, 1, ...intersections].map((value) => Number(value.toFixed(6))))].sort((a, b) => a - b); for (let index = 0; index < splitTs.length - 1; index++) { const rangeStart = splitTs[index]; @@ -1066,9 +1101,7 @@ export class VatSysProfileGeneratorService { } private mergeRanges(ranges: Array<{ start: number; end: number }>): Array<{ start: number; end: number }> { - const sorted = ranges - .filter((range) => range.end > range.start) - .sort((a, b) => a.start - b.start || a.end - b.end); + const sorted = ranges.filter((range) => range.end > range.start).sort((a, b) => a.start - b.start || a.end - b.end); const merged: Array<{ start: number; end: number }> = []; for (const range of sorted) { @@ -1355,7 +1388,8 @@ export class VatSysProfileGeneratorService { return stopbars .map((stopbar) => { - const bestMatch = bestRunwayMatches?.get(stopbar.id) ?? this.getBestRunwayMatch(stopbar, allRunways, towerPosition, runwayAxes); + const bestMatch = + bestRunwayMatches?.get(stopbar.id) ?? this.getBestRunwayMatch(stopbar, allRunways, towerPosition, runwayAxes); if (bestMatch?.runwayId === selectedRunway.id) { return bestMatch; } @@ -1405,7 +1439,11 @@ export class VatSysProfileGeneratorService { ) { continue; } - if (!bestTouch || Math.abs(projected.y) < Math.abs(bestTouch.y) || (Math.abs(projected.y) === Math.abs(bestTouch.y) && projected.x < bestTouch.x)) { + if ( + !bestTouch || + Math.abs(projected.y) < Math.abs(bestTouch.y) || + (Math.abs(projected.y) === Math.abs(bestTouch.y) && projected.x < bestTouch.x) + ) { bestTouch = projected; } } @@ -1434,7 +1472,11 @@ export class VatSysProfileGeneratorService { if (!axis) continue; const projected = this.projectStopbar(stopbar, runway, axis); if (!projected || !this.isStopbarRelevant(projected, axis, runway)) continue; - if (!bestMatch || projected.score < bestMatch.score || (projected.score === bestMatch.score && projected.runwayId < bestMatch.runwayId)) { + if ( + !bestMatch || + projected.score < bestMatch.score || + (projected.score === bestMatch.score && projected.runwayId < bestMatch.runwayId) + ) { bestMatch = projected; } } @@ -1765,9 +1807,12 @@ export class VatSysProfileGeneratorService { const startProjection = this.projectToAxis(otherStart, axis); const endProjection = this.projectToAxis(otherEnd, axis); - const crossesSide = startProjection.y === 0 || endProjection.y === 0 || Math.sign(startProjection.y) !== Math.sign(endProjection.y); + const crossesSide = + startProjection.y === 0 || endProjection.y === 0 || Math.sign(startProjection.y) !== Math.sign(endProjection.y); const crossingX = this.interpolateCrossingX(startProjection, endProjection); - const withinRunway = crossingX >= -VatSysProfileGeneratorService.CROSSING_DISTANCE_METERS && crossingX <= axis.lengthMeters + VatSysProfileGeneratorService.CROSSING_DISTANCE_METERS; + const withinRunway = + crossingX >= -VatSysProfileGeneratorService.CROSSING_DISTANCE_METERS && + crossingX <= axis.lengthMeters + VatSysProfileGeneratorService.CROSSING_DISTANCE_METERS; if (!crossesSide || !withinRunway) continue; @@ -1923,12 +1968,7 @@ export class VatSysProfileGeneratorService { } private escapeXml(value: string): string { - return value - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); + return value.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); } private sanitizeFilenamePart(value: string): string { diff --git a/src/services/xml-sanitizer.ts b/src/services/xml-sanitizer.ts index 73122ce..375f38a 100644 --- a/src/services/xml-sanitizer.ts +++ b/src/services/xml-sanitizer.ts @@ -1,4 +1,7 @@ export const MAX_CONTRIBUTION_XML_BYTES = 5 * 1024 * 1024; // 5 MB +// XML 1.0 explicitly forbids these C0 controls; a single regex avoids a full-size character array. +// eslint-disable-next-line no-control-regex +const DISALLOWED_XML_CONTROL_CHARS = new RegExp('[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]', 'g'); export function sanitizeContributionXml(raw: string, opts?: { maxBytes?: number }): string { if (!raw) throw new Error('Empty XML'); @@ -36,12 +39,7 @@ export function sanitizeContributionXml(raw: string, opts?: { maxBytes?: number let sanitized = trimmed.replace(/(<\?)(?!xml)([\s\S]*?\?>)/gi, ''); // Strip disallowed control chars (anything below 0x20 except TAB (0x09), LF (0x0A), CR (0x0D)) - sanitized = Array.from(sanitized) - .filter((ch) => { - const c = ch.charCodeAt(0); - return !((c >= 0x00 && c <= 0x08) || c === 0x0b || c === 0x0c || (c >= 0x0e && c <= 0x1f)); - }) - .join(''); + sanitized = sanitized.replace(DISALLOWED_XML_CONTROL_CHARS, ''); // Optional: collapse repeated spaces between tags to keep storage predictable (small normalization) sanitized = sanitized.replace(/>\s+<'); diff --git a/worker-configuration.d.ts b/worker-configuration.d.ts index f4e2cb6..698592c 100644 --- a/worker-configuration.d.ts +++ b/worker-configuration.d.ts @@ -1,21 +1,26 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: 4c9f43f11b9a843d974b4e1c73d05809) -// Runtime types generated with workerd@1.20250913.0 2025-11-07 nodejs_compat +// Generated by Wrangler by running `wrangler types` (hash: 1be2076908a39835ae0a4123f9b11433) +// Runtime types generated with workerd@1.20260714.1 2026-07-18 nodejs_compat +interface __BaseEnv_Env { + BARS_STORAGE: R2Bucket; + DB: D1Database; + VATSIM_CLIENT_ID: "1562"; + POSTHOG_HOST: "https://a.stopbars.com"; + VATSIM_CLIENT_SECRET: string; + AIRPORTDB_API_KEY: string; + GITHUB_TOKEN: string; + POSTHOG_API_KEY: string; + BARS: DurableObjectNamespace; + BARS_RATE_LIMITER: DurableObjectNamespace; +} declare namespace Cloudflare { - interface Env { - VATSIM_CLIENT_ID: "1562"; - POSTHOG_HOST: "https://a.stopbars.com"; - VATSIM_CLIENT_SECRET: string; - AIRPORTDB_API_KEY: string; - GITHUB_TOKEN: string; - POSTHOG_API_KEY: string; - BARS: DurableObjectNamespace; - BARS_RATE_LIMITER: DurableObjectNamespace; - BARS_STORAGE: R2Bucket; - DB: D1Database; + interface GlobalProps { + mainModule: typeof import("./src/index"); + durableNamespaces: "BARS" | "RateLimiter"; } + interface Env extends __BaseEnv_Env {} } -interface Env extends Cloudflare.Env {} +interface Env extends __BaseEnv_Env {} type StringifyValues> = { [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; }; @@ -42,17 +47,26 @@ and limitations under the License. // noinspection JSUnusedGlobalSymbols declare var onmessage: never; /** - * An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. + * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) */ declare class DOMException extends Error { constructor(message?: string, name?: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + /** + * The **`message`** read-only property of the a message or description associated with the given error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) + */ readonly message: string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + /** + * The **`name`** read-only property of the one of the strings associated with an error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) + */ readonly name: string; /** + * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) @@ -96,45 +110,121 @@ type WorkerGlobalScopeEventMap = { declare abstract class WorkerGlobalScope extends EventTarget { EventTarget: typeof EventTarget; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * + * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) + */ interface Console { "assert"(condition?: boolean, ...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + /** + * The **`console.clear()`** static method clears the console if possible. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) + */ clear(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + /** + * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) + */ count(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + /** + * The **`console.countReset()`** static method resets counter used with console/count_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) + */ countReset(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + /** + * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) + */ debug(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + /** + * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) + */ dir(item?: any, options?: any): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + /** + * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) + */ dirxml(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + /** + * The **`console.error()`** static method outputs a message to the console at the 'error' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) + */ error(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + /** + * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) + */ group(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + /** + * The **`console.groupCollapsed()`** static method creates a new inline group in the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) + */ groupCollapsed(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + /** + * The **`console.groupEnd()`** static method exits the current inline group in the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) + */ groupEnd(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + /** + * The **`console.info()`** static method outputs a message to the console at the 'info' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) + */ info(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + /** + * The **`console.log()`** static method outputs a message to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) + */ log(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + /** + * The **`console.table()`** static method displays tabular data as a table. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) + */ table(tabularData?: any, properties?: string[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + /** + * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) + */ time(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + /** + * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) + */ timeEnd(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + /** + * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) + */ timeLog(label?: string, ...data: any[]): void; timeStamp(label?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + /** + * The **`console.trace()`** static method outputs a stack trace to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) + */ trace(...data: any[]): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + /** + * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) + */ warn(...data: any[]): void; } declare const console: Console; @@ -208,7 +298,7 @@ declare namespace WebAssembly { function validate(bytes: BufferSource): boolean; } /** - * This ServiceWorker API interface represents the global execution context of a service worker. + * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) @@ -293,18 +383,11 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { FixedLengthStream: typeof FixedLengthStream; IdentityTransformStream: typeof IdentityTransformStream; HTMLRewriter: typeof HTMLRewriter; - Performance: typeof Performance; - PerformanceEntry: typeof PerformanceEntry; - PerformanceMark: typeof PerformanceMark; - PerformanceMeasure: typeof PerformanceMeasure; - PerformanceResourceTiming: typeof PerformanceResourceTiming; - PerformanceObserver: typeof PerformanceObserver; - PerformanceObserverEntryList: typeof PerformanceObserverEntryList; } declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; /** - * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * 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) */ @@ -365,57 +448,82 @@ interface TestController { interface ExecutionContext { waitUntil(promise: Promise): void; passThroughOnException(): void; + readonly exports: Cloudflare.Exports; readonly props: Props; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | 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; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; + 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; } interface StructuredSerializeOptions { transfer?: any[]; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */ -declare abstract class PromiseRejectionEvent extends Event { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ - readonly promise: Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ - readonly reason: any; -} declare abstract class Navigator { - sendBeacon(url: string, body?: (ReadableStream | string | (ArrayBuffer | ArrayBufferView) | Blob | FormData | URLSearchParams | URLSearchParams)): boolean; + sendBeacon(url: string, body?: BodyInit): boolean; readonly userAgent: string; readonly hardwareConcurrency: number; + readonly platform: string; readonly language: string; readonly languages: string[]; } interface AlarmInvocationInfo { readonly isRetry: boolean; readonly retryCount: number; + readonly scheduledTime: number; } interface Cloudflare { readonly compatibilityFlags: Record; } +interface CachePurgeError { + code: number; + message: string; +} +interface CachePurgeResult { + success: boolean; + errors: CachePurgeError[]; +} +interface CachePurgeOptions { + tags?: string[]; + pathPrefixes?: string[]; + purgeEverything?: boolean; +} +interface CacheContext { + purge(options: CachePurgeOptions): Promise; +} +interface CloudflareAccessContext { + readonly aud: string; + getIdentity(): Promise; +} +declare abstract class ColoLocalActorNamespace { + get(actorId: string): Fetcher; +} interface DurableObject { fetch(request: Request): Response | Promise; + connect?(socket: Socket): void | Promise; alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; webSocketError?(ws: WebSocket, error: unknown): void | Promise; } -type DurableObjectStub = Fetcher & { +type DurableObjectStub = Fetcher & { readonly id: DurableObjectId; readonly name?: string; }; @@ -423,6 +531,7 @@ interface DurableObjectId { toString(): string; equals(other: DurableObjectId): boolean; readonly name?: string; + readonly jurisdiction?: string; } declare abstract class DurableObjectNamespace { newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; @@ -432,22 +541,26 @@ declare abstract class DurableObjectNamespace; jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; } -type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; +type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us"; interface DurableObjectNamespaceNewUniqueIdOptions { jurisdiction?: DurableObjectJurisdiction; } -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +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> { } 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[]; @@ -524,6 +637,16 @@ declare class WebSocketRequestResponsePair { get request(): string; get response(): string; } +interface DurableObjectFacets { + get(name: string, getStartupOptions: () => FacetStartupOptions | Promise>): Fetcher; + abort(name: string, reason: any): void; + delete(name: string): void; + clone(src: string, dst: string): void; +} +interface FacetStartupOptions { + id?: DurableObjectId | string; + class: DurableObjectClass; +} interface AnalyticsEngineDataset { writeDataPoint(event?: AnalyticsEngineDataPoint): void; } @@ -533,116 +656,120 @@ interface AnalyticsEngineDataPoint { blobs?: ((ArrayBuffer | string) | null)[]; } /** - * An event which takes place in the DOM. + * The **`Event`** interface represents an event which takes place on an `EventTarget`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ declare class Event { constructor(type: string, init?: EventInit); /** - * Returns the type of event, e.g. "click", "hashchange", or "submit". + * The **`type`** read-only property of the Event interface returns a string containing the event's type. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) */ get type(): string; /** - * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * The **`eventPhase`** read-only property of the being evaluated. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) */ get eventPhase(): number; /** - * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) */ get composed(): boolean; /** - * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) */ get bubbles(): boolean; /** - * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) */ get cancelable(): boolean; /** - * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) */ get defaultPrevented(): boolean; /** + * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) */ get returnValue(): boolean; /** - * Returns the object whose event listener's callback is currently being invoked. + * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) */ get currentTarget(): EventTarget | undefined; /** - * Returns the object to which event is dispatched (its target). + * The read-only **`target`** property of the dispatched. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) */ get target(): EventTarget | undefined; /** + * The deprecated **`Event.srcElement`** is an alias for the Event.target property. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) */ get srcElement(): EventTarget | undefined; /** - * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) */ get timeStamp(): number; /** - * Returns true if event was dispatched by the user agent, and false otherwise. + * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) */ get isTrusted(): boolean; /** + * The **`cancelBubble`** property of the Event interface is deprecated. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) */ get cancelBubble(): boolean; /** + * The **`cancelBubble`** property of the Event interface is deprecated. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) */ set cancelBubble(value: boolean); /** - * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) */ stopImmediatePropagation(): void; /** - * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) */ preventDefault(): void; /** - * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) */ stopPropagation(): void; /** - * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) */ @@ -663,38 +790,26 @@ interface EventListenerObject { } type EventListenerOrEventListenerObject = EventListener | EventListenerObject; /** - * EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. + * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) */ declare class EventTarget = Record> { constructor(); /** - * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. - * - * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. - * - * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. - * - * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. - * - * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. - * - * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. - * - * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) */ addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; /** - * Removes the event listener in target's event listener list with the same type, callback, and options. + * 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; /** - * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * 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) */ @@ -713,50 +828,70 @@ interface EventTargetHandlerObject { handleEvent: (event: Event) => any | undefined; } /** - * A controller object that allows you to abort one or more DOM requests as and when desired. + * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) */ declare class AbortController { constructor(); /** - * Returns the AbortSignal object associated with this object. + * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) */ get signal(): AbortSignal; /** - * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) */ abort(reason?: any): void; } /** - * A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. + * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) */ declare abstract class AbortSignal extends EventTarget { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + /** + * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) + */ static abort(reason?: any): AbortSignal; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + /** + * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) + */ static timeout(delay: number): AbortSignal; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */ + /** + * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) + */ static any(signals: AbortSignal[]): AbortSignal; /** - * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) */ get aborted(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + /** + * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) + */ get reason(): any; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ get onabort(): any | null; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ set onabort(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + /** + * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) + */ throwIfAborted(): void; } interface Scheduler { @@ -766,19 +901,27 @@ interface SchedulerWaitOptions { signal?: AbortSignal; } /** - * Extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. + * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ declare abstract class ExtendableEvent extends Event { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + /** + * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) + */ waitUntil(promise: Promise): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ +/** + * The **`CustomEvent`** interface represents events initialized by an application for any purpose. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) + */ declare class CustomEvent extends Event { constructor(type: string, init?: CustomEventCustomEventInit); /** - * Returns any custom data event was created with. Typically used for synthetic events. + * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) */ @@ -791,40 +934,76 @@ interface CustomEventCustomEventInit { detail?: any; } /** - * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. + * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ declare class Blob { - constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); + /** + * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) + */ get size(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + /** + * The **`type`** read-only property of the Blob interface returns the MIME type of the file. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) + */ get type(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + /** + * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) + */ slice(start?: number, end?: number, type?: string): Blob; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + /** + * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) + */ arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) */ + /** + * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) + */ bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + /** + * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) + */ text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + /** + * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) + */ stream(): ReadableStream; } interface BlobOptions { type?: string; } /** - * Provides information about files and allows JavaScript in a web page to access their content. + * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ declare class File extends Blob { constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + /** + * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) + */ get name(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + /** + * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) + */ get lastModified(): number; } interface FileOptions { @@ -837,7 +1016,11 @@ interface FileOptions { * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) */ declare abstract class CacheStorage { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + /** + * The **`open()`** method of the the Cache object matching the `cacheName`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) + */ open(cacheName: string): Promise; readonly default: Cache; } @@ -867,14 +1050,20 @@ interface CacheQueryOptions { */ declare abstract class Crypto { /** + * The **`Crypto.subtle`** read-only property returns a cryptographic operations. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) */ get subtle(): SubtleCrypto; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + /** + * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) + */ getRandomValues(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) @@ -883,52 +1072,116 @@ declare abstract class Crypto { DigestStream: typeof DigestStream; } /** - * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). + * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) */ declare abstract class SubtleCrypto { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) */ + /** + * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) + */ encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */ + /** + * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) + */ decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) */ + /** + * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) + */ sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) */ + /** + * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) + */ verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */ + /** + * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) + */ digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + /** + * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) + */ generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + /** + * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) + */ deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */ + /** + * The **`deriveBits()`** method of the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) + */ deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + /** + * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) + */ importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */ + /** + * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) + */ exportKey(format: string, key: CryptoKey): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) */ + /** + * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) + */ wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + /** + * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) + */ unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; } /** - * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. + * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) */ declare abstract class CryptoKey { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + /** + * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) + */ readonly type: string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + /** + * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) + */ readonly extractable: boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + /** + * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) + */ readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + /** + * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) + */ readonly usages: string[]; } interface CryptoKeyPair { @@ -1035,24 +1288,14 @@ declare class DigestStream extends WritableStream get bytesWritten(): number | bigint; } /** - * A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. + * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) */ declare class TextDecoder { constructor(label?: string, options?: TextDecoderConstructorOptions); /** - * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. - * - * ``` - * var string = "", decoder = new TextDecoder(encoding), buffer; - * while(buffer = next_chunk()) { - * string += decoder.decode(buffer, {stream:true}); - * } - * string += decoder.decode(); // end-of-queue - * ``` - * - * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) */ @@ -1062,24 +1305,24 @@ declare class TextDecoder { get ignoreBOM(): boolean; } /** - * TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. + * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) */ declare class TextEncoder { constructor(); /** - * Returns the result of running UTF-8's encoder. + * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) */ encode(input?: string): Uint8Array; /** - * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) */ - encodeInto(input: string, buffer: ArrayBuffer | ArrayBufferView): TextEncoderEncodeIntoResult; + encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; get encoding(): string; } interface TextDecoderConstructorOptions { @@ -1094,21 +1337,41 @@ interface TextEncoderEncodeIntoResult { written: number; } /** - * Events providing information related to errors in scripts or in files. + * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) */ declare class ErrorEvent extends Event { constructor(type: string, init?: ErrorEventErrorEventInit); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + /** + * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) + */ get filename(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + /** + * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) + */ get message(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + /** + * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) + */ get lineno(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + /** + * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) + */ get colno(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + /** + * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) + */ get error(): any; } interface ErrorEventErrorEventInit { @@ -1119,38 +1382,38 @@ interface ErrorEventErrorEventInit { error?: any; } /** - * A message received by a target object. + * The **`MessageEvent`** interface represents a message received by a target object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) */ declare class MessageEvent extends Event { constructor(type: string, initializer: MessageEventInit); /** - * Returns the data of the message. + * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) */ readonly data: any; /** - * Returns the origin of the message, for server-sent events and cross-document messaging. + * The **`origin`** read-only property of the origin of the message emitter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) */ readonly origin: string | null; /** - * Returns the last event ID string, for server-sent events. + * The **`lastEventId`** read-only property of the unique ID for the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) */ readonly lastEventId: string; /** - * Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects. + * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) */ readonly source: MessagePort | null; /** - * Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. + * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) */ @@ -1160,27 +1423,90 @@ interface MessageEventInit { data: ArrayBuffer | string; } /** - * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". + * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) + */ +declare abstract class PromiseRejectionEvent extends Event { + /** + * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) + */ + readonly promise: Promise; + /** + * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) + */ + readonly reason: any; +} +/** + * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ declare class FormData { constructor(); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ append(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ append(name: string, value: Blob, filename?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */ + /** + * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) + */ delete(name: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */ + /** + * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) + */ get(name: string): (File | string) | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */ + /** + * 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)[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ + /** + * 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; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ set(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ set(name: string, value: Blob, filename?: string): void; /* Returns an array of key, value pairs for every entry in the list. */ entries(): IterableIterator<[ @@ -1268,37 +1594,69 @@ interface DocumentEnd { append(content: string, options?: ContentOptions): DocumentEnd; } /** - * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch. + * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) */ declare abstract class FetchEvent extends ExtendableEvent { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ readonly request: Request; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + /** + * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) + */ respondWith(promise: Response | Promise): void; passThroughOnException(): void; } type HeadersInit = Headers | Iterable> | Record; /** - * This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. + * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) */ declare class Headers { constructor(init?: HeadersInit); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */ + /** + * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) + */ get(name: string): string | null; getAll(name: string): string[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */ + /** + * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) + */ getSetCookie(): string[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */ + /** + * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) + */ has(name: string): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */ + /** + * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) + */ set(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */ + /** + * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) + */ append(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */ + /** + * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) + */ delete(name: string): void; forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ @@ -1315,7 +1673,7 @@ declare class Headers { value: string ]>; } -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; +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; @@ -1335,40 +1693,72 @@ declare abstract class Body { blob(): Promise; } /** - * This Fetch API interface represents the response to a request. + * The **`Response`** interface of the Fetch API represents the response to a request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ declare var Response: { prototype: Response; - new(body?: BodyInit | null, init?: ResponseInit): Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; error(): Response; redirect(url: string, status?: number): Response; json(any: any, maybeInit?: (ResponseInit | Response)): Response; }; /** - * This Fetch API interface represents the response to a request. + * The **`Response`** interface of the Fetch API represents the response to a request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ interface Response extends Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + /** + * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) + */ clone(): Response; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + /** + * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) + */ status: number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + /** + * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) + */ statusText: string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ headers: Headers; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + /** + * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) + */ ok: boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + /** + * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) + */ redirected: boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + /** + * The **`url`** read-only property of the Response interface contains the URL of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) + */ url: string; webSocket: WebSocket | null; cf: any | undefined; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) */ + /** + * The **`type`** read-only property of the Response interface contains the type of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) + */ type: "default" | "error"; } interface ResponseInit { @@ -1381,7 +1771,7 @@ interface ResponseInit { } type RequestInfo> = Request | string; /** - * This Fetch API interface represents a resource request. + * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ @@ -1390,59 +1780,63 @@ declare var Request: { new >(input: RequestInfo | URL, init?: RequestInit): Request; }; /** - * This Fetch API interface represents a resource request. + * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ interface Request> extends Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + /** + * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) + */ clone(): Request; /** - * Returns request's HTTP method, which is "GET" by default. + * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) */ method: string; /** - * Returns the URL of request as a string. + * The **`url`** read-only property of the Request interface contains the URL of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) */ url: string; /** - * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * The **`headers`** read-only property of the with the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) */ headers: Headers; /** - * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) */ redirect: string; fetcher: Fetcher | null; /** - * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) */ signal: AbortSignal; - cf: Cf | undefined; + cf?: Cf; /** - * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) */ integrity: string; /** - * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) */ keepalive: boolean; /** - * Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. + * The **`cache`** read-only property of the Request interface contains the cache mode of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) */ @@ -1541,8 +1935,31 @@ interface KVNamespaceGetWithMetadataResult { } type QueueContentType = "text" | "bytes" | "json" | "v8"; interface Queue { - 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; +} +interface QueueSendMetadata { + metrics: QueueSendMetrics; +} +interface QueueSendResponse { + metadata: QueueSendMetadata; +} +interface QueueSendBatchMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface QueueSendBatchMetadata { + metrics: QueueSendBatchMetrics; +} +interface QueueSendBatchResponse { + metadata: QueueSendBatchMetadata; } interface QueueSendOptions { contentType?: QueueContentType; @@ -1556,6 +1973,19 @@ interface MessageSendRequest { contentType?: QueueContentType; delaySeconds?: number; } +interface QueueMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface MessageBatchMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface MessageBatchMetadata { + metrics: MessageBatchMetrics; +} interface QueueRetryOptions { delaySeconds?: number; } @@ -1570,12 +2000,14 @@ interface Message { interface QueueEvent extends ExtendableEvent { readonly messages: readonly Message[]; readonly queue: string; + readonly metadata: MessageBatchMetadata; retryAll(options?: QueueRetryOptions): void; ackAll(): void; } interface MessageBatch { readonly messages: readonly Message[]; readonly queue: string; + readonly metadata: MessageBatchMetadata; retryAll(options?: QueueRetryOptions): void; ackAll(): void; } @@ -1594,7 +2026,7 @@ interface R2ListOptions { startAfter?: string; include?: ("httpMetadata" | "customMetadata")[]; } -declare abstract class R2Bucket { +interface R2Bucket { head(key: string): Promise; get(key: string, options: R2GetOptions & { onlyIf: R2Conditional | Headers; @@ -1763,6 +2195,8 @@ interface Transformer { expectedLength?: number; } interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * @@ -1781,8 +2215,6 @@ interface StreamPipeOptions { * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; - preventAbort?: boolean; - preventCancel?: boolean; signal?: AbortSignal; } type ReadableStreamReadResult = { @@ -1793,24 +2225,52 @@ type ReadableStreamReadResult = { value?: undefined; }; /** - * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ interface ReadableStream { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + /** + * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) + */ get locked(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + /** + * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) + */ cancel(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ getReader(): ReadableStreamDefaultReader; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + /** + * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) + */ pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + /** + * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) + */ pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + /** + * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) + */ tee(): [ ReadableStream, ReadableStream @@ -1819,33 +2279,57 @@ interface ReadableStream { [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; } /** - * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ declare const ReadableStream: { prototype: ReadableStream; - new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ +/** + * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) + */ declare class ReadableStreamDefaultReader { constructor(stream: ReadableStream); get closed(): Promise; cancel(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + /** + * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) + */ read(): Promise>; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + /** + * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) + */ releaseLock(): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ +/** + * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) + */ declare class ReadableStreamBYOBReader { constructor(stream: ReadableStream); get closed(): Promise; cancel(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + /** + * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) + */ read(view: T): Promise>; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + /** + * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) + */ releaseLock(): void; readAtLeast(minElements: number, view: T): Promise>; } @@ -1860,115 +2344,259 @@ interface ReadableStreamGetReaderOptions { */ mode: "byob"; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +/** + * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) + */ declare abstract class ReadableStreamBYOBRequest { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + /** + * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) + */ get view(): Uint8Array | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + /** + * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) + */ respond(bytesWritten: number): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + /** + * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) + */ respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; get atLeast(): number | null; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +/** + * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) + */ declare abstract class ReadableStreamDefaultController { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + /** + * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) + */ get desiredSize(): number | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ close(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + /** + * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) + */ enqueue(chunk?: R): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) + */ error(reason: any): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +/** + * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) + */ declare abstract class ReadableByteStreamController { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + /** + * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) + */ get byobRequest(): ReadableStreamBYOBRequest | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + /** + * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) + */ get desiredSize(): number | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ close(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + /** + * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) + */ enqueue(chunk: ArrayBuffer | ArrayBufferView): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + /** + * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) + */ error(reason: any): void; } /** - * This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. + * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) */ declare abstract class WritableStreamDefaultController { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + /** + * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) + */ get signal(): AbortSignal; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) + */ error(reason?: any): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +/** + * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) + */ declare abstract class TransformStreamDefaultController { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + /** + * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) + */ get desiredSize(): number | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + /** + * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) + */ enqueue(chunk?: O): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + /** + * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) + */ error(reason: any): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + /** + * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) + */ terminate(): void; } interface ReadableWritablePair { + readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; - readable: ReadableStream; } /** - * This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. + * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) */ declare class WritableStream { constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + /** + * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) + */ get locked(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + /** + * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) + */ abort(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ close(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + /** + * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) + */ getWriter(): WritableStreamDefaultWriter; } /** - * This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. + * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) */ declare class WritableStreamDefaultWriter { constructor(stream: WritableStream); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + /** + * The **`closed`** read-only property of the the stream errors or the writer's lock is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) + */ get closed(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + /** + * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) + */ get ready(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + /** + * The **`desiredSize`** read-only property of the to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) + */ get desiredSize(): number | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + /** + * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) + */ abort(reason?: any): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ close(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ write(chunk?: W): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ releaseLock(): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ +/** + * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) + */ declare class TransformStream { constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + /** + * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) + */ get readable(): ReadableStream; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + /** + * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) + */ get writable(): WritableStream; } declare class FixedLengthStream extends IdentityTransformStream { @@ -1983,20 +2611,36 @@ interface IdentityTransformStreamQueuingStrategy { interface ReadableStreamValuesOptions { preventCancel?: boolean; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ +/** + * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) + */ declare class CompressionStream extends TransformStream { constructor(format: "gzip" | "deflate" | "deflate-raw"); } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ +/** + * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) + */ declare class DecompressionStream extends TransformStream { constructor(format: "gzip" | "deflate" | "deflate-raw"); } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */ +/** + * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) + */ declare class TextEncoderStream extends TransformStream { constructor(); get encoding(): string; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ +/** + * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) + */ declare class TextDecoderStream extends TransformStream { constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); get encoding(): string; @@ -2008,25 +2652,33 @@ interface TextDecoderStreamTextDecoderStreamInit { ignoreBOM?: boolean; } /** - * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. + * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) */ declare class ByteLengthQueuingStrategy implements QueuingStrategy { constructor(init: QueuingStrategyInit); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + /** + * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) + */ get highWaterMark(): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ get size(): (chunk?: any) => number; } /** - * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. + * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) */ declare class CountQueuingStrategy implements QueuingStrategy { constructor(init: QueuingStrategyInit); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + /** + * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) + */ get highWaterMark(): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ get size(): (chunk?: any) => number; @@ -2039,6 +2691,11 @@ interface QueuingStrategyInit { */ highWaterMark: number; } +interface TracePreviewInfo { + id: string; + slug: string; + name: string; +} interface ScriptVersion { id?: string; tag?: string; @@ -2049,7 +2706,7 @@ declare abstract class TailEvent extends ExtendableEvent { readonly traces: TraceItem[]; } interface TraceItem { - readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; + readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; readonly eventTimestamp: number | null; readonly logs: TraceLog[]; readonly exceptions: TraceException[]; @@ -2059,6 +2716,8 @@ interface TraceItem { readonly scriptVersion?: ScriptVersion; readonly dispatchNamespace?: string; readonly scriptTags?: string[]; + readonly tailAttributes?: Record; + readonly preview?: TracePreviewInfo; readonly durableObjectId?: string; readonly outcome: string; readonly executionModel: string; @@ -2069,6 +2728,8 @@ interface TraceItem { interface TraceItemAlarmEventInfo { readonly scheduledTime: Date; } +interface TraceItemConnectEventInfo { +} interface TraceItemCustomEventInfo { } interface TraceItemScheduledEventInfo { @@ -2145,111 +2806,231 @@ interface UnsafeTraceMetrics { fromTrace(item: TraceItem): TraceMetrics; } /** - * The URL interface represents an object providing static methods used for creating object URLs. + * The **`URL`** interface is used to parse, construct, normalize, and encode URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) */ declare class URL { constructor(url: string | URL, base?: string | URL); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + /** + * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) + */ get origin(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ get href(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ set href(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ get protocol(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ set protocol(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ get username(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ set username(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ get password(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ - set password(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ - get host(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + /** + * The **`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); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ get hostname(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ set hostname(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ get port(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ set port(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ get pathname(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ set pathname(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ get search(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ set search(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ get hash(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ set hash(value: string); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + /** + * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) + */ get searchParams(): URLSearchParams; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + /** + * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) + */ toJSON(): string; /*function toString() { [native code] }*/ toString(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + /** + * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) + */ static canParse(url: string, base?: string): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */ + /** + * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) + */ static parse(url: string, base?: string): URL | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */ + /** + * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) + */ static createObjectURL(object: File | Blob): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */ + /** + * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) + */ static revokeObjectURL(object_url: string): void; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ +/** + * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) + */ declare class URLSearchParams { constructor(init?: (Iterable> | Record | string)); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) */ + /** + * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) + */ get size(): number; /** - * Appends a specified key/value pair as a new search parameter. + * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. + * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) */ delete(name: string, value?: string): void; /** - * Returns the first value associated to the given search parameter. + * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. + * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. + * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) */ has(name: string, value?: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) */ set(name: string, value: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) */ + /** + * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) + */ sort(): void; /* Returns an array of key, value pairs for every entry in the search params. */ entries(): IterableIterator<[ @@ -2261,7 +3042,7 @@ declare class URLSearchParams { /* 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] } Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ + /*function toString() { [native code] }*/ toString(): string; [Symbol.iterator](): IterableIterator<[ key: string, @@ -2312,26 +3093,26 @@ interface URLPatternOptions { ignoreCase?: boolean; } /** - * A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. + * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) */ declare class CloseEvent extends Event { constructor(type: string, initializer?: CloseEventInit); /** - * Returns the WebSocket connection close code provided by the server. + * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) */ readonly code: number; /** - * Returns the WebSocket connection close reason provided by the server. + * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) */ readonly reason: string; /** - * Returns true if the connection closed cleanly; false otherwise. + * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) */ @@ -2349,13 +3130,13 @@ type WebSocketEventMap = { error: ErrorEvent; }; /** - * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ declare var WebSocket: { prototype: WebSocket; - new(url: string, protocols?: (string[] | string)): WebSocket; + new (url: string, protocols?: (string[] | string)): WebSocket; readonly READY_STATE_CONNECTING: number; readonly CONNECTING: number; readonly READY_STATE_OPEN: number; @@ -2366,20 +3147,20 @@ declare var WebSocket: { readonly CLOSED: number; }; /** - * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(): void; + accept(options?: WebSocketAcceptOptions): void; /** - * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) */ send(message: (ArrayBuffer | ArrayBufferView) | string): void; /** - * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) */ @@ -2387,32 +3168,48 @@ interface WebSocket extends EventTarget { serializeAttachment(attachment: any): void; deserializeAttachment(): any | null; /** - * Returns the state of the WebSocket object's connection. It can have the values described below. + * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) */ readyState: number; /** - * Returns the URL that was used to establish the WebSocket connection. + * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) */ url: string | null; /** - * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) */ protocol: string | null; /** - * Returns the extensions selected by the server, if any. + * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) */ extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: "blob" | "arraybuffer"; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; } declare const WebSocketPair: { - new(): { + new (): { 0: WebSocket; 1: WebSocket; }; @@ -2468,29 +3265,33 @@ interface SocketInfo { remoteAddress?: string; localAddress?: string; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ +/** + * The **`EventSource`** interface is web content's interface to server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) + */ declare class EventSource extends EventTarget { constructor(url: string, init?: EventSourceEventSourceInit); /** - * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) */ close(): void; /** - * Returns the URL providing the event stream. + * The **`url`** read-only property of the URL of the source. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) */ get url(): string; /** - * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) */ get withCredentials(): boolean; /** - * Returns the state of this EventSource object's connection. It can have the values described below. + * The **`readyState`** read-only property of the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) */ @@ -2516,6 +3317,28 @@ interface EventSourceEventSourceInit { withCredentials?: boolean; fetcher?: Fetcher; } +interface ExecOutput { + readonly stdout: ArrayBuffer; + readonly stderr: ArrayBuffer; + readonly exitCode: number; +} +interface ContainerExecOptions { + cwd?: string; + env?: Record; + user?: string; + stdin?: ReadableStream | "pipe"; + stdout?: "pipe" | "ignore"; + stderr?: "pipe" | "ignore" | "combined"; +} +interface ExecProcess { + readonly stdin: WritableStream | null; + readonly stdout: ReadableStream | null; + readonly stderr: ReadableStream | null; + readonly pid: number; + readonly exitCode: Promise; + output(): Promise; + kill(signal?: number): void; +} interface Container { get running(): boolean; start(options?: ContainerStartupOptions): void; @@ -2523,34 +3346,64 @@ interface Container { destroy(error?: any): Promise; signal(signo: number): void; getTcpPort(port: number): Fetcher; + setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; + snapshotDirectory(options: ContainerDirectorySnapshotOptions): Promise; + snapshotContainer(options: ContainerSnapshotOptions): Promise; + interceptOutboundHttps(addr: string, binding: Fetcher): Promise; + exec(cmd: string[], options?: ContainerExecOptions): Promise; +} +interface ContainerDirectorySnapshot { + id: string; + size: number; + dir: string; + name?: string; +} +interface ContainerDirectorySnapshotOptions { + dir: string; + name?: string; +} +interface ContainerDirectorySnapshotRestoreParams { + snapshot: ContainerDirectorySnapshot; + mountPoint?: string; +} +interface ContainerSnapshot { + id: string; + size: number; + name?: string; +} +interface ContainerSnapshotOptions { + name?: string; } interface ContainerStartupOptions { entrypoint?: string[]; enableInternet: boolean; env?: Record; + labels?: Record; + directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; + containerSnapshot?: ContainerSnapshot; } /** - * This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. + * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ declare abstract class MessagePort extends EventTarget { /** - * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. - * - * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. + * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) */ postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; /** - * Disconnects the port, so that it is no longer active. + * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) */ close(): void; /** - * Begins dispatching messages received on the port. + * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) */ @@ -2559,20 +3412,20 @@ declare abstract class MessagePort extends EventTarget { set onmessage(value: any | null); } /** - * This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties. + * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) */ declare class MessageChannel { constructor(); /** - * Returns the first MessagePort object. + * 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; /** - * Returns the second MessagePort object. + * 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) */ @@ -2592,6 +3445,10 @@ type LoopbackDurableObjectClass DurableObjectClass : (opts: { props?: any; }) => DurableObjectClass); +interface LoopbackDurableObjectNamespace extends DurableObjectNamespace { +} +interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace { +} interface SyncKvStorage { get(key: string): T | undefined; list(options?: SyncKvListOptions): Iterable<[ @@ -2611,12 +3468,15 @@ interface SyncKvListOptions { } interface WorkerStub { getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; + getDurableObjectClass(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass; } interface WorkerStubEntrypointOptions { props?: any; + limits?: workerdResourceLimits; } interface WorkerLoader { - get(name: string, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; } interface WorkerLoaderModule { js?: string; @@ -2625,11 +3485,13 @@ interface WorkerLoaderModule { data?: ArrayBuffer; json?: any; py?: string; + wasm?: ArrayBuffer; } interface WorkerLoaderWorkerCode { compatibilityDate: string; compatibilityFlags?: string[]; allowExperimental?: boolean; + limits?: workerdResourceLimits; mainModule: string; modules: Record; env?: any; @@ -2637,837 +3499,2046 @@ interface WorkerLoaderWorkerCode { tails?: Fetcher[]; streamingTails?: Fetcher[]; } +interface workerdResourceLimits { + 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/) */ -declare abstract class Performance extends EventTarget { +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; - get eventCounts(): EventCounts; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/clearMarks) */ - clearMarks(name?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/clearMeasures) */ - clearMeasures(name?: string): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/clearResourceTimings) */ - clearResourceTimings(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/getEntries) */ - getEntries(): PerformanceEntry[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/getEntriesByName) */ - getEntriesByName(name: string, type?: string): PerformanceEntry[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/getEntriesByType) */ - getEntriesByType(type: string): PerformanceEntry[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/mark) */ - mark(name: string, options?: PerformanceMarkOptions): PerformanceMark; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/measure) */ - measure(measureName: string, measureOptionsOrStartMark: PerformanceMeasureOptions | string, maybeEndMark?: string): PerformanceMeasure; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/setResourceTimingBufferSize) */ - setResourceTimingBufferSize(size: number): void; -} -/** - * PerformanceMark is an abstract interface for PerformanceEntry objects with an entryType of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceMark) - */ -declare class PerformanceMark extends PerformanceEntry { - constructor(name: string, maybeOptions?: PerformanceMarkOptions); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceMark/detail) */ - get detail(): any | undefined; - toJSON(): any; + /** + * 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; +} +declare abstract class Span { + get isTraced(): boolean; + setAttribute(key: string, value?: (boolean | number | string)): void; + end(): void; } /** - * PerformanceMeasure is an abstract interface for PerformanceEntry objects with an entryType of "measure". Entries of this type are created by calling performance.measure() to add a named DOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline. + * Represents the identity of a user authenticated via Cloudflare Access. + * This matches the result of calling /cdn-cgi/access/get-identity. * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceMeasure) + * The exact structure of the returned object depends on the identity provider + * configuration for the Access application. The fields below represent commonly + * available properties, but additional provider-specific fields may be present. */ -declare abstract class PerformanceMeasure extends PerformanceEntry { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceMeasure/detail) */ - get detail(): any | undefined; - toJSON(): any; +interface CloudflareAccessIdentity extends Record { + /** The user's email address, if available from the identity provider. */ + email?: string; + /** The user's display name. */ + name?: string; + /** The user's unique identifier. */ + user_uuid?: string; + /** The Cloudflare account ID. */ + account_id?: string; + /** Login timestamp (Unix epoch seconds). */ + iat?: number; + /** The user's IP address at authentication time. */ + ip?: string; + /** Authentication methods used (e.g., "pwd"). */ + amr?: string[]; + /** Identity provider information. */ + idp?: { + id: string; + type: string; + }; + /** Geographic information about where the user authenticated. */ + geo?: { + country: string; + }; + /** Group memberships from the identity provider. */ + groups?: Array<{ + id: string; + name: string; + email?: string; + }>; + /** Device posture check results, keyed by check ID. */ + devicePosture?: Record; + /** True if the user connected via Cloudflare WARP. */ + is_warp?: boolean; + /** True if the user is authenticated via Cloudflare Gateway. */ + is_gateway?: boolean; +} +// ============================================================================ +// Agent Memory +// +// Public type surface for user Workers binding to an Agent Memory namespace. +// ============================================================================ +/** Memory type — every memory is classified into exactly one. */ +type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task"; +/** Search intensity for recall. */ +type AgentMemoryThinkingLevel = "low" | "medium" | "high"; +/** Response verbosity for recall. */ +type AgentMemoryResponseLength = "short" | "medium" | "long"; +/** A conversation message passed to ingest(). */ +interface AgentMemoryMessage { + role: "system" | "user" | "assistant"; + content: string; + /** Optional message timestamp. */ + timestamp?: Date; } -interface PerformanceMarkOptions { - detail?: any; - startTime?: number; +/** 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; } -interface PerformanceMeasureOptions { - detail?: any; - start?: number; - duration?: number; - end?: number; +/** 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; +} +/** 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; +} +/** Options for the ingest() method. */ +interface AgentMemoryIngestOptions { + /** 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; } -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceObserverEntryList) */ -declare abstract class PerformanceObserverEntryList { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceObserverEntryList/getEntries) */ - getEntries(): PerformanceEntry[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceObserverEntryList/getEntriesByType) */ - getEntriesByType(type: string): PerformanceEntry[]; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceObserverEntryList/getEntriesByName) */ - getEntriesByName(name: string, type?: string): PerformanceEntry[]; +/** Response from the getSummary() method. */ +interface AgentMemoryGetSummaryResponse { + /** Markdown summary. */ + summary: string; } /** - * Encapsulates a single performance metric that is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways such as loading a resource (such as an image). + * Options for the recall() method. * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceEntry) + * `referenceDate` accepts a Date object, an ISO-8601 date string + * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this + * date is used as "today" for resolving relative time references + * ("how many days ago", "last week") instead of the server's wall-clock time. */ -declare abstract class PerformanceEntry { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceEntry/name) */ - get name(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceEntry/entryType) */ - get entryType(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceEntry/startTime) */ - get startTime(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceEntry/duration) */ - get duration(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceEntry/toJSON) */ - toJSON(): any; +interface AgentMemoryRecallOptions { + /** Recall intensity: "low" (default), "medium", or "high". */ + thinkingLevel?: AgentMemoryThinkingLevel; + /** Response verbosity: "short", "medium" (default), or "long". */ + responseLength?: AgentMemoryResponseLength; + /** Temporal anchor for date arithmetic. */ + referenceDate?: Date | string; +} +/** Response from the recall() method. */ +interface AgentMemoryRecallResult { + /** Number of memories retrieved. */ + count: number; + /** LLM-generated answer synthesizing the matching memories. */ + answer: string; + /** Matching memories ranked by relevance. */ + candidates: AgentMemoryScoredCandidate[]; } /** - * Enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an XMLHttpRequest, , image, or script. + * Options for the list() method. * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming) - */ -declare abstract class PerformanceResourceTiming extends PerformanceEntry { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/connectEnd) */ - get connectEnd(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/connectStart) */ - get connectStart(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/decodedBodySize) */ - get decodedBodySize(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/domainLookupEnd) */ - get domainLookupEnd(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/domainLookupStart) */ - get domainLookupStart(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/encodedBodySize) */ - get encodedBodySize(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/fetchStart) */ - get fetchStart(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/initiatorType) */ - get initiatorType(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/nextHopProtocol) */ - get nextHopProtocol(): string; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/redirectEnd) */ - get redirectEnd(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/redirectStart) */ - get redirectStart(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/requestStart) */ - get requestStart(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseEnd) */ - get responseEnd(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseStart) */ - get responseStart(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseStatus) */ - get responseStatus(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/secureConnectionStart) */ - get secureConnectionStart(): number | undefined; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/transferSize) */ - get transferSize(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/workerStart) */ - get workerStart(): number; -} -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceObserver) */ -declare class PerformanceObserver { - constructor(callback: any); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceObserver/disconnect) */ - disconnect(): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceObserver/observe) */ - observe(options?: PerformanceObserverObserveOptions): void; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceObserver/takeRecords) */ - takeRecords(): PerformanceEntry[]; - readonly supportedEntryTypes: string[]; -} -interface PerformanceObserverObserveOptions { - buffered?: boolean; - durationThreshold?: number; - entryTypes?: string[]; - type?: string; + * `cursor` is the opaque continuation token returned by the previous page; + * pass it back unchanged to fetch the next page. `sessionId` and `type` + * are exact-match filters; combining them is allowed. + */ +interface AgentMemoryListMemoriesOptions { + /** Maximum number of memories to return. Default 20, max 500. */ + limit?: number; + /** Opaque cursor from a previous page. */ + cursor?: string; + /** Exact-match session filter. */ + sessionId?: string; + /** Exact-match memory-type filter. */ + type?: AgentMemoryMemoryType; +} +/** Response from the list() method. */ +interface AgentMemoryListMemoriesResult { + memories: AgentMemoryMemoryListEntry[]; + /** Continuation cursor; absent when this page exhausted the result set. */ + cursor?: string; } -interface EventCounts { - get size(): number; - get(eventType: string): number | undefined; - has(eventType: string): boolean; - entries(): IterableIterator; - keys(): IterableIterator; - values(): IterableIterator; - forEach(param1: (param0: number, param1: string, param2: EventCounts) => void, param2?: any): void; - [Symbol.iterator](): IterableIterator; +/** + * A single Agent Memory profile, scoped to a profile name. + * + * Returned by {@link AgentMemoryNamespace.getProfile}. + */ +declare abstract class AgentMemoryProfile { + /** + * Retrieve a memory by ID. + * + * @param memoryId - ULID of the memory to retrieve. + * @throws if the memory does not exist. + */ + get(memoryId: string): Promise; + /** + * Delete a memory by ID. + * + * Removes the memory and any source messages linked by the memory's + * source message IDs. + * + * @param memoryId - ULID of the memory to delete. + * @throws if the memory does not exist. + */ + delete(memoryId: string): Promise; + /** + * Store a memory in this profile. The content is automatically classified, + * summarized, and indexed. + * + * @param memory - Raw memory content to persist. + */ + remember(memory: AgentMemoryIncomingMemory): Promise; + /** + * Extract memories from a conversation. + * + * @param messages - Conversation messages to extract memories from. + * @param options - Optional ingest options. + */ + ingest(messages: Iterable, options?: AgentMemoryIngestOptions): Promise; + /** + * Get a profile summary. + * + * @param options - Optional getSummary options. + */ + getSummary(options?: AgentMemoryGetSummaryOptions): Promise; + /** + * Recall memories in this profile. + * + * @param query - Recall query matched against memory content and keywords. + * @param options - Optional recall parameters. + * @returns Matching memories with relevance scores and a synthesized answer. + */ + recall(query: string, options?: AgentMemoryRecallOptions): Promise; + /** + * List active memories in this profile. + * + * Returns a paginated, filterable view of stored memories. Superseded + * versions are excluded. Use the returned `cursor` (when present) to + * fetch the next page. + * + * @param options - Optional pagination and filter options. + */ + list(options?: AgentMemoryListMemoriesOptions): Promise; + /** + * Soft-delete every memory and message in this profile that is tagged + * with `sessionId`. + * + * Idempotent: deleting a sessionId that has no rows is a no-op. + * + * @param sessionId - Session to delete. + */ + deleteSession(sessionId: string): Promise; } -type AiImageClassificationInput = { - image: number[]; -}; -type AiImageClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; +/** + * Namespace-level Agent Memory binding. + * + * Used as the type of an `env.MEMORY`-style binding backed by the Agent + * Memory product. + * + * @example + * ```ts + * export default { + * async fetch(_request: Request, env: Env): Promise { + * const profile = await env.MEMORY.getProfile("wrangler-e2e"); + * const summary = await profile.getSummary(); + * return Response.json(summary); + * }, + * }; + * ``` + */ +declare abstract class AgentMemoryNamespace { + /** + * Get a memory profile by name. Profiles are isolated by namespace and + * addressed by a compound key (namespaceId:profileName). + * + * @param profileName - Profile name (validated against naming rules). + * @returns RPC target for interacting with the profile. + */ + getProfile(profileName: string): Promise; + /** + * Soft-delete a profile and schedule deferred purge. Marks all + * memories and messages as deleted. + * + * @param profileName - Name of the profile to delete. + */ + deleteProfile(profileName: string): Promise; } -type AiImageToTextInput = { - image: number[]; - prompt?: string; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; +// ============ AI Search Error Interfaces ============ +interface AiSearchInternalError extends Error { } -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[]; +interface AiSearchNotFoundError extends Error { +} +// ============ AI Search Common Types ============ +/** A single message in a conversation-style search or chat request. */ +type AiSearchMessage = { + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; }; -type AiImageTextToTextOutput = { - description: string; +/** + * Common shape for `ai_search_options` used by both single-instance and multi-instance requests. + * Contains retrieval, query rewrite, reranking, and cache sub-options. + */ +type AiSearchOptions = { + retrieval?: { + /** Which retrieval backend to use. Defaults to the instance's configured index_method. */ + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + /** Fusion method for combining vector + keyword results. */ + fusion_method?: 'max' | 'rrf'; + /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */ + keyword_match_mode?: 'and' | 'or'; + /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */ + match_threshold?: number; + /** Maximum number of results to return (1-50). Default 10. */ + max_num_results?: number; + /** Vectorize metadata filters applied to the search. */ + filters?: VectorizeVectorMetadataFilter; + /** Number of surrounding chunks to include for context (0-3). Default 0. */ + context_expansion?: number; + /** If true, return only item metadata without chunk text. */ + metadata_only?: boolean; + /** If true (default), return empty results on retrieval failure instead of throwing. */ + return_on_failure?: boolean; + /** Boost results by metadata field values. Max 3 entries. */ + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: string; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + cache?: { + enabled?: boolean; + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + }; + [key: string]: unknown; }; -declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiObjectDetectionInput = { - image: number[]; +// ============ 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 AiObjectDetectionOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; -} -type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; +type AiSearchChatCompletionsRequest = { + messages: AiSearchMessage[]; + model?: string; + stream?: boolean; + ai_search_options?: AiSearchOptions; + [key: string]: unknown; }; -type AiSentenceSimilarityOutput = number[]; -declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; -} -type AiAutomaticSpeechRecognitionInput = { - audio: number[]; +// ============ 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[]; }; -type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: 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; }; -declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; -} -type AiSummarizationInput = { - input_text: string; - max_length?: number; +/** A search result chunk tagged with the instance it originated from. */ +type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & { + instance_id: string; }; -type AiSummarizationOutput = { - summary: string; +/** Describes a per-instance error during a multi-instance operation. */ +type AiSearchMultiSearchError = { + instance_id: string; + message: string; }; -declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; -} -type AiTextClassificationInput = { - text: 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[]; }; -type AiTextClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; -} -type AiTextEmbeddingsInput = { - text: string | string[]; +/** 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 AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; +/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */ +type AiSearchMultiChatCompletionsResponse = Omit & { + chunks: AiSearchMultiSearchChunk[]; + errors?: AiSearchMultiSearchError[]; }; -declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; -} -type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; +// ============ 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; + }; + }>; }; -type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; +type AiSearchChatCompletionsResponse = { + id?: string; + object?: string; + model?: string; + choices: Array<{ + index?: number; + message: { + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + [key: string]: unknown; }; - required: string[]; - }; + [key: string]: unknown; + }>; + chunks: AiSearchSearchResponse['chunks']; + [key: string]: unknown; }; -type AiTextGenerationToolInput = { - type: "function" | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; +type AiSearchStatsResponse = { + queued?: number; + running?: number; + completed?: number; + error?: number; + skipped?: number; + outdated?: number; + last_activity?: string; + /** Storage engine statistics. */ + engine?: { + vectorize?: { + vectorsCount: number; + dimensions: number; + }; + r2?: { + payloadSizeBytes: number; + metadataSizeBytes: number; + objectCount: number; }; }; }; -type AiTextGenerationFunctionsInput = { - name: string; - code: string; +// ============ AI Search Instance Info Types ============ +type AiSearchInstanceInfo = { + id: string; + type?: 'r2' | 'web-crawler' | string; + source?: string; + source_params?: unknown; + paused?: boolean; + status?: string; + namespace?: string; + created_at?: string; + modified_at?: string; + token_id?: string; + ai_gateway_id?: string; + rewrite_query?: boolean; + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; + rewrite_model?: string; + reranking_model?: string; + /** @deprecated Use index_method instead. */ + hybrid_search_enabled?: boolean; + /** Controls which storage backends are active. */ + index_method?: { + vector?: boolean; + keyword?: boolean; + }; + /** Fusion method for combining vector and keyword results. */ + fusion_method?: 'max' | 'rrf'; + indexing_options?: { + keyword_tokenizer?: 'porter' | 'trigram'; + } | null; + retrieval_options?: { + keyword_match_mode?: 'and' | 'or'; + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + } | null; + chunk?: boolean; + chunk_size?: number; + chunk_overlap?: number; + score_threshold?: number; + max_num_results?: number; + cache?: boolean; + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + custom_metadata?: Array<{ + field_name: string; + data_type: 'text' | 'number' | 'boolean' | 'datetime'; + }>; + /** Sync interval in seconds. */ + sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; + metadata?: Record; + [key: string]: unknown; }; -type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; +/** Pagination, search, and ordering parameters for listing instances within a namespace. */ +type AiSearchListInstancesParams = { + page?: number; + per_page?: number; + /** Search instances by ID. */ + search?: string; + /** Field to sort by. */ + order_by?: 'created_at'; + /** Sort direction. */ + order_by_direction?: 'asc' | 'desc'; }; -type AiTextGenerationInput = { - prompt?: string; - raw?: boolean; - stream?: boolean; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - messages?: RoleScopedChatInput[]; - response_format?: AiTextGenerationResponseFormat; - tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); - functions?: AiTextGenerationFunctionsInput[]; +type AiSearchListResponse = { + result: AiSearchInstanceInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; }; -type AiTextGenerationOutput = { - response?: string; - tool_calls?: { - name: string; - arguments: unknown; - }[]; +// ============ AI Search Config Types ============ +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + /** Instance type. Omit to create with built-in storage. */ + type?: 'r2' | 'web-crawler' | string; + /** Source URL (required for web-crawler type). */ + source?: string; + source_params?: unknown; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; + rewrite_model?: string; + reranking_model?: string; + /** @deprecated Use index_method instead. */ + hybrid_search_enabled?: boolean; + /** Controls which storage backends are used during indexing. Defaults to vector-only. */ + index_method?: { + vector?: boolean; + keyword?: boolean; + }; + /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */ + fusion_method?: 'max' | 'rrf'; + indexing_options?: { + keyword_tokenizer?: 'porter' | 'trigram'; + } | null; + retrieval_options?: { + keyword_match_mode?: 'and' | 'or'; + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + } | null; + chunk?: boolean; + chunk_size?: number; + chunk_overlap?: number; + /** Minimum similarity score (0-1) for a result to be included. */ + score_threshold?: number; + max_num_results?: number; + cache?: boolean; + /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */ + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + custom_metadata?: Array<{ + field_name: string; + data_type: 'text' | 'number' | 'boolean' | 'datetime'; + }>; + namespace?: string; + /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */ + sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; + metadata?: Record; + [key: string]: unknown; }; -declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; -} -type AiTextToSpeechInput = { - prompt: string; - lang?: string; +// ============ AI Search Item Types ============ +type AiSearchItemInfo = { + id: string; + key: string; + status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated'; + next_action?: 'INDEX' | 'DELETE' | null; + error?: string; + checksum?: string; + namespace?: string; + chunks_count?: number | null; + file_size?: number | null; + source_id?: string | null; + last_seen_at?: string; + created_at?: string; + metadata?: Record; + [key: string]: unknown; }; -type AiTextToSpeechOutput = Uint8Array | { - audio: string; +type AiSearchItemContentResult = { + body: ReadableStream; + contentType: string; + filename: string; + size: number; }; -declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; -} -type AiTextToImageInput = { - prompt: string; - negative_prompt?: string; - height?: number; - width?: number; - image?: number[]; - image_b64?: string; - mask?: number[]; - num_steps?: number; - strength?: number; - guidance?: number; - seed?: number; +type AiSearchUploadItemOptions = { + metadata?: Record; }; -type AiTextToImageOutput = ReadableStream; -declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput; - postProcessedOutputs: AiTextToImageOutput; -} -type AiTranslationInput = { +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; +}; +type AiSearchListItemsResponse = { + result: AiSearchItemInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Item Logs Types ============ +type AiSearchItemLogsParams = { + /** Maximum number of log entries to return (1-100, default 50). */ + limit?: number; + /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */ + cursor?: string; +}; +type AiSearchItemLog = { + timestamp: string; + action: string; + message: string; + fileKey?: string; + chunkCount?: number; + processingTimeMs?: number; + errorType?: string; +}; +/** Paginated response for item processing logs (cursor-based). */ +type AiSearchItemLogsResponse = { + result: AiSearchItemLog[]; + result_info: { + count: number; + per_page: number; + cursor: string | null; + truncated: boolean; + }; +}; +// ============ AI Search Item Chunks Types ============ +type AiSearchItemChunksParams = { + /** Maximum number of chunks to return (1-100, default 20). */ + limit?: number; + /** Offset into the chunks list (default 0). */ + offset?: number; +}; +/** A single indexed chunk belonging to an item, including its text content and byte range. */ +type AiSearchItemChunk = { + id: string; text: string; - target_lang: string; - source_lang?: string; + start_byte: number; + end_byte: number; + item?: { + timestamp?: number; + key: string; + metadata?: Record; + }; }; -type AiTranslationOutput = { - translated_text?: string; +/** Paginated response for item chunks (offset-based). */ +type AiSearchItemChunksResponse = { + result: AiSearchItemChunk[]; + result_info: { + count: number; + total: number; + limit: number; + offset: number; + }; }; -declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; -} -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { - text: string | string[]; +// ============ AI Search Job Types ============ +type AiSearchJobInfo = { + id: string; + source: 'user' | 'schedule'; + description?: string; + last_seen_at?: string; + started_at?: string; + ended_at?: string; + end_reason?: string; +}; +type AiSearchJobLog = { + id: number; + message: string; + message_type: number; + created_at: number; +}; +type AiSearchCreateJobParams = { + description?: string; +}; +type AiSearchListJobsParams = { + page?: number; + per_page?: number; +}; +type AiSearchListJobsResponse = { + result: AiSearchJobInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +type AiSearchJobLogsParams = { + page?: number; + per_page?: number; +}; +type AiSearchJobLogsResponse = { + result: AiSearchJobLog[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Sub-Service Classes ============ +/** + * Single item service for an AI Search instance. + * Provides info, download, sync, logs, and chunks operations on a specific item. + */ +declare abstract class AiSearchItem { + /** Get metadata about this item. */ + info(): Promise; /** - * The 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. + * Download the item's content. + * @returns Object with body stream, content type, filename, and size. */ - pooling?: "mean" | "cls"; -} | { + download(): Promise; /** - * Batch of the embeddings requests to run using async-queue + * Trigger re-indexing of this item. + * @returns The updated item info. */ - 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[]; + sync(): Promise; /** - * Embeddings of the requested text values + * Retrieve processing logs for this item (cursor-based pagination). + * @param params Optional pagination parameters (limit, cursor). + * @returns Paginated log entries for this item. */ - data?: number[][]; + logs(params?: AiSearchItemLogsParams): Promise; /** - * The pooling method used in the embedding process. + * List indexed chunks for this item (offset-based pagination). + * @param params Optional pagination parameters (limit, offset). + * @returns Paginated chunk entries for this item. */ - pooling?: "mean" | "cls"; -} | AsyncResponse; -interface AsyncResponse { + 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; /** - * The async request id that can be used to obtain the results. + * 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. */ - 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 | { + upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise; /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + * 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). */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Output { + 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; /** - * The transcription + * Get an item by ID. + * @param itemId The item identifier. + * @returns Item service for info, download, sync, logs, and chunks operations. */ - 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; -} -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 = { + get(itemId: string): AiSearchItem; /** - * The text to be translated + * Delete an item from the instance. + * @param itemId The item identifier. */ - text: string; + 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; /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + * Cancel a running job. + * @returns The updated job info. + * @throws AiSearchNotFoundError if the job does not exist. */ - source_lang?: string; + 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; /** - * The language code to translate the text into (e.g., 'es' for Spanish) + * Create a new indexing job. + * @param params Optional job parameters. + * @returns The created job info. */ - target_lang: string; -} | { + create(params?: AiSearchCreateJobParams): Promise; /** - * Batch of the embeddings requests to run using async-queue + * Get a job by ID. + * @param jobId The job identifier. + * @returns Job service for info, logs, and cancel operations. */ - requests: { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - }[]; -}; -type Ai_Cf_Meta_M2M100_1_2B_Output = { + get(jobId: string): AiSearchJob; +} +// ============ AI Search Binding Classes ============ +/** + * Instance-level AI Search service. + * + * Used as: + * - The return type of `AiSearchNamespace.get(name)` (namespace binding) + * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`) + * + * Provides search, chat, update, stats, items, and jobs operations. + * + * @example + * ```ts + * // Via namespace binding + * const instance = env.AI_SEARCH.get("blog"); + * const results = await instance.search({ + * query: "How does caching work?", + * }); + * + * // Via single instance binding + * const results = await env.BLOG_SEARCH.search({ + * messages: [{ role: "user", content: "How does caching work?" }], + * }); + * ``` + */ +declare abstract class AiSearchInstance { /** - * The translated text in the target language + * 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. */ - translated_text?: string; -} | AsyncResponse; -declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input; - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; -} -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { - text: string | string[]; + search(params: AiSearchSearchRequest): Promise; /** - * 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. + * Generate chat completions with AI Search context (streaming). + * @param params Chat completions request with stream: true. + * @returns ReadableStream of server-sent events. */ - pooling?: "mean" | "cls"; -} | { + chatCompletions(params: AiSearchChatCompletionsRequest & { + stream: true; + }): Promise; /** - * Batch of the embeddings requests to run using async-queue + * Generate chat completions with AI Search context. + * @param params Chat completions request. + * @returns Chat completion response with choices and RAG chunks. */ - 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[]; + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; /** - * Embeddings of the requested text values + * Update the instance configuration. + * @param config Partial configuration to update. + * @returns Updated instance info. */ - data?: number[][]; + update(config: Partial): Promise; + /** Get metadata about this instance. */ + info(): Promise; /** - * The pooling method used in the embedding process. + * Get instance statistics (item count, indexing status, etc.). + * @returns Statistics with counts per status, last activity time, and engine details. */ - pooling?: "mean" | "cls"; -} | AsyncResponse; -declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; + stats(): Promise; + /** Items collection — list, upload, and manage items in this instance. */ + get items(): AiSearchItems; + /** Jobs collection — list, create, and inspect indexing jobs. */ + get jobs(): AiSearchJobs; } -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { - text: string | string[]; +/** + * Namespace-level AI Search service. + * + * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`). + * Scoped to a single namespace. Provides dynamic instance access, creation, deletion, + * and multi-instance search/chat operations. + * + * @example + * ```ts + * // Access an instance within the namespace + * const blog = env.AI_SEARCH.get("blog"); + * const results = await blog.search({ query: "How does caching work?" }); + * + * // List all instances in the namespace + * const instances = await env.AI_SEARCH.list(); + * + * // Create a new instance with built-in storage + * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" }); + * + * // Upload items into the instance + * await tenant.items.upload("doc.pdf", fileContent); + * + * // Search across multiple instances + * const multi = await env.AI_SEARCH.search({ + * query: "caching", + * ai_search_options: { instance_ids: ["blog", "docs"] }, + * }); + * + * // Delete an instance + * await env.AI_SEARCH.delete("tenant-123"); + * ``` + */ +declare abstract class AiSearchNamespace { /** - * 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. + * Get an instance by name within the bound namespace. + * @param name Instance name. + * @returns Instance service for search, chat, update, stats, items, and jobs. */ - pooling?: "mean" | "cls"; -} | { + get(name: string): AiSearchInstance; /** - * Batch of the embeddings requests to run using async-queue + * List instances in the bound namespace. + * @param params Optional pagination, search, and ordering parameters. + * @returns Array of instance metadata with pagination info. */ - 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[]; + list(params?: AiSearchListInstancesParams): Promise; /** - * Embeddings of the requested text values + * 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", + * }); + * ``` */ - data?: number[][]; + create(config: AiSearchConfig): Promise; /** - * The pooling method used in the embedding process. + * Delete an instance from the bound namespace. + * @param name Instance name to delete. */ - pooling?: "mean" | "cls"; -} | AsyncResponse; -declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; -} -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { + delete(name: string): Promise; /** - * The input text prompt for the model to generate a response. + * 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. */ - prompt?: string; + search(params: AiSearchMultiSearchRequest): Promise; /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * 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. */ - raw?: boolean; + chatCompletions(params: AiSearchMultiChatCompletionsRequest & { + stream: true; + }): Promise; /** - * 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. + * 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[]; +}; +type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; 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. - */ + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + 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[]; }; -interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string; +type AiImageTextToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageTextToText { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } -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 AiMultimodalEmbeddingsInput = { + image: string; + text: string[]; +}; +type AiIMultimodalEmbeddingsOutput = { + data: number[][]; + shape: number[]; +}; +declare abstract class BaseAiMultimodalEmbeddings { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } -type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ +type AiObjectDetectionInput = { + image: number[]; +}; +type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +type AiAutomaticSpeechRecognitionInput = { audio: number[]; }; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { - /** - * The transcription - */ - text: string; - word_count?: number; +type AiAutomaticSpeechRecognitionOutput = { + text?: string; words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; + word: string; + start: number; + end: number; }[]; vtt?: string; +}; +declare abstract class BaseAiAutomaticSpeechRecognition { + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; } -declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - /** - * Base64 encoded value of the audio data. - */ - audio: string; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string; - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * Preprocess the audio with a voice activity detection model. - */ - vad_filter?: boolean; - /** - * A text prompt to help provide context to the model on the contents of the audio. - */ - initial_prompt?: string; - /** - * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. - */ - prefix?: string; +type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; } -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. - */ - language_probability?: number; - /** - * The total duration of the original audio file, in seconds. - */ - duration?: number; - /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. - */ - duration_after_vad?: number; - }; - /** - * The complete transcription of the audio. - */ +type AiTextClassificationInput = { text: string; - /** - * The total number of words in the transcription. - */ - word_count?: number; - segments?: { - /** - * The starting time of the segment within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the segment within the audio, in seconds. - */ - end?: number; - /** - * The transcription of the segment. - */ - text?: string; - /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. - */ - temperature?: number; - /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. - */ - avg_logprob?: number; - /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. - */ - compression_ratio?: number; - /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. - */ - no_speech_prob?: number; - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string; - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number; - }[]; - }[]; - /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. - */ - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; -} -type Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; }; -interface BGEM3InputQueryAndContexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; +type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; } -interface BGEM3InputEmbedding { +type AiTextEmbeddingsInput = { text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; +}; +type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; } -interface BGEM3InputQueryAndContexts1 { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; +type RoleScopedChatInput = { + role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); + content: string; + name?: string; +}; +type AiTextGenerationToolLegacyInput = { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; +}; +type AiTextGenerationToolInput = { + type: "function" | (string & NonNullable); + function: { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; + }; +}; +type AiTextGenerationFunctionsInput = { + name: string; + code: string; +}; +type AiTextGenerationResponseFormat = { + type: string; + json_schema?: any; +}; +type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + 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; +}; +type AiTextGenerationToolOutput = { + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; +}; +type UsageTags = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; +}; +type AiTextGenerationOutput = { + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; +}; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; } -interface BGEM3InputEmbedding1 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; +type AiTextToSpeechInput = { + prompt: string; + lang?: string; +}; +type AiTextToSpeechOutput = Uint8Array | { + audio: string; +}; +declare abstract class BaseAiTextToSpeech { + inputs: AiTextToSpeechInput; + postProcessedOutputs: AiTextToSpeechOutput; } -type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse; -interface BGEM3OuputQuery { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; +type AiTextToImageInput = { + prompt: string; + negative_prompt?: string; + height?: number; + width?: number; + image?: number[]; + image_b64?: string; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; + seed?: number; +}; +type AiTextToImageOutput = ReadableStream; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; } -interface BGEM3OutputEmbeddingForContexts { - response?: number[][]; - shape?: number[]; +type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +/** + * Workers AI support for OpenAI's Chat Completions API + */ +type ChatCompletionContentPartText = { + type: "text"; + text: string; +}; +type ChatCompletionContentPartImage = { + type: "image_url"; + image_url: { + url: string; + detail?: "auto" | "low" | "high"; + }; +}; +type ChatCompletionContentPartInputAudio = { + type: "input_audio"; + input_audio: { + /** Base64 encoded audio data. */ + data: string; + format: "wav" | "mp3"; + }; +}; +type ChatCompletionContentPartFile = { + type: "file"; + file: { + /** Base64 encoded file data. */ + file_data?: string; + /** The ID of an uploaded file. */ + file_id?: string; + filename?: string; + }; +}; +type ChatCompletionContentPartRefusal = { + type: "refusal"; + refusal: string; +}; +type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile; +type FunctionDefinition = { + name: string; + description?: string; + parameters?: Record; + strict?: boolean | null; +}; +type ChatCompletionFunctionTool = { + type: "function"; + function: FunctionDefinition; +}; +type ChatCompletionCustomToolGrammarFormat = { + type: "grammar"; + grammar: { + definition: string; + syntax: "lark" | "regex"; + }; +}; +type ChatCompletionCustomToolTextFormat = { + type: "text"; +}; +type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat; +type ChatCompletionCustomTool = { + type: "custom"; + custom: { + name: string; + description?: string; + format?: ChatCompletionCustomToolFormat; + }; +}; +type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool; +type ChatCompletionMessageFunctionToolCall = { + id: string; + type: "function"; + function: { + name: string; + /** JSON-encoded arguments string. */ + arguments: string; + }; +}; +type ChatCompletionMessageCustomToolCall = { + id: string; + type: "custom"; + custom: { + name: string; + input: string; + }; +}; +type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall; +type ChatCompletionToolChoiceFunction = { + type: "function"; + function: { + name: string; + }; +}; +type ChatCompletionToolChoiceCustom = { + type: "custom"; + custom: { + name: string; + }; +}; +type ChatCompletionToolChoiceAllowedTools = { + type: "allowed_tools"; + allowed_tools: { + mode: "auto" | "required"; + tools: Array>; + }; +}; +type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools; +type DeveloperMessage = { + role: "developer"; + content: string | Array<{ + type: "text"; + text: string; + }>; + name?: string; +}; +type SystemMessage = { + role: "system"; + content: string | Array<{ + type: "text"; + text: string; + }>; + name?: string; +}; +/** + * Permissive merged content part used inside UserMessage arrays. + * + * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination + * inside nested array items does not correctly match different branches for + * different array elements, so the schema uses a single merged object. + */ +type UserMessageContentPart = { + type: "text" | "image_url" | "input_audio" | "file"; + text?: string; + image_url?: { + url?: string; + detail?: "auto" | "low" | "high"; + }; + input_audio?: { + data?: string; + format?: "wav" | "mp3"; + }; + file?: { + file_data?: string; + file_id?: string; + filename?: string; + }; +}; +type UserMessage = { + role: "user"; + content: string | Array; + name?: string; +}; +type AssistantMessageContentPart = { + type: "text" | "refusal"; + text?: string; + refusal?: string; +}; +type AssistantMessage = { + role: "assistant"; + content?: string | null | Array; + refusal?: string | null; + name?: string; + audio?: { + id: string; + }; + tool_calls?: Array; + function_call?: { + name: string; + arguments: string; + }; +}; +type ToolMessage = { + role: "tool"; + content: string | Array<{ + type: "text"; + text: string; + }>; + tool_call_id: string; +}; +type FunctionMessage = { + role: "function"; + content: string; + name: string; +}; +type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage; +type ChatCompletionsResponseFormatText = { + type: "text"; +}; +type ChatCompletionsResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatJSONSchema = { + type: "json_schema"; + json_schema: { + name: string; + description?: string; + schema?: Record; + strict?: boolean | null; + }; +}; +type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema; +type ChatCompletionsStreamOptions = { + include_usage?: boolean; + include_obfuscation?: boolean; +}; +type PredictionContent = { + type: "content"; + content: string | Array<{ + type: "text"; + text: string; + }>; +}; +type AudioParams = { + voice: string | { + id: string; + }; + format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; +}; +type WebSearchUserLocation = { + type: "approximate"; + approximate: { + city?: string; + country?: string; + region?: string; + timezone?: string; + }; +}; +type WebSearchOptions = { + search_context_size?: "low" | "medium" | "high"; + user_location?: WebSearchUserLocation; +}; +type ChatTemplateKwargs = { + /** Whether to enable reasoning, enabled by default. */ + enable_thinking?: boolean; + /** If false, preserves reasoning context between turns. */ + clear_thinking?: boolean; +}; +/** Shared optional properties used by both Prompt and Messages input branches. */ +type ChatCompletionsCommonOptions = { + model?: string; + audio?: AudioParams; + frequency_penalty?: number | null; + logit_bias?: Record | null; + logprobs?: boolean | null; + top_logprobs?: number | null; + max_tokens?: number | null; + max_completion_tokens?: number | null; + metadata?: Record | null; + modalities?: Array<"text" | "audio"> | null; + n?: number | null; + parallel_tool_calls?: boolean; + prediction?: PredictionContent; + presence_penalty?: number | null; + reasoning_effort?: "low" | "medium" | "high" | null; + chat_template_kwargs?: ChatTemplateKwargs; + response_format?: ResponseFormat; + seed?: number | null; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stop?: string | Array | null; + store?: boolean | null; + stream?: boolean | null; + stream_options?: ChatCompletionsStreamOptions; + temperature?: number | null; + tool_choice?: ChatCompletionToolChoiceOption; + tools?: Array; + top_p?: number | null; + user?: string; + web_search_options?: WebSearchOptions; + function_call?: "none" | "auto" | { + name: string; + }; + functions?: Array; +}; +type PromptTokensDetails = { + cached_tokens?: number; + audio_tokens?: number; +}; +type CompletionTokensDetails = { + reasoning_tokens?: number; + audio_tokens?: number; + accepted_prediction_tokens?: number; + rejected_prediction_tokens?: number; +}; +type CompletionUsage = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + prompt_tokens_details?: PromptTokensDetails; + completion_tokens_details?: CompletionTokensDetails; +}; +type ChatCompletionTopLogprob = { + token: string; + logprob: number; + bytes: Array | null; +}; +type ChatCompletionTokenLogprob = { + token: string; + logprob: number; + bytes: Array | null; + top_logprobs: Array; +}; +type ChatCompletionAudio = { + id: string; + /** Base64 encoded audio bytes. */ + data: string; + expires_at: number; + transcript: string; +}; +type ChatCompletionUrlCitation = { + type: "url_citation"; + url_citation: { + url: string; + title: string; + start_index: number; + end_index: number; + }; +}; +type ChatCompletionResponseMessage = { + role: "assistant"; + content: string | null; + refusal: string | null; + annotations?: Array; + audio?: ChatCompletionAudio; + tool_calls?: Array; + function_call?: { + name: string; + arguments: string; + } | null; +}; +type ChatCompletionLogprobs = { + content: Array | null; + refusal?: Array | null; +}; +type ChatCompletionChoice = { + index: number; + message: ChatCompletionResponseMessage; + finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; + logprobs: ChatCompletionLogprobs | null; +}; +type ChatCompletionsMessagesInput = { + messages: Array; +} & ChatCompletionsCommonOptions; +type ChatCompletionsOutput = { + id: string; + object: string; + created: number; + model: string; + choices: Array; + usage?: CompletionUsage; + system_fingerprint?: string | null; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; +}; +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: "max_output_tokens" | "content_filter"; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: "reasoning_text"; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: "response.created"; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; +}; +type ResponseError = { + code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: "response.failed"; +}; +type ResponseFormatText = { + type: "text"; +}; +type ResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; +} +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: "response.incomplete"; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: "low" | "high" | "auto"; + type: "input_image"; /** - * The pooling method used in the embedding process. + * 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 ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputText = { + text: string; + type: "input_text"; +}; +type ResponseInputTextContent = { + text: string; + type: "input_text"; +}; +type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; +}; +type ResponseOutputRefusal = { + refusal: string; + type: "refusal"; +}; +type ResponseOutputText = { + text: string; + type: "output_text"; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: "summary_text"; +}; +type ResponseReasoningContentItem = { + text: string; + type: "reasoning_text"; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; +type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: "response.completed"; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: "function"; +}; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; +/** Marks keys from T that aren't in U as optional never */ +type Without = { + [P in Exclude]?: never; +}; +/** Either T or U, but not both (mutually exclusive) */ +type XOR = (T & Without) | (U & Without); +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ pooling?: "mean" | "cls"; -} -interface BGEM3OuputEmbedding { +} | { + /** + * 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 @@ -3477,56 +5548,183 @@ interface BGEM3OuputEmbedding { * 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; } -declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { +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 | { /** - * A text description of the image you want to generate. + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values */ - prompt: string; + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Output { /** - * The number of diffusion steps; higher values can improve quality but take longer. + * The transcription */ - steps?: number; + 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; } -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { +declare abstract class Base_Ai_Cf_Openai_Whisper { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +type Ai_Cf_Meta_M2M100_1_2B_Input = { /** - * The generated image in Base64 format. + * The text to be translated */ - image?: string; + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; + }[]; +}; +type Ai_Cf_Meta_M2M100_1_2B_Output = { + /** + * The translated text in the target language + */ + translated_text?: string; +} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; } -declare abstract class Base_Ai_Cf_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; +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_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages; -interface Prompt { +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { + text: string | string[]; /** - * The input text prompt for the model to generate a response. + * 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. */ - prompt: string; - image?: number[] | (string & NonNullable); + pooling?: "mean" | "cls"; +} | { /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * Batch of the embeddings requests to run using async-queue */ - raw?: boolean; + 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[]; /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * Embeddings of the requested text values */ - stream?: boolean; + data?: number[][]; /** - * The maximum number of tokens to generate in the response. + * The pooling method used in the embedding process. */ - max_tokens?: number; + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { /** - * Controls the randomness of the output; higher values produce more random results. + * The async request id that can be used to obtain the results. */ - temperature?: number; + 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[]; /** - * 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. + * 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; +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; +} +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; /** @@ -3549,272 +5747,390 @@ interface Prompt { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; + image: number[] | (string & NonNullable); /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + * The maximum number of tokens to generate in the response. */ - lora?: string; + max_tokens?: number; +}; +interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { + description?: string; +} +declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; } -interface Messages { +type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { /** - * An array of message objects representing the conversation history. + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values */ - messages: { + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * The second this word begins in the recording */ - role?: string; + start?: number; /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + * The ending second when the word completes */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; + end?: number; }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { + audio: string | { + body?: object; + contentType?: string; + }; /** - * A list of tools available for the assistant to use. + * Supported tasks are 'translate' or 'transcribe'. */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean; + task?: string; /** - * The maximum number of tokens to generate in the response. + * The language of the audio being transcribed or translated. */ - max_tokens?: number; + language?: string; /** - * Controls the randomness of the output; higher values produce more random results. + * Preprocess the audio with a voice activity detection model. */ - temperature?: number; + vad_filter?: 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. + * A text prompt to help provide context to the model on the contents of the audio. */ - top_p?: number; + initial_prompt?: string; /** - * 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 prefix appended to the beginning of the output of the transcription and can guide the transcription result. */ - top_k?: number; + prefix?: string; /** - * Random seed for reproducibility of the generation. + * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed. */ - seed?: number; + beam_size?: number; /** - * Penalty for repeated tokens; higher values discourage repetition. + * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops. */ - repetition_penalty?: number; + condition_on_previous_text?: boolean; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped. */ - frequency_penalty?: number; + no_speech_threshold?: number; /** - * Increases the likelihood of the model introducing new topics. + * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text. */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { + compression_ratio_threshold?: number; /** - * The generated text response from the model + * Threshold for filtering out segments with low average log probability, indicating low confidence. */ - response?: string; + log_prob_threshold?: number; /** - * An array of tool calls requests made during the response generation + * Optional threshold (in seconds) to skip silent periods that may cause hallucinations. */ - tool_calls?: { + hallucination_silence_threshold?: number; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { /** - * The arguments passed to be passed to the tool call request + * The language of the audio being transcribed or translated. */ - arguments?: object; + language?: string; /** - * The name of the tool to be called + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. */ - 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; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch; -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; + 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; + }; /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + * The complete transcription of the audio. */ - lora?: string; - response_format?: JSONMode; + text: string; /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * The total number of words in the transcription. */ - raw?: boolean; + 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; + }[]; + }[]; /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. */ - stream?: boolean; + 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 | { /** - * The maximum number of tokens to generate in the response. + * Batch of the embeddings requests to run using async-queue */ - max_tokens?: number; + 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 { /** - * Controls the randomness of the output; higher values produce more random results. + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ - temperature?: number; + query?: 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. + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. */ - top_p?: number; + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; /** - * 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. + * When provided with too long context should the model error out or truncate the context to fit? */ - top_k?: number; + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { + text: string | string[]; /** - * Random seed for reproducibility of the generation. + * When provided with too long context should the model error out or truncate the context to fit? */ - seed?: number; + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { /** - * Penalty for repeated tokens; higher values discourage repetition. + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ - repetition_penalty?: number; + query?: string; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. */ - frequency_penalty?: number; + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; /** - * Increases the likelihood of the model introducing new topics. + * When provided with too long context should the model error out or truncate the context to fit? */ - presence_penalty?: number; -} -interface JSONMode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; + truncate_inputs?: boolean; } -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { + text: string | string[]; /** - * An array of message objects representing the conversation history. + * When provided with too long context should the model error out or truncate the context to fit? */ - messages: { + 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?: { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * Index of the context in the request */ - role: string; + id?: number; /** - * The content of the message as a string. + * Score of the context under the index. */ - content: string; + 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"; +} +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_M3 { + inputs: Ai_Cf_Baai_Bge_M3_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * The number of diffusion steps; higher values can improve quality but take longer. + */ + steps?: number; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +} +type 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; +} +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 | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; }[]; + image?: number[] | (string & NonNullable); functions?: { name: string; code: string; @@ -3906,13 +6222,8 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { }; }; })[]; - response_format?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * If true, the response will be streamed back incrementally. */ stream?: boolean; /** @@ -3924,7 +6235,7 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { */ temperature?: number; /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number; /** @@ -3948,73 +6259,11 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { */ presence_penalty?: number; } -interface AsyncBatch { - requests?: { - /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. - */ - external_reference?: string; - /** - * Prompt for the text generation model - */ - prompt?: string; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * 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?: JSONMode; - }[]; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { /** * The generated text response from the model */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; + response?: string; /** * An array of tool calls requests made during the response generation */ @@ -4028,25 +6277,30 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { */ name?: string; }[]; -} | AsyncResponse; -declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +}; +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; } -interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { +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 { /** - * An array of message objects representing the conversation history. + * The input text prompt for the model to generate a response. */ - 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; - }[]; + 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. */ @@ -4056,112 +6310,7 @@ interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { */ temperature?: number; /** - * Dictate the output format of the generated response. - */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: string | { - /** - * Whether the conversation is safe or not. - */ - safe?: boolean; - /** - * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. - */ - categories?: string[]; - }; - /** - * Usage statistics for the inference request - */ - 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; - }; -} -declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Input { - /** - * A query you wish to perform against the provided contexts. - */ - query: string; - /** - * 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?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - 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; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages; -interface Qwen2_5_Coder_32B_Instruct_Prompt { - /** - * 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?: JSONMode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + * 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; /** @@ -4185,7 +6334,11 @@ interface Qwen2_5_Coder_32B_Instruct_Prompt { */ presence_penalty?: number; } -interface Qwen2_5_Coder_32B_Instruct_Messages { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { /** * An array of message objects representing the conversation history. */ @@ -4194,10 +6347,16 @@ interface Qwen2_5_Coder_32B_Instruct_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; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; }[]; functions?: { name: string; @@ -4290,7 +6449,7 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { }; }; })[]; - response_format?: JSONMode; + 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. */ @@ -4332,7 +6491,60 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { */ presence_penalty?: number; } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { + requests?: { + /** + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + */ + external_reference?: string; + /** + * Prompt for the text generation model + */ + prompt?: string; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; + }[]; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { /** * The generated text response from the model */ @@ -4367,29 +6579,31 @@ type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { */ name?: string; }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; -} -type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; -interface 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; +} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * The async request id that can be used to obtain the results. */ - raw?: boolean; + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + * An array of message objects representing the conversation history. */ - stream?: boolean; + 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. */ @@ -4399,68 +6613,151 @@ interface Qwen_Qwq_32B_Prompt { */ 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. + * Dictate the output format of the generated response. */ - top_k?: number; + response_format?: { + /** + * Set to json_object to process and output generated text as JSON. + */ + type?: string; + }; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { + response?: string | { + /** + * Whether the conversation is safe or not. + */ + safe?: boolean; + /** + * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. + */ + categories?: string[]; + }; /** - * Random seed for reproducibility of the generation. + * Usage statistics for the inference request */ - seed?: number; + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Input { /** - * Penalty for repeated tokens; higher values discourage repetition. + * A query you wish to perform against the provided contexts. */ - repetition_penalty?: number; /** - * Decreases the likelihood of the model repeating the same lines verbatim. + * Number of returned results starting with the best score. */ - frequency_penalty?: number; + top_k?: number; /** - * Increases the likelihood of the model introducing new topics. + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. */ - presence_penalty?: number; -} -interface Qwen_Qwq_32B_Messages { - /** + 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; + }[]; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * 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; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_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; + role: string; /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + * The content of the message as a string. */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; + content: string; }[]; functions?: { name: string; @@ -4553,10 +6850,7 @@ interface Qwen_Qwq_32B_Messages { }; }; })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4598,7 +6892,11 @@ interface Qwen_Qwq_32B_Messages { */ presence_penalty?: number; } -type Ai_Cf_Qwen_Qwq_32B_Output = { +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { /** * The generated text response from the model */ @@ -4634,12 +6932,12 @@ type Ai_Cf_Qwen_Qwq_32B_Output = { 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; +declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages; -interface Mistral_Small_3_1_24B_Instruct_Prompt { +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. */ @@ -4689,7 +6987,7 @@ interface Mistral_Small_3_1_24B_Instruct_Prompt { */ presence_penalty?: number; } -interface Mistral_Small_3_1_24B_Instruct_Messages { +interface Ai_Cf_Qwen_Qwq_32B_Messages { /** * An array of message objects representing the conversation history. */ @@ -4699,7 +6997,7 @@ interface Mistral_Small_3_1_24B_Instruct_Messages { */ role?: string; /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + * The tool call id. If you don't know what to put here you can fall back to 000000001 */ tool_call_id?: string; content?: string | { @@ -4864,7 +7162,7 @@ interface Mistral_Small_3_1_24B_Instruct_Messages { */ presence_penalty?: number; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { +type Ai_Cf_Qwen_Qwq_32B_Output = { /** * The generated text response from the model */ @@ -4900,18 +7198,18 @@ type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { name?: string; }[]; }; -declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -type Ai_Cf_Google_Gemma_3_12B_It_Input = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages; -interface Google_Gemma_3_12B_It_Prompt { +type Ai_Cf_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 fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -4955,7 +7253,7 @@ interface Google_Gemma_3_12B_It_Prompt { */ presence_penalty?: number; } -interface Google_Gemma_3_12B_It_Messages { +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4964,6 +7262,10 @@ interface Google_Gemma_3_12B_It_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 @@ -5126,7 +7428,7 @@ interface Google_Gemma_3_12B_It_Messages { */ presence_penalty?: number; } -type Ai_Cf_Google_Gemma_3_12B_It_Output = { +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { /** * The generated text response from the model */ @@ -5162,21 +7464,20 @@ type Ai_Cf_Google_Gemma_3_12B_It_Output = { name?: string; }[]; }; -declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; +declare abstract class Base_Ai_Cf_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_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages; -interface Ai_Cf_Meta_Llama_4_Prompt { +type Ai_Cf_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 fulfilled for the response. + * JSON schema that should be fufilled for the response. */ guided_json?: object; - response_format?: JSONMode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5218,7 +7519,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages { +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { /** * An array of message objects representing the conversation history. */ @@ -5227,10 +7528,6 @@ interface Ai_Cf_Meta_Llama_4_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 @@ -5243,19 +7540,7 @@ interface Ai_Cf_Meta_Llama_4_Messages { */ 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; @@ -5348,7 +7633,6 @@ interface Ai_Cf_Meta_Llama_4_Messages { }; }; })[]; - response_format?: JSONMode; /** * JSON schema that should be fufilled for the response. */ @@ -5394,7 +7678,7 @@ interface Ai_Cf_Meta_Llama_4_Messages { */ presence_penalty?: number; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { +type Ai_Cf_Google_Gemma_3_12B_It_Output = { /** * The generated text response from the model */ @@ -5421,1894 +7705,6322 @@ type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { */ tool_calls?: { /** - * The tool call id. + * The arguments passed to be passed to the tool call request */ - id?: string; + arguments?: object; /** - * Specifies the type of tool (e.g., 'function'). + * The name of the tool to be called */ - type?: string; + 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: { /** - * Details of the function tool. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - function?: { - /** - * The name of the tool to be called - */ - name?: string; + 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 | { /** - * The arguments passed to be passed to the tool call request + * Type of the content provided */ - 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; -} -interface AiModels { - "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; - "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; - "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; - "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; - "@cf/myshell-ai/melotts": BaseAiTextToSpeech; - "@cf/microsoft/resnet-50": BaseAiImageClassification; - "@cf/facebook/detr-resnet-50": BaseAiObjectDetection; - "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; - "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; - "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; - "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; - "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; - "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; - "@hf/thebloke/llamaguard-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; - "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; - "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; - "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; - "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; - "@cf/microsoft/phi-2": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; - "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; - "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; - "@hf/google/gemma-7b-it": BaseAiTextGeneration; - "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; - "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; - "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; - "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; - "@cf/facebook/bart-large-cnn": BaseAiSummarization; - "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; - "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; - "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; - "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; - "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; - "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; - "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; - "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; - "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; - "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; - "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; - "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; - "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; - "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; - "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; - "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; - "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; - "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; - "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; - "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; -} -type AiOptions = { + 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; + }[]; /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api + * A list of tools available for the assistant to use. */ - queueRequest?: boolean; - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; -}; -type ConversionResponse = { - name: string; - mimeType: string; - format: "markdown"; - tokens: number; - data: string; -}; -type AiModelsSearchParams = { - author?: string; - hide_experimental?: boolean; - page?: number; - per_page?: number; - search?: string; - source?: number; - task?: string; -}; -type AiModelsSearchObject = { - id: string; - source: number; - name: string; - description: string; - task: { - id: string; + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ name: string; + /** + * A brief description of what the tool does. + */ description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; -}; -interface InferenceUpstreamError extends Error { -} -interface AiInternalError extends Error { -} -type AiModelListType = Record; -declare abstract class Ai { - aiGatewayLogId: string | null; - gateway(gatewayId: string): AiGateway; - autorag(autoragId?: string): AutoRAG; - run(model: Name, inputs: InputOptions, options?: Options): Promise; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(files: { - name: string; - blob: Blob; - }[], options?: { - gateway?: GatewayOptions; - extraHeaders?: object; - }): Promise; - toMarkdown(files: { - name: string; - blob: Blob; - }, options?: { - gateway?: GatewayOptions; - extraHeaders?: object; - }): Promise; -} -type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5; - retryDelayMs?: number; - backoff?: 'constant' | 'linear' | 'exponential'; -}; -type GatewayOptions = { - id: string; - cacheKey?: string; - cacheTtl?: number; - skipCache?: boolean; - metadata?: Record; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; -type UniversalGatewayOptions = Exclude & { + /** + * 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; /** - ** @deprecated + * 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. */ - id?: string; -}; -type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | null; -}; -type AiGatewayLog = { - id: string; - provider: string; - model: string; - model_type?: string; - path: string; - duration: number; - request_type?: string; - request_content_type?: string; - status_code: number; - response_content_type?: string; - success: boolean; - cached: boolean; - tokens_in?: number; - tokens_out?: number; - metadata?: Record; - step?: number; - cost?: number; - custom_cost?: boolean; - request_size: number; - request_head?: string; - request_head_complete: boolean; - response_size: number; - response_head?: string; - response_head_complete: boolean; - created_at: Date; -}; -type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; -type AIGatewayHeaders = { - 'cf-aig-metadata': Record | string; - 'cf-aig-custom-cost': { - per_token_in?: number; - per_token_out?: number; - } | { - total_cost?: number; - } | string; - 'cf-aig-cache-ttl': number | string; - 'cf-aig-skip-cache': boolean | string; - 'cf-aig-cache-key': string; - 'cf-aig-event-id': string; - 'cf-aig-request-timeout': number | string; - 'cf-aig-max-attempts': number | string; - 'cf-aig-retry-delay': number | string; - 'cf-aig-backoff': string; - 'cf-aig-collect-log': boolean | string; - Authorization: string; - 'Content-Type': string; - [key: string]: string | number | boolean | object; -}; -type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string; // eslint-disable-line - endpoint: string; - headers: Partial; - query: unknown; -}; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} -declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - }): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line -} -interface AutoRAGInternalError extends Error { -} -interface AutoRAGNotFoundError extends Error { -} -interface AutoRAGUnauthorizedError extends Error { -} -interface AutoRAGNameNotSetError extends Error { -} -type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; -}; -type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; -}; -type AutoRagSearchRequest = { - query: string; - filters?: CompoundFilter | ComparisonFilter; - max_num_results?: number; - ranking_options?: { - ranker?: string; - score_threshold?: number; - }; - rewrite_query?: boolean; -}; -type AutoRagAiSearchRequest = AutoRagSearchRequest & { stream?: boolean; - system_prompt?: string; -}; -type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; -}; -type AutoRagSearchResponse = { - object: 'vector_store.search_results.page'; - search_query: string; - data: { - file_id: string; - filename: string; - score: number; - attributes: Record; - content: { - type: 'text'; - text: string; - }[]; - }[]; - has_more: boolean; - next_page: string | null; -}; -type AutoRagListResponse = { - id: string; - enable: boolean; - type: string; - source: string; - vectorize_name: string; - paused: boolean; - status: string; -}[]; -type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; -}; -declare abstract class AutoRAG { - list(): Promise; - search(params: AutoRagSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; -} -interface BasicImageTransformations { /** - * Maximum width in image pixels. The value must be an integer. + * The maximum number of tokens to generate in the response. */ - width?: number; + max_tokens?: number; /** - * Maximum height in image pixels. The value must be an integer. + * Controls the randomness of the output; higher values produce more random results. */ - height?: number; + temperature?: number; /** - * Resizing mode as a string. It affects interpretation of width and height - * options: - * - scale-down: Similar to contain, but the image is never enlarged. If - * the image is larger than given width or height, it will be resized. - * Otherwise its original size will be kept. - * - contain: Resizes to maximum size that fits within the given width and - * height. If only a single dimension is given (e.g. only width), the - * image will be shrunk or enlarged to exactly match that dimension. - * Aspect ratio is always preserved. - * - cover: Resizes (shrinks or enlarges) to fill the entire area of width - * and height. If the image has an aspect ratio different from the ratio - * of width and height, it will be cropped to fit. - * - crop: The image will be shrunk and cropped to fit within the area - * specified by width and height. The image will not be enlarged. For images - * smaller than the given dimensions it's the same as scale-down. For - * images larger than the given dimensions, it's the same as cover. - * See also trim. - * - pad: Resizes to the maximum size that fits within the given width and - * height, and then fills the remaining area with a background color - * (white by default). Use of this mode is not recommended, as the same - * effect can be more efficiently achieved with the contain mode and the - * CSS object-fit: contain property. - * - squeeze: Stretches and deforms to the width and height given, even if it - * breaks aspect ratio + * 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. */ - fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; + top_p?: number; /** - * Image segmentation using artificial intelligence models. Sets pixels not - * within selected segment area to transparent e.g "foreground" sets every - * background pixel as transparent. + * 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. */ - segment?: "foreground"; + top_k?: number; /** - * When cropping with fit: "cover", this defines the side or point that should - * be left uncropped. The value is either a string - * "left", "right", "top", "bottom", "auto", or "center" (the default), - * or an object {x, y} containing focal point coordinates in the original - * image expressed as fractions ranging from 0.0 (top or left) to 1.0 - * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will - * crop bottom or left and right sides as necessary, but won’t crop anything - * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to - * preserve as much as possible around a point at 20% of the height of the - * source image. + * Random seed for reproducibility of the generation. */ - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; + seed?: number; /** - * Background color to add underneath the image. Applies only to images with - * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), - * hsl(…), etc.) + * Penalty for repeated tokens; higher values discourage repetition. */ - background?: string; + repetition_penalty?: number; /** - * Number of degrees (90, 180, 270) to rotate the image by. width and height - * options refer to axes after rotation. + * Decreases the likelihood of the model repeating the same lines verbatim. */ - rotate?: 0 | 90 | 180 | 270 | 360; + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; +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)[]; } -/** - * In addition to the properties you can set in the RequestInit dict - * that you pass as an argument to the Request constructor, you can - * set certain properties of a `cf` object to control how Cloudflare - * features are applied to that new Request. - * - * Note: Currently, these properties cannot be tested in the - * playground. - */ -interface RequestInitCfProperties extends Record { - cacheEverything?: boolean; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { /** - * A request's cache key is what determines if two requests are - * "the same" for caching purposes. If a request has the same cache key - * as some previous request, then we can serve the same cached response for - * both. (e.g. 'some-key') - * - * Only available for Enterprise customers. + * The input text prompt for the model to generate a response. */ - cacheKey?: string; + prompt: string; /** - * This allows you to append additional Cache-Tag response headers - * to the origin response without modifications to the origin server. - * This will allow for greater control over the Purge by Cache Tag feature - * utilizing changes only in the Workers process. - * - * Only available for Enterprise customers. + * JSON schema that should be fulfilled for the response. */ - cacheTags?: string[]; + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * Force response to be cached for a given number of seconds. (e.g. 300) + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - cacheTtl?: number; + raw?: boolean; /** - * Force response to be cached for a given number of seconds based on the Origin status code. - * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - cacheTtlByStatus?: Record; - scrapeShield?: boolean; - apps?: boolean; - image?: RequestInitCfPropertiesImage; - minify?: RequestInitCfPropertiesImageMinify; - mirage?: boolean; - polish?: "lossy" | "lossless" | "off"; - r2?: RequestInitCfPropertiesR2; + stream?: boolean; /** - * Redirects the request to an alternate origin server. You can use this, - * for example, to implement load balancing across several origins. - * (e.g.us-east.example.com) - * - * Note - For security reasons, the hostname set in resolveOverride must - * be proxied on the same Cloudflare zone of the incoming request. - * Otherwise, the setting is ignored. CNAME hosts are allowed, so to - * resolve to a host under a different domain or a DNS only domain first - * declare a CNAME record within your own zone’s DNS mapping to the - * external hostname, set proxy on Cloudflare, then set resolveOverride - * to point to that CNAME record. + * The maximum number of tokens to generate in the response. */ - resolveOverride?: string; -} -interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { + max_tokens?: number; /** - * Absolute URL of the image file to use for the drawing. It can be any of - * the supported file formats. For drawing of watermarks or non-rectangular - * overlays we recommend using PNG or WebP images. + * Controls the randomness of the output; higher values produce more random results. */ - url: string; + temperature?: number; /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. + * 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. */ - opacity?: number; + top_p?: number; /** - * - If set to true, the overlay image will be tiled to cover the entire - * area. This is useful for stock-photo-like watermarks. - * - If set to "x", the overlay image will be tiled horizontally only - * (form a line). - * - If set to "y", the overlay image will be tiled vertically only - * (form a line). + * 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. */ - repeat?: true | "x" | "y"; + top_k?: number; /** - * Position of the overlay image relative to a given edge. Each property is - * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 - * positions left side of the overlay 10 pixels from the left edge of the - * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom - * of the background image. - * - * Setting both left & right, or both top & bottom is an error. - * - * If no position is specified, the image will be centered. + * Random seed for reproducibility of the generation. */ - top?: number; - left?: number; - bottom?: number; - right?: number; + 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 RequestInitCfPropertiesImage extends BasicImageTransformations { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . + * An array of message objects representing the conversation history. */ - dpr?: number; + 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; + }[]; /** - * Allows you to trim your image. Takes dpr into account and is performed before - * resizing or rotation. - * - * It can be used as: - * - left, top, right, bottom - it will specify the number of pixels to cut - * off each side - * - width, height - the width/height you'd like to end up with - can be used - * in combination with the properties above - * - border - this will automatically trim the surroundings of an image based on - * it's color. It consists of three properties: - * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) - * - tolerance: difference from color to treat as color - * - keep: the number of pixels of border to keep + * A list of tools available for the assistant to use. */ - trim?: "border" | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; + 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; /** - * Quality setting from 1-100 (useful values are in 60-90 range). Lower values - * make images look worse, but load faster. The default is 85. It applies only - * to JPEG and WebP images. It doesn’t have any effect on PNG. + * JSON schema that should be fufilled for the response. */ - quality?: number | "low" | "medium-low" | "medium-high" | "high"; + guided_json?: object; /** - * Output format to generate. It can be: - * - avif: generate images in AVIF format. - * - webp: generate images in Google WebP format. Set quality to 100 to get - * the WebP-lossless format. - * - json: instead of generating an image, outputs information about the - * image, in JSON format. The JSON object will contain image size - * (before and after resizing), source image’s MIME type, file size, etc. - * - jpeg: generate images in JPEG format. - * - png: generate images in PNG format. + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; + raw?: boolean; /** - * Whether to preserve animation frames from input files. Default is true. - * Setting it to false reduces animations to still images. This setting is - * recommended when enlarging images or processing arbitrary user content, - * because large GIF animations can weigh tens or even hundreds of megabytes. - * It is also useful to set anim:false when using format:"json" to get the - * response quicker without the number of frames. + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - anim?: boolean; + stream?: boolean; /** - * What EXIF data should be preserved in the output image. Note that EXIF - * rotation and embedded color profiles are always applied ("baked in" into - * the image), and aren't affected by this option. Note that if the Polish - * feature is enabled, all metadata may have been removed already and this - * option may have no effect. - * - keep: Preserve most of EXIF metadata, including GPS location if there's - * any. - * - copyright: Only keep the copyright tag, and discard everything else. - * This is the default behavior for JPEG files. - * - none: Discard all invisible EXIF metadata. Currently WebP and PNG - * output formats always discard metadata. + * The maximum number of tokens to generate in the response. */ - metadata?: "keep" | "copyright" | "none"; + max_tokens?: number; /** - * Strength of sharpening filter to apply to the image. Floating-point - * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a - * recommended value for downscaled images. + * Controls the randomness of the output; higher values produce more random results. */ - sharpen?: number; + temperature?: number; /** - * Radius of a blur filter (approximate gaussian). Maximum supported radius - * is 250. + * 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. */ - blur?: number; + top_p?: number; /** - * Overlays are drawn in the order they appear in the array (last array - * entry is the topmost layer). + * 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. */ - draw?: RequestInitCfPropertiesImageDraw[]; + top_k?: number; /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * the origin. + * Random seed for reproducibility of the generation. */ - "origin-auth"?: "share-publicly"; + seed?: number; /** - * Adds a border around the image. The border is added after resizing. Border - * width takes dpr into account, and can be specified either using a single - * width property, or individually for each side. + * Penalty for repeated tokens; higher values discourage repetition. */ - border?: { - color: string; - width: number; + 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; + }; + }; + }; } | { - color: string; - top: number; - right: number; - bottom: number; - left: number; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_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; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [ + number, + number + ]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output; +} +declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +interface AiModels { + "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; + "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; + "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; + "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; + "@cf/myshell-ai/melotts": BaseAiTextToSpeech; + "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; + "@cf/microsoft/resnet-50": BaseAiImageClassification; + "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; + "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; + "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; + "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; + "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; + "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; + "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; + "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; + "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; + "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; + "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; + "@cf/microsoft/phi-2": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; + "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; + "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; + "@hf/google/gemma-7b-it": BaseAiTextGeneration; + "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; + "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; + "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; + "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; + "@cf/facebook/bart-large-cnn": BaseAiSummarization; + "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; + "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; + "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; + "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; + "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; + "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; + "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; + "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; + "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; + "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; + "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; + "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; + "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; + "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; + "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; + "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; + "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; + "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; + "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; + "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; + "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; + "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; + "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; + "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; + "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; + "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; + "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; + "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev; + "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B; + "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B; + "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash; + "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5; + "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6; + "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B; + "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT; +} +type AiOptions = { + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean; + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; + signal?: AbortSignal; +}; +type AiModelsSearchParams = { + author?: string; + hide_experimental?: boolean; + page?: number; + per_page?: number; + search?: string; + source?: number; + task?: string; +}; +type AiModelsSearchObject = { + id: string; + source: number; + name: string; + description: string; + task: { + id: string; + name: string; + description: string; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; +}; +type ChatCompletionsBase = ChatCompletionsMessagesInput; +type ChatCompletionsInput = ChatCompletionsMessagesInput; +interface InferenceUpstreamError extends Error { +} +interface AiInternalError extends Error { +} +type AiModelListType = Record; +type AiAsyncBatchResponse = { + request_id: string; +}; +declare abstract class Ai { + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + /** + * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(): AiSearchNamespace; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + * + * @param autoragId Instance ID + */ + autorag(autoragId: string): AutoRAG; + // Batch request + run(model: Name, inputs: { + requests: AiModelList[Name]['inputs'][]; + }, options: AiOptions & { + queueRequest: true; + }): Promise; + // Raw response + run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { + returnRawResponse: true; + }): Promise; + // WebSocket + run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { + websocket: true; + }): Promise; + // Streaming + run(model: Name, inputs: AiModelList[Name]['inputs'] & { + stream: true; + }, options?: AiOptions): Promise; + // Normal (default) - known model + run(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise; + // Unknown model (fallback). + // + // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to + // route any model name that is a literal key of `AiModelList` to one of + // the known-model overloads above (so input/output mismatches surface as + // type errors rather than silently falling back to `Record`). + // Names that aren't in `AiModelList` — e.g. third-party gateway models + // like `"google/nano-banana"` — still hit this overload. + run(model: Model extends keyof AiModelList ? never : Model, inputs: Record, options?: AiOptions): Promise>; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(): ToMarkdownService; + toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; +} +type GatewayRetries = { + maxAttempts?: 1 | 2 | 3 | 4 | 5; + retryDelayMs?: number; + backoff?: 'constant' | 'linear' | 'exponential'; +}; +type GatewayOptions = { + id: string; + cacheKey?: string; + cacheTtl?: number; + skipCache?: boolean; + metadata?: Record; + collectLog?: boolean; + eventId?: string; + requestTimeoutMs?: number; + retries?: GatewayRetries; +}; +type UniversalGatewayOptions = Exclude & { + /** + ** @deprecated + */ + id?: string; +}; +type AiGatewayPatchLog = { + score?: number | null; + feedback?: -1 | 1 | null; + metadata?: Record | null; +}; +type AiGatewayLog = { + id: string; + provider: string; + model: string; + model_type?: string; + path: string; + duration: number; + request_type?: string; + request_content_type?: string; + status_code: number; + response_content_type?: string; + success: boolean; + cached: boolean; + tokens_in?: number; + tokens_out?: number; + metadata?: Record; + step?: number; + cost?: number; + custom_cost?: boolean; + request_size: number; + request_head?: string; + request_head_complete: boolean; + response_size: number; + response_head?: string; + response_head_complete: boolean; + created_at: Date; +}; +type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; +type AIGatewayHeaders = { + 'cf-aig-metadata': Record | string; + 'cf-aig-custom-cost': { + per_token_in?: number; + per_token_out?: number; + } | { + total_cost?: number; + } | string; + 'cf-aig-cache-ttl': number | string; + 'cf-aig-skip-cache': boolean | string; + 'cf-aig-cache-key': string; + 'cf-aig-event-id': string; + 'cf-aig-request-timeout': number | string; + 'cf-aig-max-attempts': number | string; + 'cf-aig-retry-delay': number | string; + 'cf-aig-backoff': string; + 'cf-aig-collect-log': boolean | string; + Authorization: string; + 'Content-Type': string; + [key: string]: string | number | boolean | object; +}; +type AIGatewayUniversalRequest = { + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; +}; +interface AiGatewayInternalError extends Error { +} +interface AiGatewayLogNotFound extends Error { +} +declare abstract class AiGateway { + patchLog(logId: string, data: AiGatewayPatchLog): Promise; + getLog(logId: string): Promise; + run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { + gateway?: UniversalGatewayOptions; + extraHeaders?: object; + signal?: AbortSignal; + }): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line +} +// Copyright (c) 2022-2025 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Artifacts — Git-compatible file storage on Cloudflare Workers. + * + * Provides programmatic access to create, manage, and fork repositories, + * and to issue and revoke scoped access tokens. + */ +/** Information about a repository. */ +interface ArtifactsRepoInfo { + /** Unique repository ID. */ + id: string; + /** Repository name. */ + name: string; + /** Repository description, or null if not set. */ + description: string | null; + /** Default branch name (e.g. "main"). */ + defaultBranch: string; + /** ISO 8601 creation timestamp. */ + createdAt: string; + /** ISO 8601 last-updated timestamp. */ + updatedAt: string; + /** ISO 8601 timestamp of the last push, or null if never pushed. */ + lastPushAt: string | null; + /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */ + source: string | null; + /** Whether the repository is read-only. */ + readOnly: boolean; + /** HTTPS git remote URL. */ + remote: string; +} +/** Result of creating a repository — includes the initial access token. */ +interface ArtifactsCreateRepoResult { + /** Unique repository ID. */ + id: string; + /** Repository name. */ + name: string; + /** Repository description, or null if not set. */ + description: string | null; + /** Default branch name. */ + defaultBranch: string; + /** HTTPS git remote URL. */ + remote: string; + /** Plaintext access token (only returned at creation time). */ + token: string; + /** ISO 8601 token expiry timestamp. */ + tokenExpiresAt: string; +} +/** Paginated list of repositories. */ +interface ArtifactsRepoListResult { + /** Repositories in this page (without the `remote` field). */ + repos: Omit[]; + /** Total number of repositories in the namespace. */ + total: number; + /** Cursor for the next page, if there are more results. */ + cursor?: string; +} +/** Result of creating an access token. */ +interface ArtifactsCreateTokenResult { + /** Unique token ID. */ + id: string; + /** Plaintext token (only returned at creation time). */ + plaintext: string; + /** Token scope: "read" or "write". */ + scope: 'read' | 'write'; + /** ISO 8601 token expiry timestamp. */ + expiresAt: string; +} +/** Token metadata (no plaintext). */ +interface ArtifactsTokenInfo { + /** Unique token ID. */ + id: string; + /** Token scope: "read" or "write". */ + scope: 'read' | 'write'; + /** Token state: "active", "expired", or "revoked". */ + state: 'active' | 'expired' | 'revoked'; + /** ISO 8601 creation timestamp. */ + createdAt: string; + /** ISO 8601 expiry timestamp. */ + expiresAt: string; +} +/** Paginated list of tokens for a repository. */ +interface ArtifactsTokenListResult { + /** Tokens in this page. */ + tokens: ArtifactsTokenInfo[]; + /** Total number of tokens for the repository. */ + total: number; +} +/** + * Handle for a single repository. Returned by Artifacts.get(). + * + * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs. + */ +interface ArtifactsRepo extends ArtifactsRepoInfo { + /** + * Create an access token for this repo. + * @param scope Token scope: "write" (default) or "read". + * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000). + * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range. + */ + createToken(scope?: 'write' | 'read', ttl?: number): Promise; + /** List tokens for this repo (metadata only, no plaintext). */ + listTokens(): Promise; + /** + * Revoke a token by plaintext or ID. + * @param tokenOrId Plaintext token or token ID. + * @returns true if revoked, false if not found. + * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty. + */ + revokeToken(tokenOrId: string): Promise; + // ── Fork ── + /** + * Fork this repo to a new repo. + * @param name Target repository name. + * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true). + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists. + * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running. + */ + fork(name: string, opts?: { + description?: string; + readOnly?: boolean; + defaultBranchOnly?: boolean; + }): Promise; +} +// ── Error types ────────────────────────────────────────────────────────────── +/** + * Error codes returned by Artifacts binding operations. + * + * Each code maps to a numeric code available on `ArtifactsError.numericCode`. + */ +type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR'; +/** + * Error thrown by Artifacts binding operations. + * + * Uses a string `.code` discriminator following the Cloudflare platform + * convention (StreamError, ImagesError, etc.). The `.numericCode` matches + * the REST API `errors[].code` values. + */ +interface ArtifactsError extends Error { + readonly name: 'ArtifactsError'; + /** String error code for programmatic matching. */ + readonly code: ArtifactsErrorCode; + /** Numeric error code matching the REST API. */ + readonly numericCode: number; +} +// ── Binding ────────────────────────────────────────────────────────────────── +/** + * Artifacts binding — namespace-level operations. + * + * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs. + */ +interface Artifacts { + /** + * Create a new repository with an initial access token. + * @param name Repository name (alphanumeric, dots, hyphens, underscores). + * @param opts Optional: readOnly flag, description, default branch name. + * @returns Repo metadata with initial token. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists. + */ + create(name: string, opts?: { + readOnly?: boolean; + description?: string; + setDefaultBranch?: string; + }): Promise; + /** + * Get a handle to an existing repository. + * @param name Repository name. + * @returns Repo handle. + * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist. + * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing. + * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking. + */ + get(name: string): Promise; + /** + * Import a repository from an external git remote. + * @param params Source URL and optional branch/depth, plus target name and options. + * @returns Repo metadata with initial token. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid. + * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS. + * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository. + * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication. + * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist. + * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached. + * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists. + */ + import(params: { + source: { + url: string; + branch?: string; + depth?: number; + }; + target: { + name: string; + opts?: { + description?: string; + readOnly?: boolean; + }; + }; + }): Promise; + /** + * List repositories with cursor-based pagination. + * @param opts Optional: limit (1–200, default 50), cursor for next page. + */ + list(opts?: { + limit?: number; + cursor?: string; + }): Promise; + /** + * Delete a repository and all associated tokens. + * @param name Repository name. + * @returns true if deleted, false if not found. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + */ + delete(name: string): Promise; +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGInternalError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGNotFoundError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGUnauthorizedError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGNameNotSetError extends Error { +} +type ComparisonFilter = { + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; +}; +type CompoundFilter = { + type: 'and' | 'or'; + filters: ComparisonFilter[]; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagSearchRequest = { + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + reranking?: { + enabled?: boolean; + model?: string; + }; + rewrite_query?: boolean; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchRequest = AutoRagSearchRequest & { + stream?: boolean; + system_prompt?: string; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchRequestStreaming = Omit & { + stream: true; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagSearchResponse = { + object: 'vector_store.search_results.page'; + search_query: string; + data: { + file_id: string; + filename: string; + score: number; + attributes: Record; + content: { + type: 'text'; + text: string; + }[]; + }[]; + has_more: boolean; + next_page: string | null; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagListResponse = { + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; +}[]; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchResponse = AutoRagSearchResponse & { + response: string; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +declare abstract class AutoRAG { + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + list(): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; +} +type BrowserRunLifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'; +type BrowserRunResourceType = 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'prefetch' | 'eventsource' | 'websocket' | 'manifest' | 'signedexchange' | 'ping' | 'cspviolationreport' | 'preflight' | 'other'; +/** Options fields shared by all quick actions. */ +interface BrowserRunBaseOptions { + /** Adds `