From a98f83bcc22012a4adb72691901abfb54862f94b Mon Sep 17 00:00:00 2001 From: James M Snell Date: Thu, 19 Nov 2026 21:48:58 +0000 Subject: [PATCH] Retire the TS_EVENT_SOURCE autogate The TS_EVENT_SOURCE autogate has fully rolled out. This removes the gate and the C++ EventSource in api/eventsource.{h,c++}, leaving the TypeScript class (src/per_isolate/eventsource/) as the only implementation. Configs that still name the gate are unaffected: unknown autogate names are ignored. Every Worker now gets the class the gate gave, with the differences from the C++ one that the suite's divergence ledger recorded and the rollout accepted: - The constructor inherits from EventTarget's, its `prototype` is non-writable, and calling it without `new` throws the language's TypeError. - The event stream is parsed as the HTML standard specifies: an empty `event` field dispatches a 'message', a BOM split across chunks is stripped, an `id` field containing U+0000 is ignored, a `retry` field counts only if it is all ASCII digits, a `data` field with an empty value dispatches empty data, a CRLF split across chunks ends one line, and a reconnection sends the last dispatched event's ID. - A listener that closes the EventSource drops the rest of the messages read with that one, and closing an EventSource.from() source cancels its stream. - A reconnection's Last-Event-ID is trimmed of HTTP whitespace. The change itself: - main.ts loads the module and defines the global in every context, as it did with the gate on, where JSG_NESTED_TYPE defined the C++ class. - EW_EVENTSOURCE_ISOLATE_TYPES and workerd/api/eventsource.h are gone; an embedder that lists the types or includes the header must drop them. - With no C++ class to describe it, the TypeScript declaration moves to types/defines/eventsource.d.ts, and ServiceWorkerGlobalScope names it through its override. The generated declarations are unchanged but for their order and the defines file's comment. types/test/types/eventsource.ts covers them. - src/tests/events/eventsource/ collapses to one set of cells: which-impl.js becomes flags.js, each branch keeps its TypeScript side, and the divergence ledger folds into the suite's specification. src/tests/events/AGENTS.md describes what retiring a gate does to a suite. eventsource-test.c++, a unit test of the C++ class's native pump, goes with it. - The eventsource WPTs that failed only with the C++ class now pass. format-field-event-empty.any.js, which hung with it, now runs, and fails as format-field-event.any.js does. - Comments that compared the TypeScript implementation with the C++ one now describe it on its own. Co-Authored-By: Claude Opus 5.5 --- src/per_isolate/eventsource/eventsource.ts | 87 ++- src/per_isolate/main.ts | 38 +- src/tests/events/AGENTS.md | 21 +- src/tests/events/eventsource/AGENTS.md | 106 ++-- src/tests/events/eventsource/BUILD.bazel | 47 +- src/tests/events/eventsource/api-surface.js | 23 +- src/tests/events/eventsource/close.js | 18 +- src/tests/events/eventsource/construction.js | 11 +- .../eventsource-cpp-ts-streams.wd-test | 48 -- ...acy.wd-test => eventsource-legacy.wd-test} | 14 +- .../eventsource/eventsource-modules.capnp | 9 +- ...-in.wd-test => eventsource-opt-in.wd-test} | 7 +- .../eventsource/eventsource-ts-legacy.wd-test | 28 - .../eventsource/eventsource-ts-opt-in.wd-test | 52 -- ...wd-test => eventsource-ts-streams.wd-test} | 11 +- .../eventsource-ts-ts-streams.wd-test | 50 -- ...source-cpp.wd-test => eventsource.wd-test} | 7 +- .../eventsource/{which-impl.js => flags.js} | 17 +- src/tests/events/eventsource/from.js | 2 +- src/tests/events/eventsource/gc.js | 6 +- src/tests/events/eventsource/parser.js | 44 +- src/tests/events/eventsource/pollution.js | 7 +- src/tests/events/eventsource/reconnection.js | 16 +- src/workerd/api/BUILD.bazel | 10 - src/workerd/api/api-rtti-test.c++ | 1 - src/workerd/api/eventsource-test.c++ | 117 ---- src/workerd/api/eventsource.c++ | 580 ------------------ src/workerd/api/eventsource.h | 204 ------ src/workerd/api/global-scope.c++ | 1 - src/workerd/api/global-scope.h | 9 +- src/workerd/api/rtti.c++ | 2 - src/workerd/server/workerd-api-isolate.h | 2 - src/workerd/tools/param-names-ast.c++ | 1 - src/workerd/util/autogate.h | 3 - src/wpt/eventsource-test.ts | 35 +- types/defines/eventsource.d.ts | 53 ++ .../experimental/index.d.ts | 107 ++-- .../generated-snapshot/experimental/index.ts | 107 ++-- types/generated-snapshot/index.d.ts | 107 ++-- types/generated-snapshot/index.ts | 107 ++-- types/test/types/eventsource.ts | 36 ++ 41 files changed, 494 insertions(+), 1657 deletions(-) delete mode 100644 src/tests/events/eventsource/eventsource-cpp-ts-streams.wd-test rename src/tests/events/eventsource/{eventsource-cpp-legacy.wd-test => eventsource-legacy.wd-test} (50%) rename src/tests/events/eventsource/{eventsource-cpp-opt-in.wd-test => eventsource-opt-in.wd-test} (87%) delete mode 100644 src/tests/events/eventsource/eventsource-ts-legacy.wd-test delete mode 100644 src/tests/events/eventsource/eventsource-ts-opt-in.wd-test rename src/tests/events/eventsource/{eventsource-ts.wd-test => eventsource-ts-streams.wd-test} (84%) delete mode 100644 src/tests/events/eventsource/eventsource-ts-ts-streams.wd-test rename src/tests/events/eventsource/{eventsource-cpp.wd-test => eventsource.wd-test} (87%) rename src/tests/events/eventsource/{which-impl.js => flags.js} (50%) delete mode 100644 src/workerd/api/eventsource-test.c++ delete mode 100644 src/workerd/api/eventsource.c++ delete mode 100644 src/workerd/api/eventsource.h create mode 100644 types/defines/eventsource.d.ts create mode 100644 types/test/types/eventsource.ts diff --git a/src/per_isolate/eventsource/eventsource.ts b/src/per_isolate/eventsource/eventsource.ts index 80142e46852..0c28dce1e22 100644 --- a/src/per_isolate/eventsource/eventsource.ts +++ b/src/per_isolate/eventsource/eventsource.ts @@ -1,52 +1,40 @@ 'use strict'; -// EventSource, under the TS_EVENT_SOURCE autogate. It replaces the C++ class -// in api/eventsource.h, keeping its Workers-specific behaviors: the -// EventSourceInit `fetcher` extension, EventSource.from(), disposal through -// close(), absolute URLs only (there is no document base URL), a reconnection -// time clamped to between 1 and 10 seconds, failing rather than reconnecting -// when fetch() rejects, and one reconnection attempt after a response without -// a body. src/tests/events/eventsource/ runs one suite against both -// implementations, and its AGENTS.md records where each difference below is -// pinned. +// EventSource, which parses the event stream as the HTML standard specifies, +// with these Workers-specific behaviors: // -// DIFFERENCES FROM THE C++ IMPLEMENTATION -// -// - The constructor inherits from EventTarget's, as WebIDL requires, and its -// `prototype` is non-writable. Calling it without `new` throws the -// language's TypeError rather than JSG's. -// - The event stream is parsed as the HTML standard specifies, where the C++ -// parser departs from it: an empty `event` field dispatches a 'message' -// (C++: an event of type ''); a BOM is stripped however the first chunks -// split it; an `id` field containing U+0000 is ignored; a `retry` field -// counts only if it is all ASCII digits; a `data` field with an empty value -// dispatches a message with empty data (C++: nothing); a CRLF split across -// chunks ends one line (C++: two, dispatching early); and the last event ID -// that a reconnection sends is the one of the last dispatched event, not -// the last `id` field parsed. -// - Each message is dispatched only while the EventSource is not closed, so -// closing it from a listener drops the rest of the messages read with it. -// - close(), and an error that closes it, cancel the stream of an -// EventSource.from() source. The C++ one goes on reading it. -// - Messages are dispatched from the reaction to the read that produced -// them, rather than from a task the C++ sink queues for each write. Both -// are held back by a Durable Object's input gate: a native body's read -// resumes through IoContext::run(), which takes the input lock, and a -// JavaScript stream's chunks are enqueued under it already. +// - The EventSourceInit `fetcher` extension connects through a Fetcher +// rather than the global fetch(). withCredentials is not supported: a +// truthy value throws. +// - EventSource.from() reads a ReadableStream rather than connecting, and +// never reconnects. close(), and an error that closes the EventSource, +// cancel the stream. +// - Disposal goes through close(). +// - URLs must be absolute: there is no document base URL. +// - The reconnection time is clamped to between 1 and 10 seconds. +// - A rejected fetch() fails the EventSource rather than reconnecting, and a +// response without a body is retried only once. // - A reconnection's Last-Event-ID header is set through Headers, which -// trims HTTP whitespace from the ID; the C++ one sends the ID as parsed. +// trims HTTP whitespace from the ID. +// +// src/tests/events/eventsource/AGENTS.md specifies the class, and indexes +// where the suite pins each of these. // // HOW IT FITS TOGETHER // // The EventSource extends the C++ EventTarget through -// events/event-target-internals, and dispatches the events the C++ one does -// with the same exception policies: an 'open' or 'message' listener -// exception errors the EventSource out (fail fast) and an 'error' listener's -// is only reported. Its I/O goes through a RequestIo (utils), bound to the -// request that created it: every continuation first checks that it runs -// in that request, and throws as the C++ one does if not. The stream is read -// with a reader of whichever streams implementation is installed, captured -// below, and decoded with a streaming TextDecoder before it is parsed. +// events/event-target-internals. An 'open' or 'message' listener exception +// errors the EventSource out (fail fast) and an 'error' listener's is only +// reported. Its I/O goes through a RequestIo (utils), bound to the request +// that created it: every continuation first checks that it runs in that +// request, and throws if not. The stream is read with a reader of whichever +// streams implementation is installed, captured below, and decoded with a +// streaming TextDecoder before it is parsed. Messages are dispatched from the +// reaction to the read that produced them, each only while the EventSource +// is not closed, so closing it from a listener drops the rest of the messages +// read with that one. A Durable Object's input gate holds them back: a native +// body's read resumes through IoContext::run(), which takes the input lock, +// and a JavaScript stream's chunks are enqueued under it already. import type { DomExceptionModule } from '../dom-exception'; import type { EventTargetInternals } from '../events/event-target-internals'; @@ -157,7 +145,7 @@ const HeadersGet = uncurryThis(globalThis.Headers.prototype.get) as ( name: string ) => string | null; -// JSG's messages, so that misuse reads the same as with the C++ class. +// JSG's messages, so that misuse reads as it does for a JSG class. const kIllegalInvocation = 'Illegal invocation: function called with incorrect `this` reference. ' + 'See https://developers.cloudflare.com/workers/observability/errors/' + @@ -184,8 +172,8 @@ const kStreamOption = ObjectFreeze({ __proto__: null, stream: true }); const kEventStreamMimeType = 'text/event-stream'; -// What the C++ implementation's read of each streams implementation throws -// for a chunk that is not bytes. +// What a draining read of each streams implementation throws for a chunk +// that is not bytes; a non-byte chunk fails the EventSource with it. const kNotBytes = compatFlags['typescript_implemented_streams'] === true ? 'This ReadableStream did not return bytes.' @@ -335,9 +323,8 @@ class EventStreamParser { const encoder = new TextEncoder(); -// A chunk as bytes, as the C++ implementation's draining read converts it: -// a string as its UTF-8, any buffer or view as its bytes. Undefined for -// anything else. +// A chunk as bytes, as a draining read converts it: a string as its UTF-8, +// any buffer or view as its bytes. Undefined for anything else. function chunkBytes(chunk: unknown): Uint8Array | undefined { if (typeof chunk === 'string') return TextEncoderEncode(encoder, chunk); if (isAnyArrayBuffer(chunk)) return new Uint8Array(chunk); @@ -360,7 +347,7 @@ function chunkBytes(chunk: unknown): Uint8Array | undefined { // Whether a read failure is a disconnection, as JSG classifies a JavaScript // exception it converts (DISCONNECTED: `retryable` but not `overloaded`), -// which the C++ implementation treats as the end of the stream. +// which ends the stream rather than failing the EventSource. function isDisconnection(error: unknown): boolean { if ( (typeof error !== 'object' && typeof error !== 'function') || @@ -418,8 +405,8 @@ class EventSource extends EventTarget { return; } - // Converted as JSG converts the C++ constructor's arguments, before - // anything is checked. + // Converted as JSG converts a constructor's arguments, before anything + // is checked. if (url === undefined) { throw new TypeError( "Failed to construct 'EventSource': constructor parameter 1 is not " + diff --git a/src/per_isolate/main.ts b/src/per_isolate/main.ts index 5f89b7cc12f..4b647ed0c41 100644 --- a/src/per_isolate/main.ts +++ b/src/per_isolate/main.ts @@ -349,33 +349,31 @@ if (compatFlags['expose_global_message_channel']) { } } -// The TypeScript EventSource replaces the C++ one, which global-scope.h then -// leaves out. Loaded after the streams globals above, whose reader it -// captures. -if (autogates['ts-event-source']) { - const { EventSource } = require('eventsource/eventsource'); - // Installed as the MessageChannel classes above are, matching - // JSG_NESTED_TYPE. - ObjectDefineProperties(ObjectGetPrototypeOf(globalThis), { +// EventSource is always a global. Loaded after the streams globals above, +// whose reader it captures, and installed as JSG_NESTED_TYPE installs a +// global class: on the global scope's prototype, with all three attributes +// true, and under spec_compliant_property_attributes also as an own property +// of the global, non-enumerable per Web IDL. +const { EventSource } = require('eventsource/eventsource'); +ObjectDefineProperties(ObjectGetPrototypeOf(globalThis), { + EventSource: { + __proto__: null, + configurable: true, + enumerable: true, + writable: true, + value: EventSource, + }, +}); +if (compatFlags['spec_compliant_property_attributes']) { + ObjectDefineProperties(globalThis, { EventSource: { __proto__: null, configurable: true, - enumerable: true, + enumerable: false, writable: true, value: EventSource, }, }); - if (compatFlags['spec_compliant_property_attributes']) { - ObjectDefineProperties(globalThis, { - EventSource: { - __proto__: null, - configurable: true, - enumerable: false, - writable: true, - value: EventSource, - }, - }); - } } // The TypeScript URL and URLSearchParams replace the C++ ones, which diff --git a/src/tests/events/AGENTS.md b/src/tests/events/AGENTS.md index 4ac79aca34a..59b3de23a7f 100644 --- a/src/tests/events/AGENTS.md +++ b/src/tests/events/AGENTS.md @@ -4,9 +4,9 @@ Test suites for EventTarget subclasses implemented in the per-isolate bootstrap (`src/per_isolate/`), one subdirectory per API (`messagechannel/`, `eventsource/`). While an API's TypeScript implementation is behind an autogate, its suite runs against **both** -implementations, the C++ one and the TypeScript one, to prove parity -(`eventsource/`). Once the gate and the C++ implementation are removed, the -suite runs against the TypeScript one alone (`messagechannel/`). +implementations, the C++ one and the TypeScript one, to prove parity. +Once the gate and the C++ implementation are removed, the suite runs +against the TypeScript one alone, as both suites here do. The suite rules are those of `src/tests/streams/AGENTS.md`; read that file first. Every suite here follows the ones that hold for any suite: one file @@ -37,12 +37,13 @@ While a suite covers both implementations: unflagged behaviors are asserted for each, in `-cpp-legacy` and `-ts-legacy`. -Retiring the gate collapses the suite to one set of cells, -`.wd-test`, `-opt-in.wd-test` and `-legacy.wd-test`, with -neither the autogate nor the binding. `which-impl.js` becomes `flags.js`, -each `usingTsImpl` branch keeps its TypeScript side, and the divergence -ledger folds into the suite's specification, since what it records is now -simply how the API behaves. +Retiring the gate collapses the suite to one set of cells, `.wd-test`, +`-opt-in.wd-test` and `-legacy.wd-test` (and, for +`eventsource/`, `eventsource-ts-streams.wd-test`), with neither the +autogate nor the binding. `which-impl.js` becomes `flags.js`, each +`usingTsImpl` branch keeps its TypeScript side, and the divergence ledger +folds into the suite's specification, since what it records is now simply +how the API behaves. The seam the TypeScript subclasses share is `src/per_isolate/events/event-target-internals.ts`; its C++ half is unit @@ -57,8 +58,6 @@ tested in `src/workerd/api/event-target-bootstrap-test.c++`. - `messagePortLegacyRedispatch` and `eventSourceLegacyError` in `src/workerd/api/tests/legacy-dispatch-exceptions-test.js`, which pins the legacy dispatch policy across several APIs at once. -- `src/workerd/api/eventsource-test.c++`: a unit test of the C++ - EventSource's native pump. ## Running diff --git a/src/tests/events/eventsource/AGENTS.md b/src/tests/events/eventsource/AGENTS.md index c3d37691bc3..22e0ebd3182 100644 --- a/src/tests/events/eventsource/AGENTS.md +++ b/src/tests/events/eventsource/AGENTS.md @@ -2,16 +2,11 @@ An informal specification of EventSource as implemented in workerd, derived from, and kept in lockstep with, the test suite in this directory. -**The tests are the normative artifact.** Both the C++ implementation -(`src/workerd/api/eventsource.{h,c++}`) and the TypeScript implementation -(`src/per_isolate/eventsource/eventsource.ts`, behind the -`TS_EVENT_SOURCE` autogate) are covered. The TypeScript class subclasses +**The tests are the normative artifact.** The implementation is +`src/per_isolate/eventsource/eventsource.ts`, whose class subclasses the C++ EventTarget through the seam in `src/per_isolate/events/event-target-internals.ts` and does its I/O through -`RequestIo` (`src/workerd/api/request-io.{h,c++}`), so dispatch, fetch -and request binding are shared; the divergences are in -class shape, in event stream parsing, in the Last-Event-ID header, and in -how reads are driven. +`RequestIo` (`src/workerd/api/request-io.{h,c++}`). ## Interface @@ -55,13 +50,17 @@ dictionary EventSourceInit { TypeError for any other receiver. Members are enumerable, like every JSG member; names, lengths and constants' configurability follow `spec_compliant_property_attributes`. +- Where the class does not look like JSG's: its constructor inherits from + EventTarget's, as WebIDL requires; its `prototype` is non-writable + whatever `immutable_api_prototypes` says; and calling it without `new` + throws the language's TypeError. ## Core semantics - **Request:** a GET through the init's `fetcher`, else the global fetch(), with `Accept: text/event-stream`, `Cache-Control: no-cache`, and - `Last-Event-ID` on a reconnection that has one (whitespace trimmed in - the TypeScript implementation, #16). + `Last-Event-ID` on a reconnection that has one: the last dispatched + event's ID, with HTTP whitespace trimmed, as Headers trims any value. - **Response:** a status other than 200, or a content type other than `text/event-stream` (parameters allowed), fails the EventSource for good with an `AbortError`. A redirect moves `url` and the messages' `origin`. @@ -70,23 +69,31 @@ dictionary EventSourceInit { without reconnecting. - **Reconnection:** the end of a connected EventSource's stream fires an 'error' (`The server disconnected.`) in CONNECTING and reconnects after - the reconnection time, 2 seconds unless a `retry` field set it, clamped to - 1 to 10 seconds. The end of an EventSource.from() stream closes it. -- **Parsing** follows the HTML standard in the TypeScript implementation; - the C++ parser departs from it in the cases of ledger #4 to #9. The - stream is decoded as UTF-8 with replacement. A string chunk from a - from() stream is read as its UTF-8 bytes, any buffer or view as its - bytes; anything else fails the EventSource with the TypeError the + the reconnection time, 2 seconds unless a `retry` field of ASCII digits + set it, clamped to 1 to 10 seconds (not pinned: observable only through + reconnection timing). The end of an EventSource.from() stream closes it. +- **Parsing** follows the HTML standard, where an empty `event` field + dispatches a 'message', a BOM is stripped however the first chunks split + it, an `id` containing U+0000 is ignored, a `data` field with an empty + value dispatches empty data, and a CRLF split across chunks ends one + line. The stream is decoded as UTF-8 with replacement. A string chunk + from a from() stream is read as its UTF-8 bytes, any buffer or view as + its bytes; anything else fails the EventSource with the TypeError the streams implementation's byte reads throw. - **Events:** a trusted OpenEvent (whose class is not a global), trusted MessageEvents carrying `lastEventId` and the URL's origin (null for a from() source), and trusted ErrorEvents whose `error` says why. None - bubbles or is cancelable. + bubbles or is cancelable. Messages are dispatched from the reaction to + the read that produced them, held back by a Durable Object's input gate + (not pinned: no cheap observable). - **Event handlers:** onopen, onmessage and onerror are HTML event handler attributes, positioned at first assignment and kept across reassignment; any other `on` property is called as EventTarget calls it. -- **close()** is idempotent and fires nothing. Callbacks resumed by another - request do nothing, and close() from another request throws. +- **close()** is idempotent and fires nothing. A listener that closes the + EventSource drops the rest of the messages read with that one. Closing + an EventSource.from() source cancels its stream, as does an error that + closes it. Callbacks resumed by another request do nothing, and close() + from another request throws. - **Listener exceptions** under `spec_compliant_dispatch_exceptions`: a throwing 'open' or 'message' listener's exception is reported, the remaining listeners run, then the EventSource errors out with it and the @@ -94,13 +101,11 @@ dictionary EventSourceInit { is only reported. Without the flag the first throwing 'message' listener ends the dispatch, unreported, and errors the EventSource out. - **Lifetime:** a pending read retains its EventSource; once the stream has - ended, nothing does. -- **Prototype pollution:** the TypeScript implementation reaches built-ins - only through primordials. The C++ implementation calls no built-in - either, except that reading the TypeScript streams, the native pump - resolves a promise with another, which looks up - `Promise.prototype.then`; `pollution.js` leaves that unpatched for the - `cpp-ts-streams` cell. + ended, nothing does, nor once a from() source is closed and its read + cancelled (not pinned). An event wrapped before dispatch keeps its target + alive until the event is swept, so the EventSource can outlive its + stream's end by a major GC; `gc.js` allows three. +- **Prototype pollution:** built-ins are reached only through primordials. ## Compatibility flags @@ -108,57 +113,32 @@ dictionary EventSourceInit { | --- | --- | --- | | `set_tostring_tag` (2024-09-26) | `[object EventSource]` branding | `legacyToStringTag` | | `spec_compliant_dispatch_exceptions` (2026-09-15) | reporting listener exceptions | `legacyThrowingMessageListener` | -| `spec_compliant_property_attributes` (dateless) | accessor names; lengths; non-configurable constants; the global as an own property | the main cells (the `-opt-in` cells enable it) | -| `immutable_api_prototypes` (dateless) | C++ constructor's `prototype` non-writable | the main cells (the `-opt-in` cells enable it) | -| `typescript_implemented_streams` (experimental) | the streams an EventSource reads | the main cells (the `-ts-streams` cells enable it) | +| `spec_compliant_property_attributes` (dateless) | accessor names; lengths; non-configurable constants; the global as an own property | the main cells (the `-opt-in` cell enables it) | +| `immutable_api_prototypes` (dateless) | nothing: the constructor's `prototype` is non-writable regardless | `constructorAttributes` (the `-opt-in` cell enables it) | +| `typescript_implemented_streams` (experimental) | the streams an EventSource reads | the `eventsource` and `-opt-in` cells (the `-ts-streams` cell enables it) | -The main cells pin the two dated flags on; the legacy cells pin them off +The main cells pin the two dated flags on; the legacy cell pins them off by their disable names, so every cell keeps its `@all-compat-flags` variant. The main cells also pin `nodejs_compat` (`node:assert`, `node:util`), `enable_weak_ref` and `rpc` (for `gc.js`), and `streams_enable_constructors`. -## Divergence ledger (C++ vs TypeScript) - -| # | Area | C++ | TypeScript | Pinned in | -| --- | --- | --- | --- | --- | -| 1 | Constructor static inheritance | `getPrototypeOf(EventSource) === Function.prototype` | `=== EventTarget` | `prototypeChains` | -| 2 | Constructor's `prototype` | writable unless `immutable_api_prototypes` | never writable | `constructorAttributes` | -| 3 | Calling the constructor without `new` | JSG's TypeError | the language's TypeError | `constructorRequiresNew` | -| 4 | Empty `event` field | an event of type `''` | a 'message' | `emptyEventField` | -| 5 | BOM split across chunks | not stripped | stripped | `bomSplitAcrossChunks` | -| 6 | `id` field containing U+0000 | taken | ignored | `idWithNullIsIgnored` | -| 7 | `data` field with an empty value | dispatches nothing | dispatches empty data | `formatFieldData` | -| 8 | CRLF split across chunks | ends two lines | ends one | `crlfSplitAcrossChunks` | -| 9 | Last event ID across a reconnection | the last `id` field parsed | the last dispatched event's | `formatDataBeforeFinalEmptyLine` | -| 10 | A listener closes the EventSource | the rest of the messages read with that one are dispatched | dropped | `closeFromAListener` | -| 11 | close() of a from() source | goes on reading the stream | cancels it | `closeCancelsAFromStream` | -| 12 | `retry` value | anything KJ parses as a `uint32_t`; larger values ignored | ASCII digits only; any length, clamped | not pinned: observable only through reconnection timing | -| 13 | Message dispatch | from a task per write | from the reaction to each read | not pinned: no cheap observable. Both are held by a Durable Object's input gate: a native body's read resumes through `IoContext::run()`, and a JavaScript stream's chunks are enqueued under the input lock | -| 14 | A from() source closed while a read is pending | retained until the read settles | collectable (its read is cancelled, #11) | not pinned: the C++ side is a leak | -| 15 | Collection after the last event | on the next major GC | one major GC later: an event wrapped before dispatch keeps its target alive until it is swept | not pinned: `gc.js` allows three collections | -| 16 | Last-Event-ID with leading or trailing whitespace | sent as parsed | trimmed, as Headers trims values | `lastEventIdWhitespace` | - -The C++ implementation also logs a from() stream's non-byte chunk error -twice; the TypeScript one, once. Not in the ledger, as only the logs see -it. - ## Assertion catalogue | Module | Asserts | | --- | --- | -| `api-surface.js` | static and prototype members, attributes, names and lengths; key order; prototype chains (#1); constructor attributes (#2); runtime class marks; toStringTag branding; dispose member; no own instance properties; the global | +| `api-surface.js` | static and prototype members, attributes, names and lengths; key order; prototype chains; constructor attributes; runtime class marks; toStringTag branding; dispose member; no own instance properties; the global | | `inspect.js` | `util.inspect()` of an EventSource and of `EventSource.prototype` | -| `construction.js` | `new` required (#3); URL conversion and errors; absolute URLs; init, `withCredentials` and `fetcher` checks; conversion order; initial state; module scope refused | +| `construction.js` | `new` required; URL conversion and errors; absolute URLs; init, `withCredentials` and `fetcher` checks; conversion order; initial state; module scope refused | | `illegal-invocation.js` | every member brand-checked against every non-EventSource receiver | | `from.js` | argument checks; locked and disturbed streams; no receiver; synchronous open; reading to the end; chunk kinds; string chunks; non-byte chunks | -| `parser.js` | data joining; ignored lines; leading space; line endings; unterminated events; BOMs; UTF-8; named events; last event ID; #4 to #8; WPT format cases | +| `parser.js` | data joining; ignored lines; leading space; line endings, split CRLFs included; unterminated events; BOMs, split ones included; UTF-8; named and empty event fields; last event ID, `id` with U+0000 included; empty data; WPT format cases | | `request.js` | request headers; a rejected fetch() closes | | `response.js` | status; content type; redirects; responses without a body | -| `reconnection.js` | end of stream reconnects; Last-Event-ID; #16; #9; `retry` | +| `reconnection.js` | end of stream reconnects; Last-Event-ID, its whitespace, and the last dispatched event's ID; `retry` | | `event-shapes.js` | OpenEvent, MessageEvent and ErrorEvent shapes | | `handlers.js` | default null; positional ordering; `on` for a named event | -| `close.js` | idempotent and silent; dispose, which ignores a patched close(); closing from a listener (#10); cancelling a from() stream (#11) | +| `close.js` | idempotent and silent; dispose, which ignores a patched close(); closing from a listener; cancelling a from() stream | | `listener-exceptions.js` | throwing 'message', 'open' and 'error' listeners | | `context.js` | cross-request callbacks and close(), with and without `handle_cross_request_promise_resolution`; close during reconnection; same-request delivery | | `gc.js` | pending reads retain, ended streams release, for native and JavaScript sources and in a Durable Object | @@ -167,7 +147,7 @@ it. | `legacy-listener-exceptions.js` | the first throwing listener ends the dispatch, unreported | | `server.js` | the event streams connected EventSources fetch, through `subrequest` | | `context-worker.js` | `context.js`'s fixture services | -| `which-impl.js` | the cell's implementation and the flags the suite branches on | +| `flags.js` | the flags the suite branches on | | `helpers.js` | descriptor attribute strings; streams; event waiting and recording | ## Web Platform Tests @@ -182,8 +162,6 @@ EventSource.from() or `server.js`: `format-bom-2`, ## Tests that live elsewhere (by design) -- `src/workerd/api/eventsource-test.c++`: a unit test of the C++ - implementation's native pump, removed with it. - `eventSourceLegacyError` in `src/workerd/api/tests/legacy-dispatch-exceptions-test.js`, which pins the legacy dispatch policy across several APIs at once. diff --git a/src/tests/events/eventsource/BUILD.bazel b/src/tests/events/eventsource/BUILD.bazel index eee65092106..e45306bcd8b 100644 --- a/src/tests/events/eventsource/BUILD.bazel +++ b/src/tests/events/eventsource/BUILD.bazel @@ -1,61 +1,30 @@ load("//:build/wd_test.bzl", "wd_test") -# The EventSource suite runs the same test modules under a C++ and a -# TypeScript cell of each kind: main (reading the C++ streams), main reading -# the TypeScript streams, opt-in (the dateless flags that change the -# surface) and legacy (the semantic flags turned off). -# -# The C++ cells disable the @all-autogates variant: enabling every autogate -# enables TS_EVENT_SOURCE, which swaps in the TypeScript implementation -# under a cell whose USING_TS_IMPL binding says C++. The TypeScript cells -# keep it. +# The EventSource suite runs the same test modules under four cells: main +# (reading the C++ streams), main reading the TypeScript streams, opt-in (the +# dateless flags that change the surface) and legacy (the semantic flags +# turned off). eventsource_suite_srcs = glob(["*.js"]) + ["eventsource-modules.capnp"] wd_test( - src = "eventsource-cpp.wd-test", + src = "eventsource.wd-test", data = eventsource_suite_srcs, - generate_all_autogates_variant = False, ) wd_test( - src = "eventsource-ts.wd-test", - data = eventsource_suite_srcs, -) - -wd_test( - src = "eventsource-cpp-ts-streams.wd-test", - args = ["--experimental"], - data = eventsource_suite_srcs, - generate_all_autogates_variant = False, -) - -wd_test( - src = "eventsource-ts-ts-streams.wd-test", + src = "eventsource-ts-streams.wd-test", args = ["--experimental"], data = eventsource_suite_srcs, ) wd_test( - src = "eventsource-cpp-opt-in.wd-test", + src = "eventsource-opt-in.wd-test", args = ["--experimental"], data = eventsource_suite_srcs, - generate_all_autogates_variant = False, -) - -wd_test( - src = "eventsource-ts-opt-in.wd-test", - args = ["--experimental"], - data = eventsource_suite_srcs, -) - -wd_test( - src = "eventsource-cpp-legacy.wd-test", - data = eventsource_suite_srcs, - generate_all_autogates_variant = False, ) wd_test( - src = "eventsource-ts-legacy.wd-test", + src = "eventsource-legacy.wd-test", data = eventsource_suite_srcs, ) diff --git a/src/tests/events/eventsource/api-surface.js b/src/tests/events/eventsource/api-surface.js index 79be072deaf..aae5e4b15bc 100644 --- a/src/tests/events/eventsource/api-surface.js +++ b/src/tests/events/eventsource/api-surface.js @@ -3,21 +3,13 @@ // https://opensource.org/licenses/Apache-2.0 // Object shape of EventSource: members, attributes, prototype chains and -// the marks JSG puts on every runtime class. Divergences (see the ledger in -// AGENTS.md): -// - #1: only the TypeScript constructor inherits from EventTarget's, as -// WebIDL requires. -// - #2: the TypeScript constructor's `prototype` is non-writable even -// without immutable_api_prototypes. +// the marks JSG puts on every runtime class. As WebIDL requires, the +// constructor inherits from EventTarget's, and its `prototype` is +// non-writable even without immutable_api_prototypes. import { deepStrictEqual, ok, strictEqual, throws } from 'node:assert'; import { attributes, streamOf } from 'helpers'; -import { - immutableApiPrototypes, - setToStringTag, - specCompliantPropertyAttributes, - usingTsImpl, -} from 'which-impl'; +import { setToStringTag, specCompliantPropertyAttributes } from 'flags'; // WebIDL constants are non-configurable; JSG's are configurable unless // spec_compliant_property_attributes. @@ -129,10 +121,7 @@ export const prototypeChains = { Object.getPrototypeOf(EventSource.prototype), EventTarget.prototype ); - strictEqual( - Object.getPrototypeOf(EventSource), - usingTsImpl ? EventTarget : Function.prototype - ); + strictEqual(Object.getPrototypeOf(EventSource), EventTarget); }, }; @@ -156,7 +145,7 @@ export const constructorAttributes = { strictEqual(constructor.value, EventSource); strictEqual( attributes(Object.getOwnPropertyDescriptor(EventSource, 'prototype')), - usingTsImpl || immutableApiPrototypes ? 'data' : 'dataw' + 'data' ); }, }; diff --git a/src/tests/events/eventsource/close.js b/src/tests/events/eventsource/close.js index 38f8bbfc23c..0bcd8abe919 100644 --- a/src/tests/events/eventsource/close.js +++ b/src/tests/events/eventsource/close.js @@ -2,15 +2,12 @@ // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -// close() and disposal. Divergences (see AGENTS.md): -// - #10: once a listener closes the TypeScript EventSource, the rest of the -// messages read with that one are dropped; C++ dispatches them. -// - #11: closing an EventSource.from() source cancels its stream in the -// TypeScript implementation; C++ goes on reading it. +// close() and disposal. Once a listener closes the EventSource, the rest of +// the messages read with that one are dropped, and closing an +// EventSource.from() source cancels its stream. import { deepStrictEqual, strictEqual } from 'node:assert'; import { connect, nextEvent, record, streamOf } from 'helpers'; -import { usingTsImpl } from 'which-impl'; export const closeIsIdempotentAndSilent = { async test(ctrl, env) { @@ -52,7 +49,6 @@ export const disposeIgnoresAPatchedClose = { }, }; -// #10. export const closeFromAListener = { async test() { const source = EventSource.from(streamOf(['data: a\n\ndata: b\n\n'])); @@ -62,11 +58,10 @@ export const closeFromAListener = { source.close(); }; await scheduler.wait(20); - deepStrictEqual(data, usingTsImpl ? ['a'] : ['a', 'b']); + deepStrictEqual(data, ['a']); }, }; -// #11. export const closeCancelsAFromStream = { async test() { let pulls = 0; @@ -93,9 +88,6 @@ export const closeCancelsAFromStream = { await scheduler.wait(10); const before = pulls; await scheduler.wait(30); - deepStrictEqual( - [cancelled, pulls > before], - usingTsImpl ? [true, false] : [false, true] - ); + deepStrictEqual([cancelled, pulls > before], [true, false]); }, }; diff --git a/src/tests/events/eventsource/construction.js b/src/tests/events/eventsource/construction.js index fdb05a559d2..a30bc3e958b 100644 --- a/src/tests/events/eventsource/construction.js +++ b/src/tests/events/eventsource/construction.js @@ -3,12 +3,10 @@ // https://opensource.org/licenses/Apache-2.0 // The constructor: argument conversion, its errors and their order, and -// the state of a new EventSource. Divergence #3 (see AGENTS.md): calling -// the TypeScript constructor without `new` throws the language's -// TypeError. +// the state of a new EventSource. Calling the constructor without `new` +// throws the language's TypeError. import { deepStrictEqual, strictEqual, throws } from 'node:assert'; -import { usingTsImpl } from 'which-impl'; const kUrl = 'http://example.org/request-headers'; @@ -44,10 +42,7 @@ export const constructorRequiresNew = { test() { throws(() => EventSource(kUrl), { name: 'TypeError', - message: usingTsImpl - ? "Class constructor EventSource cannot be invoked without 'new'" - : "Failed to construct 'EventSource': Please use the 'new' " + - 'operator, this object constructor cannot be called as a function.', + message: "Class constructor EventSource cannot be invoked without 'new'", }); }, }; diff --git a/src/tests/events/eventsource/eventsource-cpp-ts-streams.wd-test b/src/tests/events/eventsource/eventsource-cpp-ts-streams.wd-test deleted file mode 100644 index 57f0d510938..00000000000 --- a/src/tests/events/eventsource/eventsource-cpp-ts-streams.wd-test +++ /dev/null @@ -1,48 +0,0 @@ -using Workerd = import "/workerd/workerd.capnp"; -using EventSourceModules = import "eventsource-modules.capnp"; - -# Main cell, C++ implementation, reading the TypeScript streams -# (typescript_implemented_streams, which needs --experimental). -# -# No compatibilityDate: the wd_test variants supply the date axis and the -# tests must hold at both extremes. Date-gated semantics are pinned by flag: -# - nodejs_compat: node:assert and node:util. -# - enable_weak_ref: WeakRef, for gc.js. -# - rpc: gc.js calls its Durable Object's method. -# - streams_enable_constructors: the ReadableStream constructor. -# - set_tostring_tag: [object EventSource]. -# - spec_compliant_dispatch_exceptions: listener exceptions are reported. - -const unitTests :Workerd.Config = ( - services = [ - ( name = "events-eventsource-cpp-ts-streams", - worker = ( - modules = EventSourceModules.modules, - compatibilityFlags = [ - "nodejs_compat", - "enable_weak_ref", - "rpc", - "streams_enable_constructors", - "set_tostring_tag", - "spec_compliant_dispatch_exceptions", - "typescript_implemented_streams", - ], - bindings = [ - (name = "USING_TS_IMPL", json = "false"), - (name = "subrequest", service = "events-eventsource-cpp-ts-streams"), - (name = "ns", durableObjectNamespace = "EventSourceGcDo"), - (name = "current", service = "context-current"), - (name = "legacy", service = "context-legacy"), - ], - durableObjectNamespaces = [ - (className = "EventSourceGcDo", uniqueKey = "6984eceb22924037ab88556a7dc2eb6e"), - ], - durableObjectStorage = (inMemory = void), - ) - ), - EventSourceModules.contextCurrent, - EventSourceModules.contextLegacy, - EventSourceModules.contextHelper, - ], - v8Flags = ["--expose-gc"], -); diff --git a/src/tests/events/eventsource/eventsource-cpp-legacy.wd-test b/src/tests/events/eventsource/eventsource-legacy.wd-test similarity index 50% rename from src/tests/events/eventsource/eventsource-cpp-legacy.wd-test rename to src/tests/events/eventsource/eventsource-legacy.wd-test index 82f755fb3b2..03f1cab1e5d 100644 --- a/src/tests/events/eventsource/eventsource-cpp-legacy.wd-test +++ b/src/tests/events/eventsource/eventsource-legacy.wd-test @@ -1,15 +1,14 @@ using Workerd = import "/workerd/workerd.capnp"; using EventSourceModules = import "eventsource-modules.capnp"; -# Legacy cell, C++ implementation: without set_tostring_tag EventSource -# is untagged, and without spec_compliant_dispatch_exceptions the first -# throwing listener ends a dispatch and its exception is not reported. See -# legacy-*.js. Both flags are pinned off by their disable names, so the cell -# holds at every date. +# Legacy cell: without set_tostring_tag EventSource is untagged, and without +# spec_compliant_dispatch_exceptions the first throwing listener ends a +# dispatch and its exception is not reported. See legacy-*.js. Both flags +# are pinned off by their disable names, so the cell holds at every date. const unitTests :Workerd.Config = ( services = [ - ( name = "events-eventsource-cpp-legacy", + ( name = "events-eventsource-legacy", worker = ( modules = EventSourceModules.legacyModules, compatibilityFlags = [ @@ -18,9 +17,6 @@ const unitTests :Workerd.Config = ( "do_not_set_tostring_tag", "no_spec_compliant_dispatch_exceptions", ], - bindings = [ - (name = "USING_TS_IMPL", json = "false"), - ], ) ), ], diff --git a/src/tests/events/eventsource/eventsource-modules.capnp b/src/tests/events/eventsource/eventsource-modules.capnp index 23b81ddce3f..248b7f7f247 100644 --- a/src/tests/events/eventsource/eventsource-modules.capnp +++ b/src/tests/events/eventsource/eventsource-modules.capnp @@ -1,7 +1,6 @@ # Single source of truth for the EventSource suite's module sets and the # services every main and opt-in cell shares; every cell references these -# constants, so the two implementations run exactly the same embedded code. -# embed paths resolve relative to THIS file. +# constants. embed paths resolve relative to THIS file. @0xb7d4e3f1a2c59e61; @@ -9,7 +8,7 @@ using Workerd = import "/workerd/workerd.capnp"; const modules :List(Workerd.Worker.Module) = [ (name = "main", esModule = embed "main.js"), - (name = "which-impl", esModule = embed "which-impl.js"), + (name = "flags", esModule = embed "flags.js"), (name = "helpers", esModule = embed "helpers.js"), (name = "server", esModule = embed "server.js"), (name = "api-surface", esModule = embed "api-surface.js"), @@ -30,11 +29,9 @@ const modules :List(Workerd.Worker.Module) = [ (name = "pollution", esModule = embed "pollution.js"), ]; -# The legacy cells' set. Shared: both implementations honor the flags these -# cells leave off. +# The legacy cell's set. const legacyModules :List(Workerd.Worker.Module) = [ (name = "main", esModule = embed "legacy-main.js"), - (name = "which-impl", esModule = embed "which-impl.js"), (name = "helpers", esModule = embed "helpers.js"), (name = "legacy-shape", esModule = embed "legacy-shape.js"), (name = "legacy-listener-exceptions", esModule = embed "legacy-listener-exceptions.js"), diff --git a/src/tests/events/eventsource/eventsource-cpp-opt-in.wd-test b/src/tests/events/eventsource/eventsource-opt-in.wd-test similarity index 87% rename from src/tests/events/eventsource/eventsource-cpp-opt-in.wd-test rename to src/tests/events/eventsource/eventsource-opt-in.wd-test index d1c7b26d006..e08a95fde32 100644 --- a/src/tests/events/eventsource/eventsource-cpp-opt-in.wd-test +++ b/src/tests/events/eventsource/eventsource-opt-in.wd-test @@ -1,7 +1,7 @@ using Workerd = import "/workerd/workerd.capnp"; using EventSourceModules = import "eventsource-modules.capnp"; -# Opt-in cell, C++ implementation, reading the C++ streams. +# Opt-in cell, reading the C++ streams. # Adds the dateless flags that change the surface: # spec_compliant_property_attributes and immutable_api_prototypes. # @@ -16,7 +16,7 @@ using EventSourceModules = import "eventsource-modules.capnp"; const unitTests :Workerd.Config = ( services = [ - ( name = "events-eventsource-cpp-opt-in", + ( name = "events-eventsource-opt-in", worker = ( modules = EventSourceModules.modules, compatibilityFlags = [ @@ -30,8 +30,7 @@ const unitTests :Workerd.Config = ( "immutable_api_prototypes", ], bindings = [ - (name = "USING_TS_IMPL", json = "false"), - (name = "subrequest", service = "events-eventsource-cpp-opt-in"), + (name = "subrequest", service = "events-eventsource-opt-in"), (name = "ns", durableObjectNamespace = "EventSourceGcDo"), (name = "current", service = "context-current"), (name = "legacy", service = "context-legacy"), diff --git a/src/tests/events/eventsource/eventsource-ts-legacy.wd-test b/src/tests/events/eventsource/eventsource-ts-legacy.wd-test deleted file mode 100644 index 2081beaecc4..00000000000 --- a/src/tests/events/eventsource/eventsource-ts-legacy.wd-test +++ /dev/null @@ -1,28 +0,0 @@ -using Workerd = import "/workerd/workerd.capnp"; -using EventSourceModules = import "eventsource-modules.capnp"; - -# Legacy cell, TypeScript implementation: without set_tostring_tag EventSource -# is untagged, and without spec_compliant_dispatch_exceptions the first -# throwing listener ends a dispatch and its exception is not reported. See -# legacy-*.js. Both flags are pinned off by their disable names, so the cell -# holds at every date. - -const unitTests :Workerd.Config = ( - services = [ - ( name = "events-eventsource-ts-legacy", - worker = ( - modules = EventSourceModules.legacyModules, - compatibilityFlags = [ - "nodejs_compat", - "streams_enable_constructors", - "do_not_set_tostring_tag", - "no_spec_compliant_dispatch_exceptions", - ], - bindings = [ - (name = "USING_TS_IMPL", json = "true"), - ], - ) - ), - ], - autogates = ["workerd-autogate-ts-event-source"], -); diff --git a/src/tests/events/eventsource/eventsource-ts-opt-in.wd-test b/src/tests/events/eventsource/eventsource-ts-opt-in.wd-test deleted file mode 100644 index 31199bbf743..00000000000 --- a/src/tests/events/eventsource/eventsource-ts-opt-in.wd-test +++ /dev/null @@ -1,52 +0,0 @@ -using Workerd = import "/workerd/workerd.capnp"; -using EventSourceModules = import "eventsource-modules.capnp"; - -# Opt-in cell, TypeScript implementation (src/per_isolate/eventsource/, -# under the TS_EVENT_SOURCE autogate), reading the C++ streams. -# Adds the dateless flags that change the surface: -# spec_compliant_property_attributes and immutable_api_prototypes. -# -# No compatibilityDate: the wd_test variants supply the date axis and the -# tests must hold at both extremes. Date-gated semantics are pinned by flag: -# - nodejs_compat: node:assert and node:util. -# - enable_weak_ref: WeakRef, for gc.js. -# - rpc: gc.js calls its Durable Object's method. -# - streams_enable_constructors: the ReadableStream constructor. -# - set_tostring_tag: [object EventSource]. -# - spec_compliant_dispatch_exceptions: listener exceptions are reported. - -const unitTests :Workerd.Config = ( - services = [ - ( name = "events-eventsource-ts-opt-in", - worker = ( - modules = EventSourceModules.modules, - compatibilityFlags = [ - "nodejs_compat", - "enable_weak_ref", - "rpc", - "streams_enable_constructors", - "set_tostring_tag", - "spec_compliant_dispatch_exceptions", - "spec_compliant_property_attributes", - "immutable_api_prototypes", - ], - bindings = [ - (name = "USING_TS_IMPL", json = "true"), - (name = "subrequest", service = "events-eventsource-ts-opt-in"), - (name = "ns", durableObjectNamespace = "EventSourceGcDo"), - (name = "current", service = "context-current"), - (name = "legacy", service = "context-legacy"), - ], - durableObjectNamespaces = [ - (className = "EventSourceGcDo", uniqueKey = "6984eceb22924037ab88556a7dc2eb6e"), - ], - durableObjectStorage = (inMemory = void), - ) - ), - EventSourceModules.contextCurrent, - EventSourceModules.contextLegacy, - EventSourceModules.contextHelper, - ], - autogates = ["workerd-autogate-ts-event-source"], - v8Flags = ["--expose-gc"], -); diff --git a/src/tests/events/eventsource/eventsource-ts.wd-test b/src/tests/events/eventsource/eventsource-ts-streams.wd-test similarity index 84% rename from src/tests/events/eventsource/eventsource-ts.wd-test rename to src/tests/events/eventsource/eventsource-ts-streams.wd-test index 0879f3385b4..b764f1b9f42 100644 --- a/src/tests/events/eventsource/eventsource-ts.wd-test +++ b/src/tests/events/eventsource/eventsource-ts-streams.wd-test @@ -1,8 +1,8 @@ using Workerd = import "/workerd/workerd.capnp"; using EventSourceModules = import "eventsource-modules.capnp"; -# Main cell, TypeScript implementation (src/per_isolate/eventsource/, -# under the TS_EVENT_SOURCE autogate), reading the C++ streams. +# Main cell, reading the TypeScript streams (typescript_implemented_streams, +# which needs --experimental). # # No compatibilityDate: the wd_test variants supply the date axis and the # tests must hold at both extremes. Date-gated semantics are pinned by flag: @@ -15,7 +15,7 @@ using EventSourceModules = import "eventsource-modules.capnp"; const unitTests :Workerd.Config = ( services = [ - ( name = "events-eventsource-ts", + ( name = "events-eventsource-ts-streams", worker = ( modules = EventSourceModules.modules, compatibilityFlags = [ @@ -25,10 +25,10 @@ const unitTests :Workerd.Config = ( "streams_enable_constructors", "set_tostring_tag", "spec_compliant_dispatch_exceptions", + "typescript_implemented_streams", ], bindings = [ - (name = "USING_TS_IMPL", json = "true"), - (name = "subrequest", service = "events-eventsource-ts"), + (name = "subrequest", service = "events-eventsource-ts-streams"), (name = "ns", durableObjectNamespace = "EventSourceGcDo"), (name = "current", service = "context-current"), (name = "legacy", service = "context-legacy"), @@ -43,6 +43,5 @@ const unitTests :Workerd.Config = ( EventSourceModules.contextLegacy, EventSourceModules.contextHelper, ], - autogates = ["workerd-autogate-ts-event-source"], v8Flags = ["--expose-gc"], ); diff --git a/src/tests/events/eventsource/eventsource-ts-ts-streams.wd-test b/src/tests/events/eventsource/eventsource-ts-ts-streams.wd-test deleted file mode 100644 index 2b0f0ed9415..00000000000 --- a/src/tests/events/eventsource/eventsource-ts-ts-streams.wd-test +++ /dev/null @@ -1,50 +0,0 @@ -using Workerd = import "/workerd/workerd.capnp"; -using EventSourceModules = import "eventsource-modules.capnp"; - -# Main cell, TypeScript implementation (src/per_isolate/eventsource/, -# under the TS_EVENT_SOURCE autogate), reading the TypeScript streams -# (typescript_implemented_streams, which needs --experimental). -# -# No compatibilityDate: the wd_test variants supply the date axis and the -# tests must hold at both extremes. Date-gated semantics are pinned by flag: -# - nodejs_compat: node:assert and node:util. -# - enable_weak_ref: WeakRef, for gc.js. -# - rpc: gc.js calls its Durable Object's method. -# - streams_enable_constructors: the ReadableStream constructor. -# - set_tostring_tag: [object EventSource]. -# - spec_compliant_dispatch_exceptions: listener exceptions are reported. - -const unitTests :Workerd.Config = ( - services = [ - ( name = "events-eventsource-ts-ts-streams", - worker = ( - modules = EventSourceModules.modules, - compatibilityFlags = [ - "nodejs_compat", - "enable_weak_ref", - "rpc", - "streams_enable_constructors", - "set_tostring_tag", - "spec_compliant_dispatch_exceptions", - "typescript_implemented_streams", - ], - bindings = [ - (name = "USING_TS_IMPL", json = "true"), - (name = "subrequest", service = "events-eventsource-ts-ts-streams"), - (name = "ns", durableObjectNamespace = "EventSourceGcDo"), - (name = "current", service = "context-current"), - (name = "legacy", service = "context-legacy"), - ], - durableObjectNamespaces = [ - (className = "EventSourceGcDo", uniqueKey = "6984eceb22924037ab88556a7dc2eb6e"), - ], - durableObjectStorage = (inMemory = void), - ) - ), - EventSourceModules.contextCurrent, - EventSourceModules.contextLegacy, - EventSourceModules.contextHelper, - ], - autogates = ["workerd-autogate-ts-event-source"], - v8Flags = ["--expose-gc"], -); diff --git a/src/tests/events/eventsource/eventsource-cpp.wd-test b/src/tests/events/eventsource/eventsource.wd-test similarity index 87% rename from src/tests/events/eventsource/eventsource-cpp.wd-test rename to src/tests/events/eventsource/eventsource.wd-test index d1a67f21d79..6d14bad100e 100644 --- a/src/tests/events/eventsource/eventsource-cpp.wd-test +++ b/src/tests/events/eventsource/eventsource.wd-test @@ -1,7 +1,7 @@ using Workerd = import "/workerd/workerd.capnp"; using EventSourceModules = import "eventsource-modules.capnp"; -# Main cell, C++ implementation, reading the C++ streams. +# Main cell, reading the C++ streams. # # No compatibilityDate: the wd_test variants supply the date axis and the # tests must hold at both extremes. Date-gated semantics are pinned by flag: @@ -14,7 +14,7 @@ using EventSourceModules = import "eventsource-modules.capnp"; const unitTests :Workerd.Config = ( services = [ - ( name = "events-eventsource-cpp", + ( name = "events-eventsource", worker = ( modules = EventSourceModules.modules, compatibilityFlags = [ @@ -26,8 +26,7 @@ const unitTests :Workerd.Config = ( "spec_compliant_dispatch_exceptions", ], bindings = [ - (name = "USING_TS_IMPL", json = "false"), - (name = "subrequest", service = "events-eventsource-cpp"), + (name = "subrequest", service = "events-eventsource"), (name = "ns", durableObjectNamespace = "EventSourceGcDo"), (name = "current", service = "context-current"), (name = "legacy", service = "context-legacy"), diff --git a/src/tests/events/eventsource/which-impl.js b/src/tests/events/eventsource/flags.js similarity index 50% rename from src/tests/events/eventsource/which-impl.js rename to src/tests/events/eventsource/flags.js index aa9cd1bd8a8..650354586b6 100644 --- a/src/tests/events/eventsource/which-impl.js +++ b/src/tests/events/eventsource/flags.js @@ -2,24 +2,13 @@ // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -// Which implementation this cell runs, and the compat flags the suite -// branches on. The implementation is selected by the TS_EVENT_SOURCE -// autogate, which user code cannot read, so each cell says which one it is -// meant to run through its USING_TS_IMPL binding. -import { env } from 'cloudflare:workers'; - -export const usingTsImpl = env.USING_TS_IMPL === true; +// The compat flags the suite branches on. const flags = globalThis.Cloudflare.compatibilityFlags; // The streams an EventSource reads are the TypeScript implementation's. export const usingTsStreams = flags['typescript_implemented_streams'] === true; -// Listener exceptions are reported, and errors the EventSource out after -// the dispatch. -export const specCompliantDispatchExceptions = - flags['spec_compliant_dispatch_exceptions'] === true; - // Prototypes carry Symbol.toStringTag. export const setToStringTag = flags['set_tostring_tag'] === true; @@ -27,7 +16,3 @@ export const setToStringTag = flags['set_tostring_tag'] === true; // globals as own properties of globalThis. export const specCompliantPropertyAttributes = flags['spec_compliant_property_attributes'] === true; - -// Constructors' `prototype` is non-writable. -export const immutableApiPrototypes = - flags['immutable_api_prototypes'] === true; diff --git a/src/tests/events/eventsource/from.js b/src/tests/events/eventsource/from.js index 2210386f9f5..7d3ac41dc8c 100644 --- a/src/tests/events/eventsource/from.js +++ b/src/tests/events/eventsource/from.js @@ -8,7 +8,7 @@ import { deepStrictEqual, ok, strictEqual, throws } from 'node:assert'; import { nextEvent, parse, streamOf } from 'helpers'; -import { usingTsStreams } from 'which-impl'; +import { usingTsStreams } from 'flags'; export const fromRejectsNonStreams = { test() { diff --git a/src/tests/events/eventsource/gc.js b/src/tests/events/eventsource/gc.js index ce62bc08f67..b45db7e8cb3 100644 --- a/src/tests/events/eventsource/gc.js +++ b/src/tests/events/eventsource/gc.js @@ -4,9 +4,9 @@ // An EventSource stays alive while a read of its stream is pending, and is // collectable once its stream has ended. An event that had a JavaScript -// wrapper before it was dispatched, as every event the TypeScript -// implementation dispatches has, keeps its target alive until the event -// itself is swept, so collection is checked over a few major GCs. +// wrapper before it was dispatched, as every event an EventSource dispatches +// has, keeps its target alive until the event itself is swept, so collection +// is checked over a few major GCs. import { deepStrictEqual, ok, strictEqual } from 'node:assert'; import { DurableObject } from 'cloudflare:workers'; diff --git a/src/tests/events/eventsource/parser.js b/src/tests/events/eventsource/parser.js index f336fae9426..8ad921c401f 100644 --- a/src/tests/events/eventsource/parser.js +++ b/src/tests/events/eventsource/parser.js @@ -2,14 +2,12 @@ // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -// Event stream interpretation, through EventSource.from(). Cases named -// after a WPT file are adapted from it (see AGENTS.md). Where the C++ -// parser departs from the HTML standard, the TypeScript one follows the -// standard; each such case is a ledger divergence (#4 to #8 in AGENTS.md). +// Event stream interpretation, as the HTML standard specifies it, through +// EventSource.from(). Cases named after a WPT file are adapted from it (see +// AGENTS.md). import { deepStrictEqual, strictEqual } from 'node:assert'; import { parse } from 'helpers'; -import { usingTsImpl } from 'which-impl'; async function data(chunks) { return (await parse(chunks)).messages.map(([, value]) => value); @@ -182,17 +180,16 @@ export const lastEventIdPersistsAndResets = { }, }; -// #4. WPT format-field-event-empty.any.js: an empty `event` field -// dispatches a 'message'. C++: an event of type ''. +// WPT format-field-event-empty.any.js: an empty `event` field dispatches a +// 'message'. export const emptyEventField = { async test() { const { messages } = await parse(['event: \ndata:data\n\n'], ['']); - deepStrictEqual(messages, [[usingTsImpl ? 'message' : '', 'data', '']]); + deepStrictEqual(messages, [['message', 'data', '']]); }, }; -// #5. A BOM split across chunks is stripped. C++ strips only a BOM within -// the first chunk, so the first line's field name is unknown. +// A BOM split across chunks is stripped. export const bomSplitAcrossChunks = { async test() { deepStrictEqual( @@ -201,38 +198,35 @@ export const bomSplitAcrossChunks = { new Uint8Array([0xbf]), 'data: a\n\n', ]), - usingTsImpl ? ['a'] : [] + ['a'] ); }, }; -// #6. An `id` field containing U+0000 is ignored. C++ takes it. +// An `id` field containing U+0000 is ignored. export const idWithNullIsIgnored = { async test() { const { messages } = await parse(['id: a\0b\ndata: x\n\n']); - deepStrictEqual(messages, [['message', 'x', usingTsImpl ? '' : 'a\0b']]); + deepStrictEqual(messages, [['message', 'x', '']]); }, }; -// #7. WPT format-field-data.any.js: a `data` field with an empty value -// dispatches a message with empty data. C++ dispatches nothing for it. +// WPT format-field-data.any.js: a `data` field with an empty value +// dispatches a message with empty data. export const formatFieldData = { async test() { - deepStrictEqual( - await data(['data:\n\ndata\ndata\n\ndata:test\n\n']), - usingTsImpl ? ['', '\n', 'test'] : ['\n', 'test'] - ); + deepStrictEqual(await data(['data:\n\ndata\ndata\n\ndata:test\n\n']), [ + '', + '\n', + 'test', + ]); }, }; -// #8. A CRLF split across chunks ends one line. C++ ends two, so the empty -// second one dispatches early. +// A CRLF split across chunks ends one line. export const crlfSplitAcrossChunks = { async test() { - deepStrictEqual( - await data(['data: a\r', '\ndata: b\n\n']), - usingTsImpl ? ['a\nb'] : ['a', 'b'] - ); + deepStrictEqual(await data(['data: a\r', '\ndata: b\n\n']), ['a\nb']); }, }; diff --git a/src/tests/events/eventsource/pollution.js b/src/tests/events/eventsource/pollution.js index c501f8892bd..3411e04d179 100644 --- a/src/tests/events/eventsource/pollution.js +++ b/src/tests/events/eventsource/pollution.js @@ -4,13 +4,10 @@ // An EventSource works with the built-ins it relies on patched: every // method or accessor of theirs it reaches is captured before user code -// runs. The C++ implementation calls none of them, but when it reads the -// TypeScript streams, the native pump resolves a promise with another, which -// looks up Promise.prototype.then, so that combination leaves it unpatched. +// runs. import { deepStrictEqual, strictEqual } from 'node:assert'; import { connect, nextEvent, streamOf } from 'helpers'; -import { usingTsImpl, usingTsStreams } from 'which-impl'; // Replaces each of `names` on `object` with a function that throws, and // returns a function that restores them. Index loops and no array @@ -77,7 +74,7 @@ function recordMessages(source) { export const fromStreamUnderPollution = { async test() { const stream = streamOf(['id: 1\ndata: a\n', 'data: b\n\n', 'data: c\n\n']); - const restore = patchAll({ promises: usingTsImpl || !usingTsStreams }); + const restore = patchAll(); let source; let messages; let ended; diff --git a/src/tests/events/eventsource/reconnection.js b/src/tests/events/eventsource/reconnection.js index 29f4ff5df5f..15872e2a63d 100644 --- a/src/tests/events/eventsource/reconnection.js +++ b/src/tests/events/eventsource/reconnection.js @@ -4,15 +4,12 @@ // Reconnection after the end of a connected EventSource's stream: the // 'error' event that announces it, the Last-Event-ID it sends, and the -// reconnection time a `retry` field sets. Divergences (see AGENTS.md): -// - #9: the TypeScript implementation sends the ID of the last dispatched -// event, as the standard says; C++ sends the last `id` field parsed. -// - #16: the TypeScript implementation trims HTTP whitespace from the ID it -// sends; C++ sends it as parsed. +// reconnection time a `retry` field sets. The ID sent is the last +// dispatched event's, as the standard says, with HTTP whitespace trimmed, as +// Headers trims any value. import { deepStrictEqual, strictEqual } from 'node:assert'; import { connect, nextEvent, record } from 'helpers'; -import { usingTsImpl } from 'which-impl'; export const endOfStreamReconnects = { async test(ctrl, env) { @@ -44,7 +41,6 @@ export const lastEventIdIsSent = { }, }; -// #16. export const lastEventIdWhitespace = { async test(ctrl, env) { const source = connect(env, '/padded-last-event-id'); @@ -52,11 +48,11 @@ export const lastEventIdWhitespace = { source.onmessage = (event) => data.push(event.data); while (data.length < 2) await nextEvent(source, 'message'); source.close(); - deepStrictEqual(data, ['first', usingTsImpl ? '[padded]' : '[ padded \t]']); + deepStrictEqual(data, ['first', '[padded]']); }, }; -// #9. WPT format-data-before-final-empty-line.any.js: the reconnection's +// WPT format-data-before-final-empty-line.any.js: the reconnection's // message carries the last dispatched event's ID. export const formatDataBeforeFinalEmptyLine = { async test(ctrl, env) { @@ -69,7 +65,7 @@ export const formatDataBeforeFinalEmptyLine = { source.close(); deepStrictEqual(messages, [ ['test1', ''], - ['test1', usingTsImpl ? '' : 'test'], + ['test1', ''], ]); }, }; diff --git a/src/workerd/api/BUILD.bazel b/src/workerd/api/BUILD.bazel index 0190fbfa833..dfe1a533f6b 100644 --- a/src/workerd/api/BUILD.bazel +++ b/src/workerd/api/BUILD.bazel @@ -20,7 +20,6 @@ filegroup( "container.c++", "event-target-bootstrap.c++", "events.c++", - "eventsource.c++", "export-loopback.c++", "filesystem.c++", "filesystem-bootstrap.c++", @@ -83,7 +82,6 @@ filegroup( "container.h", "event-target-bootstrap.h", "events.h", - "eventsource.h", "export-loopback.h", "filesystem.h", "filesystem-bootstrap.h", @@ -755,14 +753,6 @@ kj_test( ], ) -kj_test( - src = "eventsource-test.c++", - deps = [ - "//src/workerd/io", - "//src/workerd/tests:test-fixture", - ], -) - kj_test( src = "event-target-bootstrap-test.c++", deps = [ diff --git a/src/workerd/api/api-rtti-test.c++ b/src/workerd/api/api-rtti-test.c++ index e1a846d8fcf..3c4dae4aaad 100644 --- a/src/workerd/api/api-rtti-test.c++ +++ b/src/workerd/api/api-rtti-test.c++ @@ -8,7 +8,6 @@ #include #include #include -#include #include #include #include diff --git a/src/workerd/api/eventsource-test.c++ b/src/workerd/api/eventsource-test.c++ deleted file mode 100644 index 1e5fc1afa10..00000000000 --- a/src/workerd/api/eventsource-test.c++ +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2026 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 - -#include "eventsource.h" - -#include -#include - -#include -#include - -namespace workerd::api { -namespace { - -struct SourceState { - bool readPending = false; - bool canceled = false; - bool destroyed = false; - uint chunks = 0; -}; - -class GatedSource final: public ReadableStreamSource { - public: - GatedSource(kj::Promise gate, SourceState& state): gate(kj::mv(gate)), state(state) {} - - ~GatedSource() noexcept(false) { - state.destroyed = true; - } - - kj::Promise tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { - if (state.chunks == 0) { - state.readPending = true; - co_await gate; - state.readPending = false; - } - kj::StringPtr chunk; - switch (state.chunks) { - case 0: - chunk = "id: first\nretry: 1000\ndata: one\n\n"_kj; - break; - case 1: - chunk = "id: second\ndata: two\n\n"_kj; - break; - default: - co_return 0; - } - KJ_REQUIRE(maxBytes >= chunk.size()); - kj::arrayPtr(static_cast(buffer), chunk.size()).copyFrom(chunk.asBytes()); - ++state.chunks; - co_return chunk.size(); - } - - void cancel(kj::Exception reason) override { - state.canceled = true; - } - - private: - kj::Promise gate; - SourceState& state; -}; - -enum class PumpOutcome { COMPLETE, CANCEL }; - -KJ_TEST("EventSource native pump owns parser state after its EventSource is destroyed") { - for (auto typescript: kj::arr(false, true)) { - for (auto outcome: kj::arr(PumpOutcome::COMPLETE, PumpOutcome::CANCEL)) { - SourceState state; - capnp::MallocMessageBuilder message; - auto flags = message.initRoot(); - flags.setTypeScriptImplementedStreams(typescript); - TestFixture fixture({.featureFlags = flags.asReader()}); - auto gate = kj::newPromiseAndFulfiller(); - fixture.runInIoContext([&](const TestFixture::Environment& env) -> kj::Promise { - kj::Promise pump = nullptr; - jsg::WeakRef weakSource(nullptr); - { - auto source = env.js.alloc(env.js); - weakSource = source.getWeakRef(env.js); - auto readable = JsReadableStream::create( - env.js, env.context, kj::heap(kj::mv(gate.promise), state)); - pump = env.context.waitForDeferredProxy( - readable.pumpTo(env.js, source->newSink(env.js), EndStream::YES)); - KJ_ASSERT(state.readPending); - } - // Keep a read pending while releasing the EventSource owner. No wrapper was - // exported to JS, so destruction is synchronous. - KJ_ASSERT(!weakSource.isAlive()); - if (outcome == PumpOutcome::CANCEL) { - pump = nullptr; - KJ_EXPECT(state.canceled); - return kj::READY_NOW; - } - gate.fulfiller->fulfill(); - return kj::mv(pump); - }); - KJ_EXPECT(state.destroyed); - KJ_EXPECT(state.canceled == (outcome == PumpOutcome::CANCEL)); - KJ_EXPECT(state.chunks == (outcome == PumpOutcome::COMPLETE ? 2 : 0)); - } - } -} - -KJ_TEST("EventSource sink drops delivery after its originating context is destroyed") { - TestFixture fixture; - auto sink = fixture.runInIoContext([](const TestFixture::Environment& env) { - auto source = env.js.alloc(env.js); - return source->newSink(env.js); - }); - KJ_ASSERT(!IoContext::hasCurrent()); - sink->write("id: first\nretry: 1000\ndata: one\n\n"_kj.asBytes()).wait(fixture.getWaitScope()); - sink->write("id: second\ndata: two\n\n"_kj.asBytes()).wait(fixture.getWaitScope()); - sink->end().wait(fixture.getWaitScope()); -} - -} // namespace -} // namespace workerd::api diff --git a/src/workerd/api/eventsource.c++ b/src/workerd/api/eventsource.c++ deleted file mode 100644 index 94201e53f6d..00000000000 --- a/src/workerd/api/eventsource.c++ +++ /dev/null @@ -1,580 +0,0 @@ -// Copyright (c) 2017-2024 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 - -#include "eventsource.h" - -#include "events.h" -#include "http.h" -#include "streams/common.h" - -#include -#include -#include - -namespace workerd::api { - -namespace { -class EventSourceSink final: public WritableStreamSink { - public: - EventSourceSink(IoContext& context, - kj::Own state, - kj::Rc> weakEventSource) - : weakContext(context.getWeakRef()), - state(kj::mv(state)), - weakEventSource(kj::mv(weakEventSource)) {} - - kj::Promise write(kj::ArrayPtr buffer) override { - // The event stream is a new-line delimited format where each line represents an event. - // We need to scan the buffer for end-of-line characters. When we find one, everything before - // it is pushed into the event queue and we keep scanning. If we do not find an end-of-line - // sequence in the remaining input, we buffer it and wait for the next write to continue - // scanning, or until the stream is ended or aborted. - - if (ended) { - // Write was received after end() or abort() was called. - // We'll just ignore the write. - return kj::READY_NOW; - } - - auto input = buffer.asChars(); - - // The stream may or may not begin with the UTF-8 BOM (%xFEFF). If this is the - // first write, we need to check for it and skip it if it is present. - // The BOM is a 3-byte sequence (0xEF, 0xBB, 0xBF) that encodes the Unicode - // codepoint U+FEFF. We only want to check for this once. - if (!bomChecked) { - bomChecked = true; - if (input.size() >= 3 && input[0] == '\xEF' && input[1] == '\xBB' && input[2] == '\xBF') { - input = input.slice(3); - } - } - - while (input != nullptr) { - KJ_IF_SOME(found, findEndOfLine(input)) { - auto prefix = kept.releaseAsArray(); - // Feed the line into the processor. - feed(kj::str(prefix, input.first(found.pos))); - input = found.remaining; - // If we've reached the end of the input, input will == nullptr here. - } else { - // No end-of-line found, buffer the input. - kept.addAll(input.begin(), input.end()); - input = nullptr; - } - } - - // Release any buffered events to the EventSource - release(); - - return kj::READY_NOW; - } - - kj::Promise write(kj::ArrayPtr> pieces) override { - for (auto& piece: pieces) { - co_await write(piece); - } - co_return; - } - - kj::Promise end() override { - // The stream has finished. There's really nothing left to do here. Any partially - // filled data will be dropped on the floor. - clear(); - return kj::READY_NOW; - } - - void abort(kj::Exception reason) override { - // There's really nothing to do here. - clear(); - } - - private: - // The pump and its sink stay on the originating I/O thread, even outside the isolate. - kj::Own weakContext; - kj::Own state; - kj::Rc> weakEventSource; - bool ended = false; - - // Retained bytes to be processed in the next write. - kj::Vector kept; - - // The collected messages that are pending to be dispatched as events - kj::Vector pendingMessages; - - // The message that is currently being processed. - kj::Maybe currentPendingMessage; - - // Set to true once the byte-order-mark has been checked - bool bomChecked = false; - - EventSource::PendingMessage& getPendingMessage() { - KJ_IF_SOME(pending, currentPendingMessage) { - return pending; - } - return currentPendingMessage.emplace(); - } - - void feed(kj::String line) { - // Parse line according to the event stream format and dispatch the event. - - // stream = [ bom ] *event - // event = *( comment / field ) end-of-line - // comment = colon *any-char end-of-line - // field = 1*name-char [ colon [ space ] *any-char ] end-of-line - // end-of-line = ( cr lf / cr / lf ) - - // ; characters - // lf = %x000A ; U+000A LINE FEED (LF) - // cr = %x000D ; U+000D CARRIAGE RETURN (CR) - // space = %x0020 ; U+0020 SPACE - // colon = %x003A ; U+003A COLON (:) - // bom = %xFEFF ; U+FEFF BYTE ORDER MARK - // name-char = %x0000-0009 / %x000B-000C / %x000E-0039 / %x003B-10FFFF - // ; a scalar value other than U+000A LINE FEED (LF), U+000D CARRIAGE RETURN - // (CR), or U+003A COLON (:) - // any-char = %x0000-0009 / %x000B-000C / %x000E-10FFFF - // ; a scalar value other than U+000A LINE FEED (LF) or U+000D CARRIAGE - // RETURN (CR) - - // Note that the BOM (if present) is filtered out in the write() method. - - if (line.size() == 0) { - // Dispatch the current pending message and clear it. If there is no - // pending message, we'll just ignore the line. - KJ_IF_SOME(pending, currentPendingMessage) { - // This message is done and ready to be dispatched. Add it to the - // pendingMessages list. The next time release() is called, it will - // be passed off to the EventSource. - pending.id = kj::str(state->lastEventId); - pendingMessages.add(kj::mv(pending)); - currentPendingMessage = kj::none; - } - } else if (line[0] == ':') { - // Ignore the line. - } else { - static constexpr auto handle = [](auto& self, kj::ArrayPtr field, - kj::ArrayPtr value) { - auto& pending = self.getPendingMessage(); - // Per the spec, only one space after the colon is optional and trimmed. - // Any other whitespace, or additional spaces aren't accounted for so would - // be part of the value. - if (value.size() > 0 && value[0] == ' ') { - value = value.slice(1); - } - if (field == "data"_kjc) { - pending.data.add(kj::str(value)); - } else if (field == "event"_kjc) { - pending.event = kj::str(value); - } else if (field == "id"_kjc) { - self.state->lastEventId = kj::str(value); - } else if (field == "retry"_kjc) { - KJ_IF_SOME(time, kj::str(value).tryParseAs()) { - self.state->setReconnectionTime(time); - } - // Ignore the line if it cannot be successfully parsed as a uint32_t - } - }; - - KJ_IF_SOME(pos, line.findFirst(':')) { - handle(*this, line.first(pos), line.slice(pos + 1)); - } else { - handle(*this, line, ""_kjc); - } - } - } - - void release() { - if (pendingMessages.empty()) return; - auto pending = pendingMessages.releaseAsArray(); - // If the event source is gone, just drop the messages on the floor. - weakContext->runIfAlive([&](IoContext& context) { - EventSource::enqueueMessages(context, kj::mv(pending), weakEventSource.addRef()); - }); - } - - void clear() { - ended = true; - kept.clear(); - pendingMessages.clear(); - currentPendingMessage = kj::none; - } - - struct EndOfLine { - size_t pos; - kj::ArrayPtr remaining; - }; - kj::Maybe findEndOfLine(kj::ArrayPtr input) { - // The end-of-line marker is either \n, \r, or \r\n - size_t pos = 0; - while (pos < input.size()) { - if (input[pos] == '\n') { - return EndOfLine{pos, input.slice(pos + 1)}; - } else if (input[pos] == '\r') { - if (pos + 1 < input.size() && input[pos + 1] == '\n') { - return EndOfLine{pos, input.slice(pos + 2)}; - } - return EndOfLine{pos, input.slice(pos + 1)}; - } - pos++; - } - return kj::none; - } -}; - -kj::Promise processBody(kj::Promise promise) { - try { - co_await promise; - } catch (...) { - auto ex = kj::getCaughtExceptionAsKj(); - // We would see a disconnection exception if the eventstream is closed for - // multiple kinds of reasons. If it's a network error and we know we can - // reconnect, we should try to reconnect. - if (ex.getType() == kj::Exception::Type::DISCONNECTED) { - co_return; - } - // Propagate the exception up. - kj::throwException(kj::mv(ex)); - } -} -} // namespace - -jsg::Ref EventSource::constructor( - jsg::Lock& js, kj::String url, jsg::Optional init) { - JSG_REQUIRE(IoContext::hasCurrent(), DOMNotSupportedError, - "An EventSource can only be created within the context of a worker request."); - - KJ_IF_SOME(i, init) { - KJ_IF_SOME(withCredentials, i.withCredentials) { - JSG_REQUIRE(!withCredentials, DOMNotSupportedError, - "The init.withCredentials option is not supported. It must be false or undefined."); - } - } - - auto eventsource = js.alloc(js, - JSG_REQUIRE_NONNULL(jsg::Url::tryParse(url.asPtr()), DOMSyntaxError, - kj::str("Cannot open an EventSource to '", url, "'. The URL is invalid.")), - kj::mv(init)); - eventsource->start(js); - return kj::mv(eventsource); -} - -jsg::Ref EventSource::from(jsg::Lock& js, JsReadableStream readable) { - JSG_REQUIRE(IoContext::hasCurrent(), DOMNotSupportedError, - "An EventSource can only be created within the context of a worker request."); - JSG_REQUIRE(!readable.isLocked(js), TypeError, "This ReadableStream is locked."); - JSG_REQUIRE( - !readable.isDisturbed(js), TypeError, "This ReadableStream has already been read from."); - auto eventsource = js.alloc(js); - eventsource->run(js, kj::mv(readable), false /* No reconnection attempts */); - return kj::mv(eventsource); -} - -EventSource::EventSource(jsg::Lock& js, jsg::Url url, kj::Maybe init) - : contextId(IoContext::current().getId()), - streamState(IoContext::current().addObject(kj::refcounted())), - impl({ - .url = kj::mv(url), - .options = kj::mv(init).orDefault({}), - }), - abortController(js.alloc(js)), - readyState(State::CONNECTING) {} - -EventSource::EventSource(jsg::Lock& js) - : contextId(IoContext::current().getId()), - streamState(IoContext::current().addObject(kj::refcounted())), - abortController(js.alloc(js)), - readyState(State::CONNECTING) {} - -IoContext& EventSource::getContext() { - IoContext::requireCurrentOrThrowJs(contextId); - return IoContext::current(); -} - -void EventSource::notifyError( - jsg::Lock& js, const jsg::JsValue& error, bool reconnecting, AlreadyReported alreadyReported) { - getContext(); - if (readyState == State::CLOSED) return; - - // Abort the connection if it hasn't already been. This will be a non-op if the - // controller has already been aborted. - abortController->abort(js, error); - - if (!reconnecting) - readyState = State::CLOSED; - else - readyState = State::CONNECTING; - - // Dispatch the error event. Report-only: the EventSource is already errored out at this - // point, so a throwing 'error' listener has its exception reported but triggers no - // further fail-fast reaction. - dispatchEventImpl(js, js.alloc(js, error), - effectiveExceptionPolicy(js, DispatchExceptionPolicy::REPORT)); - - if (alreadyReported == AlreadyReported::NO) { - // Log the error as an uncaught exception for debugging purposes. - IoContext::current().logUncaughtException(UncaughtExceptionSource::ASYNC_TASK, error); - } -} - -void EventSource::notifyOpen(jsg::Lock& js) { - getContext(); - if (readyState == State::CLOSED) return; - readyState = State::OPEN; - auto result = dispatchEventImpl( - js, js.alloc(), effectiveExceptionPolicy(js, DispatchExceptionPolicy::REPORT)); - KJ_IF_SOME(exception, result.firstException) { - // An 'open' listener threw. Its exception was reported (and the remaining listeners - // still ran); fail fast by erroring out the EventSource. - notifyError(js, exception.getHandle(js), false, AlreadyReported::YES); - } -} - -void EventSource::notifyMessages(jsg::Lock& js, kj::Array messages) { - getContext(); - if (readyState == State::CLOSED) return; - auto policy = effectiveExceptionPolicy(js, DispatchExceptionPolicy::REPORT); - // Under PROPAGATE (spec_compliant_dispatch_exceptions disabled), the first throwing - // listener ends the dispatch and its exception lands in the catch handler below, which - // errors out the EventSource — rather than escaping into (and failing) the enclosing - // read-loop task with no 'error' event at all. - js.tryCatch([&] { - for (auto& message: messages) { - auto data = kj::str(kj::delimited(kj::mv(message.data), "\n"_kjc)); - if (data.size() == 0) continue; - kj::String type = kj::mv(message.event).orDefault([]() { return kj::str("message"); }); - auto result = dispatchEventImpl(js, - js.alloc(js, kj::mv(type), js.str(data), kj::mv(message.id), - kj::none /** source **/, impl.map([](FetchImpl& i) -> jsg::Url& { return i.url; }), - Trusted::YES), - policy); - KJ_IF_SOME(exception, result.firstException) { - // A listener threw under REPORT. Its exception was reported (and the remaining - // listeners for this event still ran); fail fast: error out the EventSource and - // drop the remaining messages in this batch. - notifyError(js, exception.getHandle(js), false, AlreadyReported::YES); - return; - } - } - }, [&](jsg::Value exception) { notifyError(js, jsg::JsValue(exception.getHandle(js))); }); -} - -void EventSource::reconnect(jsg::Lock& js) { - auto& context = getContext(); - if (readyState == State::CLOSED) return; - KJ_ASSERT(impl != kj::none); - readyState = State::CONNECTING; - abortController = js.alloc(js); - auto signal = abortController->getSignal(); - context.awaitIo(js, signal->wrap(js, context.afterLimitTimeout(streamState->reconnectionTime))) - .then(js, - JSG_VISITABLE_LAMBDA( - (self = JSG_THIS), (self), (jsg::Lock & js) mutable { self->start(js); }), - JSG_VISITABLE_LAMBDA((self = JSG_THIS), (self), (jsg::Lock& js, jsg::Value exception) { - // In this case, it is most likely the EventSource was closed by the user or - // there was some other failure. We should not continue trying to reconnect. - self->notifyError(js, jsg::JsValue(exception.getHandle(js))); - })); -} - -void EventSource::start(jsg::Lock& js) { - getContext(); - auto& i = KJ_ASSERT_NONNULL(impl); - if (readyState == State::CLOSED) return; - - auto fetcher = i.options.fetcher.map([](jsg::Ref& f) { return f.addRef(); }); - - static constexpr auto handleError = [](auto& js, auto& self, kj::String message) { - self->notifyError(js, js.domException(kj::str("AbortError"), kj::mv(message))); - return js.resolvedPromise(); - }; - - auto onSuccess = JSG_VISITABLE_LAMBDA( - (self = JSG_THIS, fetcher = fetcher.map([](jsg::Ref& f) -> jsg::Ref { - return f.addRef(); - })), - (self, fetcher), (jsg::Lock& js, jsg::Ref response) { - self->getContext(); - if (self->readyState == State::CLOSED) return js.resolvedPromise(); - auto& impl = KJ_ASSERT_NONNULL(self->impl); - if (!response->getOk()) { - // Response status code is not 2xx, so we fail. - // No reconnection attempt should be made. - return handleError( - js, self, kj::str("The response status code was ", response->getStatus(), ".")); - } - - KJ_IF_SOME(contentType, - response->getHeaders(js)->getCommon(js, capnp::CommonHeaderName::CONTENT_TYPE)) { - bool invalid = false; - KJ_IF_SOME(parsed, MimeType::tryParse(contentType)) { - invalid = parsed != MimeType::EVENT_STREAM; - } else { - invalid = true; - } - if (invalid) { - // No reconnection attempt should be made. - return handleError(js, self, kj::str("The content type '", contentType, "' is invalid.")); - } - } else { - // No reconnection attempt should be made. - return handleError( - js, self, kj::str("No content type header was present in the response.")); - } - - // If the request was redirected, update the URL to the new location. - if (response->getRedirected()) { - KJ_IF_SOME(newUrl, jsg::Url::tryParse(response->getUrl())) { - impl.url = kj::mv(newUrl); - } else { - } // Extra else block to squash compiler warning - } - - KJ_IF_SOME(body, response->getBody(js)) { - // Well, ok! We're ready to start trying to process the stream! We do so by - // pumping the body into an EventSourceSink until the body is closed, canceled, - // or errored. - self->run(js, kj::mv(body), true, response.addRef(), kj::mv(fetcher)); - return js.resolvedPromise(); - } else { - auto& i = KJ_ASSERT_NONNULL(self->impl); - // If there is no body, there's nothing to do. We'll treat this as if - // the server disconnected. If it only happens once, we'll try to reconnect. - // If it happens again, we'll fail the connection as it is likely indicative - // of a bug in the server or along the path to the server. - if (i.previousNoBody) { - self->notifyError(js, js.error("The server provided no content.")); - } else { - i.previousNoBody = true; - self->notifyError(js, js.error("The server provided no content. Will try reconnecting."), - true /* reconnecting */); - self->reconnect(js); - } - return js.resolvedPromise(); - } - }); - - auto onFailed = - JSG_VISITABLE_LAMBDA((self = JSG_THIS), (self), (jsg::Lock& js, jsg::Value exception) { - self->notifyError(js, jsg::JsValue(exception.getHandle(js))); - return js.resolvedPromise(); - }); - - auto headers = js.alloc(); - headers->setCommon(capnp::CommonHeaderName::ACCEPT, MimeType::EVENT_STREAM.essence()); - headers->setCommon(capnp::CommonHeaderName::CACHE_CONTROL, kj::str("no-cache")); - if (streamState->lastEventId != ""_kjc) { - headers->setUnguarded(js, kj::str("last-event-id"), kj::str(streamState->lastEventId)); - } - - fetchImpl(js, kj::mv(fetcher), kj::str(i.url), - RequestInitializerDict{ - .headers = kj::mv(headers), - .signal = abortController->getSignal(), - }) - .then(js, kj::mv(onSuccess), kj::mv(onFailed)); -} - -namespace { -template -kj::Maybe> addRef(kj::Maybe>& ref) { - return ref.map([](jsg::Ref& r) { return r.addRef(); }); -} -} // namespace - -void EventSource::run(jsg::Lock& js, - JsReadableStream readable, - bool withReconnection, - kj::Maybe> response, - kj::Maybe> fetcher) { - auto& context = getContext(); - notifyOpen(js); - if (readyState == State::CLOSED) return; - - KJ_IF_SOME(resp, response) { - JSG_REQUIRE(resp->getType() != "error"_kj, TypeError, - "Error responses are unsupported with EventSource"); - } - - auto onSuccess = - JSG_VISITABLE_LAMBDA((self = JSG_THIS, readable = readable.addRef(js), withReconnection, - response = addRef(response), fetcher = addRef(fetcher)), - (self, readable, response, fetcher), (jsg::Lock& js) { - self->getContext(); - if (self->readyState == State::CLOSED) return; - // The pump finished. Did the server disconnect? If so, try reconnecting if we can. - self->notifyError(js, js.error("The server disconnected."), withReconnection); - if (withReconnection) self->reconnect(js); - }); - - auto onFailed = JSG_VISITABLE_LAMBDA( - (self = JSG_THIS, response = addRef(response), fetcher = addRef(fetcher)), - (self, response, fetcher), (jsg::Lock& js, jsg::Value exception) { - // If the pump fails, catch the error and convert it into an error event. - // If we got here, it likely isn't just a DISCONNECT event. Let's not - // try to reconnect at this point. - self->notifyError(js, jsg::JsValue(exception.getHandle(js))); - }); - - // Transfer ownership of all parser state before pumpTo(), which can start work and then - // throw before returning a promise. The sink must not borrow from this EventSource. - auto sink = newSink(js); - context - .awaitIo(js, - processBody( - context.waitForDeferredProxy(readable.pumpTo(js, kj::mv(sink), EndStream::YES)))) - .then(js, kj::mv(onSuccess), kj::mv(onFailed)); -} - -kj::Own EventSource::newSink(jsg::Lock& js) { - auto& context = getContext(); - return kj::heap( - context, kj::addRef(*streamState), kj::rc>(JSG_THIS_WEAK(js))); -} - -void EventSource::close(jsg::Lock& js) { - if (closeCalled) return; - getContext(); - closeCalled = true; - abortController->abort(js, kj::none); - readyState = State::CLOSED; -} - -void EventSource::enqueueMessages(IoContext& context, - kj::Array messages, - kj::Rc> weakSelf) { - context.addTask( - context.run([weakSelf = kj::mv(weakSelf), messages = kj::mv(messages)](auto& lock) mutable { - KJ_IF_SOME(self, weakSelf->tryAddRef(lock)) { - self->notifyMessages(lock, kj::mv(messages)); - } - })); -} - -void EventSource::StreamState::setReconnectionTime(uint32_t time) { - // We enforce both a min and max reconnection time. The minimum is 1 second, - // and the maximum is 10 seconds. - reconnectionTime = - kj::max(kj::min(time, static_cast(10000)), static_cast(1000)) * - kj::MILLISECONDS; -} - -void EventSource::visitForGc(jsg::GcVisitor& visitor) { - KJ_IF_SOME(i, impl) { - visitor.visit(i.options.fetcher); - } - visitor.visit(abortController); -} - -void EventSource::visitForMemoryInfo(jsg::MemoryTracker& tracker) const { - KJ_IF_SOME(i, impl) { - tracker.trackField("fetcher", i.options.fetcher); - tracker.trackField("url", i.url); - } - tracker.trackField("abortController", abortController); - KJ_IF_SOME(state, streamState.tryGet()) { - tracker.trackField("streamState", &state); - } -} - -} // namespace workerd::api diff --git a/src/workerd/api/eventsource.h b/src/workerd/api/eventsource.h deleted file mode 100644 index 4ad6840e911..00000000000 --- a/src/workerd/api/eventsource.h +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) 2017-2024 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 - -#pragma once -#include "basics.h" -#include "events.h" -#include "http.h" - -#include -#include -#include - -namespace workerd::api { - -WD_STRONG_BOOL(AlreadyReported); - -using kj::uint; -class Fetcher; -class ReadableStream; -class Response; - -// Implements the web standard EventSource API -// https://developer.mozilla.org/en-US/docs/Web/API/EventSource -// -// Under the TS_EVENT_SOURCE autogate, EventSource is instead the TypeScript implementation in -// src/per_isolate/eventsource/, installed by the per-isolate bootstrap, and this class is -// registered but never exposed. -class EventSource: public EventTarget { - public: - struct EventSourceInit { - // We don't actually make use of the standard withCredentials option. If this is set to - // any truthy value, we'll throw. - jsg::Optional withCredentials; - - // This is a non-standard workers-specific extension that allows the EventSource to - // use a custom Fetcher instance. - jsg::Optional> fetcher; - JSG_STRUCT(withCredentials, fetcher); - }; - - enum class State { - CONNECTING = 0, - OPEN = 1, - CLOSED = 2, - }; - - EventSource(jsg::Lock& js, jsg::Url url, kj::Maybe init = kj::none); - - EventSource(jsg::Lock& js); - - static jsg::Ref constructor( - jsg::Lock& js, kj::String url, jsg::Optional init); - - kj::ArrayPtr getUrl() const { - KJ_IF_SOME(i, impl) { - return i.url.getHref(); - } - return nullptr; - } - bool getWithCredentials() const { - return false; - } - uint getReadyState() const { - return static_cast(readyState); - } - - void close(jsg::Lock& js); - - // A non-standard extension that creates an EventSource instance around a ReadableStream - // instance. In this instance, automatic reconnection is disabled since there is no URL - // or underlying fetch used. The ReadableStream instance must produce bytes. It will be - // locked and disturbed, and will be read until it either ends or errors. Calling close() - // will cause the stream to be canceled. - static jsg::Ref from(jsg::Lock& js, JsReadableStream stream); - - // The onopen, onmessage, and onerror event handler IDL attributes - // (see EventTarget::setEventHandlerAttribute). - kj::Maybe getOnOpen(jsg::Lock& js) { - return getEventHandlerAttribute(js, "open"_kj); - } - void setOnOpen( - jsg::Lock& js, jsg::Optional> handler) { - setEventHandlerAttribute(js, "open"_kj, kj::mv(handler)); - } - kj::Maybe getOnMessage(jsg::Lock& js) { - return getEventHandlerAttribute(js, "message"_kj); - } - void setOnMessage( - jsg::Lock& js, jsg::Optional> handler) { - setEventHandlerAttribute(js, "message"_kj, kj::mv(handler)); - } - kj::Maybe getOnError(jsg::Lock& js) { - return getEventHandlerAttribute(js, "error"_kj); - } - void setOnError( - jsg::Lock& js, jsg::Optional> handler) { - setEventHandlerAttribute(js, "error"_kj, kj::mv(handler)); - } - - JSG_RESOURCE_TYPE(EventSource) { - JSG_INHERIT(EventTarget); - JSG_METHOD(close); - JSG_READONLY_PROTOTYPE_PROPERTY(url, getUrl); - JSG_READONLY_PROTOTYPE_PROPERTY(withCredentials, getWithCredentials); - JSG_READONLY_PROTOTYPE_PROPERTY(readyState, getReadyState); - JSG_PROTOTYPE_PROPERTY(onopen, getOnOpen, setOnOpen); - JSG_PROTOTYPE_PROPERTY(onmessage, getOnMessage, setOnMessage); - JSG_PROTOTYPE_PROPERTY(onerror, getOnError, setOnError); - JSG_STATIC_CONSTANT_NAMED(CONNECTING, static_cast(State::CONNECTING)); - JSG_STATIC_CONSTANT_NAMED(OPEN, static_cast(State::OPEN)); - JSG_STATIC_CONSTANT_NAMED(CLOSED, static_cast(State::CLOSED)); - JSG_STATIC_METHOD(from); - - // EventSource is not defined by the spec as being disposable using ERM, but - // it makes sense to do so. The dispose operation simply defers to close(). - // This will enable `using eventsource = new EventSource(...)` - JSG_DISPOSE(close); - } - - struct PendingMessage { - kj::Vector data; - kj::Maybe event; - kj::String id; - }; - - // Called by the internal implementation to notify the EventSource about messages - // received from the server. - static void enqueueMessages(IoContext& context, - kj::Array messages, - kj::Rc> weakSelf); - - // The native parser owns its state and refers back to this EventSource only weakly. - kj::Own newSink(jsg::Lock& js); - - // Shared with the sink, which can survive failure to register the pump's JS callbacks. - // This state has no references back to the EventSource or its request. - struct StreamState final: public kj::Refcounted { - kj::String lastEventId; - kj::Duration reconnectionTime = 2 * kj::SECONDS; - void setReconnectionTime(uint32_t time); - - JSG_MEMORY_INFO(StreamState) { - tracker.trackField("lastEventId", lastEventId); - } - }; - - void visitForGc(jsg::GcVisitor& visitor); - void visitForMemoryInfo(jsg::MemoryTracker& tracker) const; - - private: - IoContext& getContext(); - IoContext::Id contextId; - // IoOwn's checked lookup is non-const, including for read-only heap snapshot traversal. - mutable IoOwn streamState; - struct FetchImpl { - jsg::Url url; - EventSourceInit options; - // Indicates that the server previously responded with no content after a - // successful connection. This is likely indicative of a bug on the server. - // If this happens once, we'll try to reconnect. If it happens again, we'll - // fail the connection. - bool previousNoBody = false; - }; - // Used when the EventSource is created using the constructor. This - // is the normal mode of operation, when the EventSource uses fetch - // under the covers to connect, and reconnect, to the server. This - // will be kj::none when the EventSource is created using the from() - // method. - kj::Maybe impl; - jsg::Ref abortController; - State readyState; - - // Indicates that the close method has been previously called. - bool closeCalled = false; - - // The EventSource spec defines onopen, onmessage, and onerror as prototype - // properties on the class. - - void notifyOpen(jsg::Lock& js); - // AlreadyReported::YES indicates the error was already delivered to the global scope's - // report-an-exception machinery (a reported listener exception), so notifyError() must - // not log it again. - void notifyError(jsg::Lock& js, - const jsg::JsValue& error, - bool reconnecting = false, - AlreadyReported alreadyReported = AlreadyReported::NO); - void notifyMessages(jsg::Lock& js, kj::Array messages); - - // The run() method handles the actual processing of the stream. - void run(jsg::Lock& js, - JsReadableStream stream, - bool withReconnection = true, - kj::Maybe> response = kj::none, - kj::Maybe> fetcher = kj::none); - // The start() method initializes the fetch and the processing of the - // stream by calling run. - void start(jsg::Lock& js); - void reconnect(jsg::Lock& js); -}; - -} // namespace workerd::api - -#define EW_EVENTSOURCE_ISOLATE_TYPES api::EventSource, api::EventSource::EventSourceInit diff --git a/src/workerd/api/global-scope.c++ b/src/workerd/api/global-scope.c++ index 866f479c708..987ecb2a5e2 100644 --- a/src/workerd/api/global-scope.c++ +++ b/src/workerd/api/global-scope.c++ @@ -9,7 +9,6 @@ #include #include #include -#include #ifdef WORKERD_FUZZILLI #include #endif diff --git a/src/workerd/api/global-scope.h b/src/workerd/api/global-scope.h index 8e60ce76615..cef0c10578b 100644 --- a/src/workerd/api/global-scope.h +++ b/src/workerd/api/global-scope.h @@ -43,7 +43,6 @@ class JsRpcProperty; class Crypto; class CryptoKey; class ErrorEvent; -class EventSource; class FixedLengthStream; class SubtleCrypto; class TextDecoder; @@ -1049,11 +1048,8 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope { JSG_NESTED_TYPE(StorageManager); } - // Under the TS_EVENT_SOURCE autogate, the per-isolate bootstrap (src/per_isolate/main.ts) - // installs the TypeScript EventSource instead. - if (!util::Autogate::isEnabled(util::AutogateKey::TS_EVENT_SOURCE)) { - JSG_NESTED_TYPE(EventSource); - } + // The per-isolate bootstrap (src/per_isolate/main.ts) defines EventSource; the TypeScript + // override below declares it. // The bootstrap installs the TypeScript controllers regardless of streams_enable_constructors. if (flags.getStreamsJavaScriptControllers() && !flags.getTypeScriptImplementedStreams()) { @@ -1288,6 +1284,7 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope { MessageChannel: typeof MessageChannel; MessagePort: typeof MessagePort; + EventSource: typeof EventSource; }); } diff --git a/src/workerd/api/rtti.c++ b/src/workerd/api/rtti.c++ index 3a62cf48833..09754fe5ee2 100644 --- a/src/workerd/api/rtti.c++ +++ b/src/workerd/api/rtti.c++ @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include @@ -86,7 +85,6 @@ F("base64", EW_BASE64_ISOLATE_TYPES) \ F("node", EW_NODE_ISOLATE_TYPES) \ F("rtti", EW_RTTI_ISOLATE_TYPES) \ - F("eventsource", EW_EVENTSOURCE_ISOLATE_TYPES) \ F("container", EW_CONTAINER_ISOLATE_TYPES) \ F("webfs", EW_WEB_FILESYSTEM_ISOLATE_TYPE) \ F("messagechannel", EW_MESSAGECHANNEL_ISOLATE_TYPES) \ diff --git a/src/workerd/server/workerd-api-isolate.h b/src/workerd/server/workerd-api-isolate.h index cefd416a5fe..dabc1b8e075 100644 --- a/src/workerd/server/workerd-api-isolate.h +++ b/src/workerd/server/workerd-api-isolate.h @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include @@ -118,7 +117,6 @@ namespace workerd::server { EW_NODE_ISOLATE_TYPES, \ EW_RTTI_ISOLATE_TYPES, \ EW_HYPERDRIVE_ISOLATE_TYPES, \ - EW_EVENTSOURCE_ISOLATE_TYPES, \ EW_WORKER_LOADER_ISOLATE_TYPES, \ EW_MESSAGECHANNEL_ISOLATE_TYPES, \ EW_WORKERS_MODULE_ISOLATE_TYPES, \ diff --git a/src/workerd/tools/param-names-ast.c++ b/src/workerd/tools/param-names-ast.c++ index 38c9dc3c362..4bd86e56b1c 100644 --- a/src/workerd/tools/param-names-ast.c++ +++ b/src/workerd/tools/param-names-ast.c++ @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include diff --git a/src/workerd/util/autogate.h b/src/workerd/util/autogate.h index 8bd91b7ab30..7135fa07391 100644 --- a/src/workerd/util/autogate.h +++ b/src/workerd/util/autogate.h @@ -93,9 +93,6 @@ namespace workerd::util { logged by the TypeScript implementation (src/node/internal/internal_fs_stdio.ts) rather \ than by StdioFile in io/worker-fs.c++. The C++ implementation is retained for rollback. */ \ V(TS_STDIO) \ - /* EventSource is the TypeScript implementation from the per-isolate bootstrap \ - (src/per_isolate/eventsource/) rather than the C++ class in api/eventsource.h. */ \ - V(TS_EVENT_SOURCE) \ /* URL and URLSearchParams are the TypeScript implementations from the per-isolate bootstrap \ (src/per_isolate/url/) rather than the C++ classes in api/url.h and api/url-standard.h. */ \ V(TS_URL) \ diff --git a/src/wpt/eventsource-test.ts b/src/wpt/eventsource-test.ts index 74f87d96b1b..3615ce0f237 100644 --- a/src/wpt/eventsource-test.ts +++ b/src/wpt/eventsource-test.ts @@ -4,15 +4,6 @@ import { type TestRunnerConfig } from 'harness/harness'; -// The TypeScript EventSource (the TS_EVENT_SOURCE autogate) matches the C++ -// one's shape, but its functions are not native. -const usingTsEventSource = !( - EventSource as unknown as { from: () => void } -).from - .toString() - .includes('[native code]'); -const kFailsWithCppEventSource = usingTsEventSource ? [] : true; - const kListenerThis = "Inside an EventSource listener, `this` is not the EventSource, so the test's this.close() throws"; @@ -54,10 +45,7 @@ export default { comment: 'Uses postMessage which is not available in workerd', omittedTests: true, }, - 'event-data.any.js': { - comment: 'The C++ EventSource drops an event whose data is empty', - expectedFailures: kFailsWithCppEventSource, - }, + 'event-data.any.js': {}, 'eventsource-close.window.js': { comment: 'Window-specific tests are not supported', omittedTests: true, @@ -105,26 +93,15 @@ export default { }, 'eventsource-url.any.js': {}, 'format-bom-2.any.js': {}, - 'format-bom-split.any.js': { - comment: - 'The C++ EventSource does not strip a byte order mark split across chunks', - expectedFailures: kFailsWithCppEventSource, - }, + 'format-bom-split.any.js': {}, 'format-bom-utf-16.any.js': {}, 'format-bom.any.js': {}, 'format-comments.any.js': {}, - 'format-data-before-final-empty-line.any.js': { - comment: - 'The C++ EventSource sets lastEventId from an event that is never dispatched', - expectedFailures: kFailsWithCppEventSource, - }, - 'format-field-data.any.js': { - comment: 'The C++ EventSource drops an event whose data is empty', - expectedFailures: kFailsWithCppEventSource, - }, + 'format-data-before-final-empty-line.any.js': {}, + 'format-field-data.any.js': {}, 'format-field-event-empty.any.js': { - comment: `${kListenerThis}, and with the C++ EventSource the file hangs`, - disabledTests: true, + comment: kListenerThis, + expectedFailures: true, }, 'format-field-event.any.js': { comment: kListenerThis, diff --git a/types/defines/eventsource.d.ts b/types/defines/eventsource.d.ts new file mode 100644 index 00000000000..9d67d7fcacb --- /dev/null +++ b/types/defines/eventsource.d.ts @@ -0,0 +1,53 @@ +// EventSource, a global at every compatibility date. +/** + * 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); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} diff --git a/types/generated-snapshot/experimental/index.d.ts b/types/generated-snapshot/experimental/index.d.ts index fb185f168d6..a4e786d2f70 100755 --- a/types/generated-snapshot/experimental/index.d.ts +++ b/types/generated-snapshot/experimental/index.d.ts @@ -288,7 +288,6 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { FileSystemDirectoryHandle: typeof FileSystemDirectoryHandle; FileSystemWritableFileStream: typeof FileSystemWritableFileStream; StorageManager: typeof StorageManager; - EventSource: typeof EventSource; ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; ReadableStreamDefaultController: typeof ReadableStreamDefaultController; ReadableByteStreamController: typeof ReadableByteStreamController; @@ -335,6 +334,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { PerformanceObserverEntryList: typeof PerformanceObserverEntryList; MessageChannel: typeof MessageChannel; MessagePort: typeof MessagePort; + EventSource: typeof EventSource; } declare function addEventListener( type: Type, @@ -3676,58 +3676,6 @@ declare class Datagram { constructor(data: Uint8Array); get data(): Uint8Array; } -/** - * 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); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} interface ExecOutput { readonly stdout: ArrayBuffer; readonly stderr: ArrayBuffer; @@ -15338,6 +15286,59 @@ declare module "cloudflare:email" { }; export { _EmailMessage as EmailMessage }; } +// EventSource, a global at every compatibility date. +/** + * 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); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} /** * Evaluation context for targeting rules. * Keys are attribute names (e.g. "userId", "country"), values are the attribute values. diff --git a/types/generated-snapshot/experimental/index.ts b/types/generated-snapshot/experimental/index.ts index 10c5b3e874a..cb6f2a3b8b0 100755 --- a/types/generated-snapshot/experimental/index.ts +++ b/types/generated-snapshot/experimental/index.ts @@ -288,7 +288,6 @@ export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { FileSystemDirectoryHandle: typeof FileSystemDirectoryHandle; FileSystemWritableFileStream: typeof FileSystemWritableFileStream; StorageManager: typeof StorageManager; - EventSource: typeof EventSource; ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; ReadableStreamDefaultController: typeof ReadableStreamDefaultController; ReadableByteStreamController: typeof ReadableByteStreamController; @@ -335,6 +334,7 @@ export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { PerformanceObserverEntryList: typeof PerformanceObserverEntryList; MessageChannel: typeof MessageChannel; MessagePort: typeof MessagePort; + EventSource: typeof EventSource; } export declare function addEventListener< Type extends keyof WorkerGlobalScopeEventMap, @@ -3682,58 +3682,6 @@ export declare class Datagram { constructor(data: Uint8Array); get data(): Uint8Array; } -/** - * The **`EventSource`** interface is web content's interface to server-sent events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) - */ -export declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -export interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} export interface ExecOutput { readonly stdout: ArrayBuffer; readonly stderr: ArrayBuffer; @@ -15324,6 +15272,59 @@ export declare type EmailExportedHandler = ( env: Env, ctx: ExecutionContext, ) => void | Promise; +// EventSource, a global at every compatibility date. +/** + * The **`EventSource`** interface is web content's interface to server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) + */ +export declare class EventSource extends EventTarget { + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +export interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} /** * Evaluation context for targeting rules. * Keys are attribute names (e.g. "userId", "country"), values are the attribute values. diff --git a/types/generated-snapshot/index.d.ts b/types/generated-snapshot/index.d.ts index 2b451f8b92e..5c3b5c13015 100755 --- a/types/generated-snapshot/index.d.ts +++ b/types/generated-snapshot/index.d.ts @@ -282,7 +282,6 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; CountQueuingStrategy: typeof CountQueuingStrategy; ErrorEvent: typeof ErrorEvent; - EventSource: typeof EventSource; ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; ReadableStreamDefaultController: typeof ReadableStreamDefaultController; ReadableByteStreamController: typeof ReadableByteStreamController; @@ -336,6 +335,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { PerformanceObserverEntryList: typeof PerformanceObserverEntryList; MessageChannel: typeof MessageChannel; MessagePort: typeof MessagePort; + EventSource: typeof EventSource; } declare function addEventListener( type: Type, @@ -3498,58 +3498,6 @@ interface SocketInfo { remoteAddress?: string; localAddress?: string; } -/** - * 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); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} interface ExecOutput { readonly stdout: ArrayBuffer; readonly stderr: ArrayBuffer; @@ -14970,6 +14918,59 @@ declare module "cloudflare:email" { }; export { _EmailMessage as EmailMessage }; } +// EventSource, a global at every compatibility date. +/** + * 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); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} /** * Evaluation context for targeting rules. * Keys are attribute names (e.g. "userId", "country"), values are the attribute values. diff --git a/types/generated-snapshot/index.ts b/types/generated-snapshot/index.ts index ca3423ee4e7..e5ad3add251 100755 --- a/types/generated-snapshot/index.ts +++ b/types/generated-snapshot/index.ts @@ -282,7 +282,6 @@ export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; CountQueuingStrategy: typeof CountQueuingStrategy; ErrorEvent: typeof ErrorEvent; - EventSource: typeof EventSource; ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; ReadableStreamDefaultController: typeof ReadableStreamDefaultController; ReadableByteStreamController: typeof ReadableByteStreamController; @@ -336,6 +335,7 @@ export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { PerformanceObserverEntryList: typeof PerformanceObserverEntryList; MessageChannel: typeof MessageChannel; MessagePort: typeof MessagePort; + EventSource: typeof EventSource; } export declare function addEventListener< Type extends keyof WorkerGlobalScopeEventMap, @@ -3507,58 +3507,6 @@ export interface SocketInfo { remoteAddress?: string; localAddress?: string; } -/** - * The **`EventSource`** interface is web content's interface to server-sent events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) - */ -export declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -export interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} export interface ExecOutput { readonly stdout: ArrayBuffer; readonly stderr: ArrayBuffer; @@ -14959,6 +14907,59 @@ export declare type EmailExportedHandler = ( env: Env, ctx: ExecutionContext, ) => void | Promise; +// EventSource, a global at every compatibility date. +/** + * The **`EventSource`** interface is web content's interface to server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) + */ +export declare class EventSource extends EventTarget { + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +export interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} /** * Evaluation context for targeting rules. * Keys are attribute names (e.g. "userId", "country"), values are the attribute values. diff --git a/types/test/types/eventsource.ts b/types/test/types/eventsource.ts new file mode 100644 index 00000000000..46fe7e2a4b9 --- /dev/null +++ b/types/test/types/eventsource.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +function expectType(_value: T) {} + +const kUrl = 'https://example.com/events'; + +const source = new EventSource(kUrl); +expectType(source); +expectType(source.url); +expectType(source.withCredentials); +expectType(source.readyState); +// @ts-expect-error readyState is read-only. +source.readyState = EventSource.CLOSED; +source.onopen = (event: Event) => event.type; +source.onmessage = (event: MessageEvent) => event.data; +source.onerror = null; +source.close(); + +expectType(EventSource.CONNECTING); +expectType(EventSource.OPEN); +expectType(EventSource.CLOSED); + +declare const fetcher: Fetcher; +new EventSource(kUrl, { fetcher }); +new EventSource(kUrl, { withCredentials: false }); +// @ts-expect-error a fetcher is a Fetcher. +new EventSource(kUrl, { fetcher: {} }); +// @ts-expect-error the URL is required. +new EventSource(); + +declare const stream: ReadableStream; +expectType(EventSource.from(stream)); + +expectType(self.EventSource);