@panyam/servicekit-client 0.0.6 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/sse.test.d.ts +2 -0
- package/dist/__tests__/sse.test.d.ts.map +1 -0
- package/dist/__tests__/sse.test.js +286 -0
- package/dist/__tests__/sse.test.js.map +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +478 -1
- package/dist/servicekit-client.browser.js +478 -1
- package/dist/sse-client.d.ts +117 -0
- package/dist/sse-client.d.ts.map +1 -0
- package/dist/sse-client.js +188 -0
- package/dist/sse-client.js.map +1 -0
- package/dist/sse-mock.d.ts +57 -0
- package/dist/sse-mock.d.ts.map +1 -0
- package/dist/sse-mock.js +108 -0
- package/dist/sse-mock.js.map +1 -0
- package/dist/sse-parser.d.ts +64 -0
- package/dist/sse-parser.d.ts.map +1 -0
- package/dist/sse-parser.js +174 -0
- package/dist/sse-parser.js.map +1 -0
- package/dist/streamable-client.d.ts +80 -0
- package/dist/streamable-client.d.ts.map +1 -0
- package/dist/streamable-client.js +142 -0
- package/dist/streamable-client.js.map +1 -0
- package/package.json +14 -11
- package/src/__tests__/sse.test.ts +358 -0
- package/src/index.ts +22 -3
- package/src/sse-client.ts +232 -0
- package/src/sse-mock.ts +159 -0
- package/src/sse-parser.ts +243 -0
- package/src/streamable-client.ts +171 -0
package/src/index.ts
CHANGED
|
@@ -1,23 +1,28 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @panyam/servicekit-client
|
|
3
3
|
*
|
|
4
|
-
* TypeScript client library for ServiceKit WebSocket protocols.
|
|
4
|
+
* TypeScript client library for ServiceKit WebSocket and SSE protocols.
|
|
5
5
|
*
|
|
6
6
|
* ## Architecture
|
|
7
7
|
*
|
|
8
8
|
* The client mirrors the server-side architecture with two layers:
|
|
9
|
-
* - **Transport layer**: Handles WebSocket connection, ping/pong heartbeats
|
|
9
|
+
* - **Transport layer**: Handles WebSocket/SSE connection, ping/pong heartbeats
|
|
10
10
|
* - **Codec layer**: Handles encoding/decoding of data messages
|
|
11
11
|
*
|
|
12
12
|
* Control messages (ping, pong, error) are always JSON at the transport layer,
|
|
13
13
|
* while data messages use the configured codec (JSON, binary protobuf, etc.).
|
|
14
14
|
*
|
|
15
|
-
* ## Clients
|
|
15
|
+
* ## WebSocket Clients
|
|
16
16
|
*
|
|
17
17
|
* - `BaseWSClient`: Low-level WebSocket with auto ping/pong (for http/JSONConn)
|
|
18
18
|
* - `GRPCWSClient`: gRPC-style streaming with envelope protocol (for grpcws)
|
|
19
19
|
* - `TypedGRPCWSClient`: Type-safe wrapper for GRPCWSClient
|
|
20
20
|
*
|
|
21
|
+
* ## SSE Clients
|
|
22
|
+
*
|
|
23
|
+
* - `SSEClient`: Server-Sent Events client (for http/SSEServe endpoints)
|
|
24
|
+
* - `StreamableClient`: POST-that-optionally-streams (for http/StreamableServe)
|
|
25
|
+
*
|
|
21
26
|
* ## Codecs
|
|
22
27
|
*
|
|
23
28
|
* - `JSONCodec`: Default, matches server-side JSONCodec
|
|
@@ -80,5 +85,19 @@ export { BaseWSClient } from './base-client';
|
|
|
80
85
|
export { GRPCWSClient, MockController } from './grpcws-client';
|
|
81
86
|
export { TypedGRPCWSClient } from './typed-client';
|
|
82
87
|
|
|
88
|
+
// SSE Clients
|
|
89
|
+
export { SSEClient, SSEClientOptions } from './sse-client';
|
|
90
|
+
export { StreamableClient, StreamableClientOptions } from './streamable-client';
|
|
91
|
+
|
|
92
|
+
// SSE Parser (vendored from eventsource-parser, MIT)
|
|
93
|
+
export {
|
|
94
|
+
createParser,
|
|
95
|
+
EventSourceMessage,
|
|
96
|
+
EventSourceParser,
|
|
97
|
+
ParserCallbacks,
|
|
98
|
+
ParseError,
|
|
99
|
+
} from './sse-parser';
|
|
100
|
+
|
|
83
101
|
// Test utilities
|
|
84
102
|
export { createMockWSPair, MockWSController } from './mock';
|
|
103
|
+
export { createMockSSEPair, MockSSEController } from './sse-mock';
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSEClient — Server-Sent Events client for ServiceKit SSEServe endpoints.
|
|
3
|
+
*
|
|
4
|
+
* Uses `fetch` + `ReadableStream` for SSE consumption (not the browser's
|
|
5
|
+
* native `EventSource`, which is GET-only and doesn't support custom headers).
|
|
6
|
+
*
|
|
7
|
+
* Follows the same patterns as BaseWSClient:
|
|
8
|
+
* - Event handler properties (onMessage, onError, onClose)
|
|
9
|
+
* - Dependency injection for fetch (SSEClientOptions.fetch)
|
|
10
|
+
* - Static createMock() for testing
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* const client = new SSEClient<MyEvent>();
|
|
15
|
+
* client.onMessage = (data) => console.log('Received:', data);
|
|
16
|
+
* client.onEvent = (type, data) => console.log('Event:', type, data);
|
|
17
|
+
* await client.connect('http://localhost:8080/events');
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { MessageHandler, ErrorHandler, VoidHandler } from './types';
|
|
22
|
+
import { createParser } from './sse-parser';
|
|
23
|
+
import { createMockSSEPair, MockSSEController } from './sse-mock';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Options for configuring SSEClient.
|
|
27
|
+
*/
|
|
28
|
+
export interface SSEClientOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Custom fetch implementation (for Node.js or testing).
|
|
31
|
+
* Default: globalThis.fetch
|
|
32
|
+
*/
|
|
33
|
+
fetch?: typeof globalThis.fetch;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* HTTP headers to include in the SSE request.
|
|
37
|
+
* Useful for authentication tokens.
|
|
38
|
+
*/
|
|
39
|
+
headers?: Record<string, string>;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Initial Last-Event-ID for reconnection.
|
|
43
|
+
* If set, the client sends this as the Last-Event-ID header on connect.
|
|
44
|
+
*/
|
|
45
|
+
lastEventId?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* SSE client for long-lived server-sent event streams.
|
|
50
|
+
*
|
|
51
|
+
* Connects to SSEServe endpoints via HTTP GET, parses the SSE stream using
|
|
52
|
+
* a vendored WHATWG-compliant parser, and dispatches events to handlers.
|
|
53
|
+
*
|
|
54
|
+
* Features:
|
|
55
|
+
* - Custom headers (auth tokens) — unlike native EventSource
|
|
56
|
+
* - POST support — unlike native EventSource
|
|
57
|
+
* - Keepalive comments silently consumed
|
|
58
|
+
* - Last-Event-ID tracking for reconnection
|
|
59
|
+
* - Mock utilities for testing (SSEClient.createMock())
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```typescript
|
|
63
|
+
* const client = new SSEClient<{ status: string }>();
|
|
64
|
+
* client.onMessage = (data) => console.log(data.status);
|
|
65
|
+
* client.onEvent = (type, data) => console.log(type, data);
|
|
66
|
+
* client.onClose = () => console.log('Stream ended');
|
|
67
|
+
* await client.connect('http://localhost:8080/events', {
|
|
68
|
+
* headers: { Authorization: 'Bearer token' },
|
|
69
|
+
* });
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
export class SSEClient<O = unknown> {
|
|
73
|
+
private _fetch: typeof globalThis.fetch;
|
|
74
|
+
private _headers: Record<string, string>;
|
|
75
|
+
private _lastEventId: string | undefined;
|
|
76
|
+
private _connected = false;
|
|
77
|
+
private _abortController: AbortController | null = null;
|
|
78
|
+
|
|
79
|
+
/** Called when an unnamed data event is received (no "event:" field). */
|
|
80
|
+
public onMessage: MessageHandler<O> = () => {};
|
|
81
|
+
|
|
82
|
+
/** Called when a named event is received (has "event:" field). */
|
|
83
|
+
public onEvent: (event: string, data: O) => void = () => {};
|
|
84
|
+
|
|
85
|
+
/** Called when the SSE stream closes (server closes or network error). */
|
|
86
|
+
public onClose: VoidHandler = () => {};
|
|
87
|
+
|
|
88
|
+
/** Called when an error occurs (fetch failure, parse error). */
|
|
89
|
+
public onError: ErrorHandler = () => {};
|
|
90
|
+
|
|
91
|
+
constructor(options: SSEClientOptions = {}) {
|
|
92
|
+
this._fetch = options.fetch ?? globalThis.fetch;
|
|
93
|
+
this._headers = options.headers ?? {};
|
|
94
|
+
this._lastEventId = options.lastEventId;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Connect to an SSE endpoint.
|
|
99
|
+
*
|
|
100
|
+
* @param url The HTTP URL to connect to
|
|
101
|
+
* @returns Promise that resolves when the connection is established (headers received)
|
|
102
|
+
* @throws Error if the response is not 200 or not text/event-stream
|
|
103
|
+
*/
|
|
104
|
+
async connect(url: string): Promise<void> {
|
|
105
|
+
const headers: Record<string, string> = { ...this._headers };
|
|
106
|
+
if (this._lastEventId) {
|
|
107
|
+
headers['Last-Event-ID'] = this._lastEventId;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
this._abortController = new AbortController();
|
|
111
|
+
|
|
112
|
+
const response = await this._fetch(url, {
|
|
113
|
+
headers,
|
|
114
|
+
signal: this._abortController.signal,
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
if (!response.ok) {
|
|
118
|
+
throw new Error(`SSE connection failed: HTTP ${response.status}`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const contentType = response.headers.get('Content-Type') ?? '';
|
|
122
|
+
if (!contentType.includes('text/event-stream')) {
|
|
123
|
+
throw new Error(`Expected text/event-stream, got ${contentType}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (!response.body) {
|
|
127
|
+
throw new Error('Response has no body');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
this._connected = true;
|
|
131
|
+
|
|
132
|
+
// Start reading the stream in the background
|
|
133
|
+
this._readStream(response.body);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Close the SSE connection.
|
|
138
|
+
* Aborts the underlying fetch request and fires onClose.
|
|
139
|
+
*/
|
|
140
|
+
close(): void {
|
|
141
|
+
if (this._abortController) {
|
|
142
|
+
this._abortController.abort();
|
|
143
|
+
this._abortController = null;
|
|
144
|
+
}
|
|
145
|
+
if (this._connected) {
|
|
146
|
+
this._connected = false;
|
|
147
|
+
this.onClose();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Whether the client is currently connected to an SSE stream. */
|
|
152
|
+
get isConnected(): boolean {
|
|
153
|
+
return this._connected;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The last event ID received from the server (for reconnection). */
|
|
157
|
+
get lastEventId(): string | undefined {
|
|
158
|
+
return this._lastEventId;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Create a mock SSEClient + controller pair for testing.
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```typescript
|
|
166
|
+
* const { client, controller } = SSEClient.createMock();
|
|
167
|
+
* client.onMessage = (data) => received.push(data);
|
|
168
|
+
* await client.connect('http://test/events');
|
|
169
|
+
* controller.simulateMessage({ hello: 'world' });
|
|
170
|
+
* controller.simulateClose();
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
static createMock<O = unknown>(): {
|
|
174
|
+
client: SSEClient<O>;
|
|
175
|
+
controller: MockSSEController;
|
|
176
|
+
} {
|
|
177
|
+
const { fetch, controller } = createMockSSEPair();
|
|
178
|
+
const client = new SSEClient<O>({ fetch });
|
|
179
|
+
return { client, controller };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Read the SSE stream and dispatch events via the parser. */
|
|
183
|
+
private async _readStream(body: ReadableStream<Uint8Array>): Promise<void> {
|
|
184
|
+
const reader = body.getReader();
|
|
185
|
+
const decoder = new TextDecoder();
|
|
186
|
+
|
|
187
|
+
const parser = createParser({
|
|
188
|
+
onEvent: (event) => {
|
|
189
|
+
// Track last event ID for reconnection
|
|
190
|
+
if (event.id !== undefined) {
|
|
191
|
+
this._lastEventId = event.id;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Parse JSON data
|
|
195
|
+
let parsed: O;
|
|
196
|
+
try {
|
|
197
|
+
parsed = JSON.parse(event.data) as O;
|
|
198
|
+
} catch {
|
|
199
|
+
// If not valid JSON, pass raw string as-is
|
|
200
|
+
parsed = event.data as unknown as O;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Dispatch to appropriate handler
|
|
204
|
+
if (event.event) {
|
|
205
|
+
this.onEvent(event.event, parsed);
|
|
206
|
+
} else {
|
|
207
|
+
this.onMessage(parsed);
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
// Comments (keepalive) are silently consumed — no handler needed
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
try {
|
|
214
|
+
while (true) {
|
|
215
|
+
const { done, value } = await reader.read();
|
|
216
|
+
if (done) break;
|
|
217
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
218
|
+
}
|
|
219
|
+
} catch (err) {
|
|
220
|
+
// AbortError is expected when close() is called
|
|
221
|
+
if (err instanceof Error && err.name === 'AbortError') {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
this.onError(String(err));
|
|
225
|
+
} finally {
|
|
226
|
+
if (this._connected) {
|
|
227
|
+
this._connected = false;
|
|
228
|
+
this.onClose();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
package/src/sse-mock.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mock SSE utilities for testing.
|
|
3
|
+
*
|
|
4
|
+
* Provides a fake `fetch` implementation that returns a controllable SSE stream.
|
|
5
|
+
* Follows the same DI pattern as `createMockWSPair` (inject via options).
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { SSEClient } from './sse-client';
|
|
10
|
+
* import { createMockSSEPair } from './sse-mock';
|
|
11
|
+
*
|
|
12
|
+
* const { fetch, controller } = createMockSSEPair();
|
|
13
|
+
* const client = new SSEClient({ fetch });
|
|
14
|
+
* await client.connect('http://test/events');
|
|
15
|
+
* controller.simulateMessage({ hello: 'world' });
|
|
16
|
+
* controller.simulateClose();
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Controller for driving a mock SSE stream in tests.
|
|
22
|
+
*
|
|
23
|
+
* Operates at the SSE protocol level — messages are automatically
|
|
24
|
+
* formatted as SSE events before being enqueued to the stream.
|
|
25
|
+
*/
|
|
26
|
+
export interface MockSSEController {
|
|
27
|
+
/** Simulate receiving an unnamed data event (no "event:" field). */
|
|
28
|
+
simulateMessage(data: unknown): void;
|
|
29
|
+
|
|
30
|
+
/** Simulate receiving a named event with "event:" field. */
|
|
31
|
+
simulateEvent(event: string, data: unknown): void;
|
|
32
|
+
|
|
33
|
+
/** Simulate receiving a named event with "event:" and "id:" fields. */
|
|
34
|
+
simulateEventWithId(event: string, id: string, data: unknown): void;
|
|
35
|
+
|
|
36
|
+
/** Simulate receiving a keepalive comment (": keepalive"). */
|
|
37
|
+
simulateComment(text: string): void;
|
|
38
|
+
|
|
39
|
+
/** Close the SSE stream (fires onClose on the client). */
|
|
40
|
+
simulateClose(): void;
|
|
41
|
+
|
|
42
|
+
/** The URL that was passed to fetch(). */
|
|
43
|
+
readonly receivedUrl: string | undefined;
|
|
44
|
+
|
|
45
|
+
/** The headers that were passed to fetch(). */
|
|
46
|
+
readonly receivedHeaders: Record<string, string>;
|
|
47
|
+
|
|
48
|
+
/** The HTTP method used (GET or POST). */
|
|
49
|
+
readonly receivedMethod: string | undefined;
|
|
50
|
+
|
|
51
|
+
/** The request body (for POST requests). */
|
|
52
|
+
readonly receivedBody: string | undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Create a mock fetch function + controller pair for testing SSE clients.
|
|
57
|
+
*
|
|
58
|
+
* The returned `fetch` can be passed as `SSEClientOptions.fetch`.
|
|
59
|
+
* The controller lets tests push SSE events into the stream.
|
|
60
|
+
*
|
|
61
|
+
* @param contentType - Content-Type header for the response (default: "text/event-stream")
|
|
62
|
+
*/
|
|
63
|
+
export function createMockSSEPair(
|
|
64
|
+
contentType: string = 'text/event-stream',
|
|
65
|
+
): {
|
|
66
|
+
fetch: typeof globalThis.fetch;
|
|
67
|
+
controller: MockSSEController;
|
|
68
|
+
} {
|
|
69
|
+
let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;
|
|
70
|
+
let capturedUrl: string | undefined;
|
|
71
|
+
let capturedHeaders: Record<string, string> = {};
|
|
72
|
+
let capturedMethod: string | undefined;
|
|
73
|
+
let capturedBody: string | undefined;
|
|
74
|
+
|
|
75
|
+
const encoder = new TextEncoder();
|
|
76
|
+
|
|
77
|
+
const enqueue = (text: string) => {
|
|
78
|
+
if (streamController) {
|
|
79
|
+
streamController.enqueue(encoder.encode(text));
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const mockFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
84
|
+
capturedUrl = typeof input === 'string' ? input : input.toString();
|
|
85
|
+
capturedMethod = init?.method ?? 'GET';
|
|
86
|
+
capturedBody =
|
|
87
|
+
typeof init?.body === 'string' ? init.body : undefined;
|
|
88
|
+
|
|
89
|
+
// Capture headers
|
|
90
|
+
capturedHeaders = {};
|
|
91
|
+
if (init?.headers) {
|
|
92
|
+
if (init.headers instanceof Headers) {
|
|
93
|
+
init.headers.forEach((v, k) => {
|
|
94
|
+
capturedHeaders[k] = v;
|
|
95
|
+
});
|
|
96
|
+
} else if (Array.isArray(init.headers)) {
|
|
97
|
+
for (const [k, v] of init.headers) {
|
|
98
|
+
capturedHeaders[k] = v;
|
|
99
|
+
}
|
|
100
|
+
} else {
|
|
101
|
+
capturedHeaders = { ...init.headers } as Record<string, string>;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const body = new ReadableStream<Uint8Array>({
|
|
106
|
+
start(controller) {
|
|
107
|
+
streamController = controller;
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
return new Response(body, {
|
|
112
|
+
status: 200,
|
|
113
|
+
headers: { 'Content-Type': contentType },
|
|
114
|
+
});
|
|
115
|
+
}) as typeof globalThis.fetch;
|
|
116
|
+
|
|
117
|
+
const controller: MockSSEController = {
|
|
118
|
+
simulateMessage(data: unknown) {
|
|
119
|
+
enqueue(`data: ${JSON.stringify(data)}\n\n`);
|
|
120
|
+
},
|
|
121
|
+
|
|
122
|
+
simulateEvent(event: string, data: unknown) {
|
|
123
|
+
enqueue(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
simulateEventWithId(event: string, id: string, data: unknown) {
|
|
127
|
+
enqueue(`event: ${event}\nid: ${id}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
simulateComment(text: string) {
|
|
131
|
+
enqueue(`: ${text}\n\n`);
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
simulateClose() {
|
|
135
|
+
if (streamController) {
|
|
136
|
+
streamController.close();
|
|
137
|
+
streamController = null;
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
get receivedUrl() {
|
|
142
|
+
return capturedUrl;
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
get receivedHeaders() {
|
|
146
|
+
return capturedHeaders;
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
get receivedMethod() {
|
|
150
|
+
return capturedMethod;
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
get receivedBody() {
|
|
154
|
+
return capturedBody;
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
return { fetch: mockFetch, controller };
|
|
159
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WHATWG Server-Sent Events parser.
|
|
3
|
+
*
|
|
4
|
+
* Vendored from eventsource-parser v3.0.6 (MIT License)
|
|
5
|
+
* Copyright (c) 2025 Espen Hovlandsdal <espen@hovlandsdal.com>
|
|
6
|
+
* https://github.com/rexxars/eventsource-parser
|
|
7
|
+
*
|
|
8
|
+
* Consolidated from parse.ts, types.ts, and errors.ts into a single file.
|
|
9
|
+
* The SSE spec is frozen (2015) — no maintenance risk from vendoring.
|
|
10
|
+
*
|
|
11
|
+
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
// ============================================================================
|
|
15
|
+
// Types
|
|
16
|
+
// ============================================================================
|
|
17
|
+
|
|
18
|
+
/** The type of parse error that occurred. */
|
|
19
|
+
export type ErrorType = 'invalid-retry' | 'unknown-field';
|
|
20
|
+
|
|
21
|
+
/** Error thrown when encountering an issue during SSE parsing. */
|
|
22
|
+
export class ParseError extends Error {
|
|
23
|
+
type: ErrorType;
|
|
24
|
+
field?: string | undefined;
|
|
25
|
+
value?: string | undefined;
|
|
26
|
+
line?: string | undefined;
|
|
27
|
+
|
|
28
|
+
constructor(
|
|
29
|
+
message: string,
|
|
30
|
+
options: { type: ErrorType; field?: string; value?: string; line?: string },
|
|
31
|
+
) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = 'ParseError';
|
|
34
|
+
this.type = options.type;
|
|
35
|
+
this.field = options.field;
|
|
36
|
+
this.value = options.value;
|
|
37
|
+
this.line = options.line;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A parsed EventSource message event. */
|
|
42
|
+
export interface EventSourceMessage {
|
|
43
|
+
/** Event type from the "event:" field. Undefined if not set (defaults to "message" in browsers). */
|
|
44
|
+
event?: string | undefined;
|
|
45
|
+
/** Event ID from the "id:" field. Used for reconnection via Last-Event-ID header. */
|
|
46
|
+
id?: string | undefined;
|
|
47
|
+
/** The event data from "data:" field(s). Multi-line data is joined with "\n". */
|
|
48
|
+
data: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** EventSource parser instance returned by createParser. */
|
|
52
|
+
export interface EventSourceParser {
|
|
53
|
+
/** Feed the parser another chunk of SSE data. Triggers callbacks as events are parsed. */
|
|
54
|
+
feed(chunk: string): void;
|
|
55
|
+
/** Reset parser state. Required between reconnections. */
|
|
56
|
+
reset(options?: { consume?: boolean }): void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Callbacks invoked by the parser during stream processing. */
|
|
60
|
+
export interface ParserCallbacks {
|
|
61
|
+
/** Called when a complete event is parsed. */
|
|
62
|
+
onEvent?: ((event: EventSourceMessage) => void) | undefined;
|
|
63
|
+
/** Called when the server sends a reconnection interval via "retry:" field. */
|
|
64
|
+
onRetry?: ((retry: number) => void) | undefined;
|
|
65
|
+
/** Called when a comment line is encountered (lines starting with ":"). */
|
|
66
|
+
onComment?: ((comment: string) => void) | undefined;
|
|
67
|
+
/** Called when a parse error occurs (unknown fields, invalid retry values). */
|
|
68
|
+
onError?: ((error: ParseError) => void) | undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ============================================================================
|
|
72
|
+
// Parser
|
|
73
|
+
// ============================================================================
|
|
74
|
+
|
|
75
|
+
function noop(_arg: unknown) {
|
|
76
|
+
// intentional noop
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Creates a new WHATWG-compliant EventSource parser.
|
|
81
|
+
*
|
|
82
|
+
* @param callbacks - Callbacks to invoke on parsing events
|
|
83
|
+
* @returns Parser with `feed()` and `reset()` methods
|
|
84
|
+
*/
|
|
85
|
+
export function createParser(callbacks: ParserCallbacks): EventSourceParser {
|
|
86
|
+
if (typeof callbacks === 'function') {
|
|
87
|
+
throw new TypeError(
|
|
88
|
+
'`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?',
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
|
|
93
|
+
|
|
94
|
+
let incompleteLine = '';
|
|
95
|
+
let isFirstChunk = true;
|
|
96
|
+
let id: string | undefined;
|
|
97
|
+
let data = '';
|
|
98
|
+
let eventType = '';
|
|
99
|
+
|
|
100
|
+
function feed(newChunk: string) {
|
|
101
|
+
const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, '') : newChunk;
|
|
102
|
+
const [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
|
|
103
|
+
|
|
104
|
+
for (const line of complete) {
|
|
105
|
+
parseLine(line);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
incompleteLine = incomplete;
|
|
109
|
+
isFirstChunk = false;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function parseLine(line: string) {
|
|
113
|
+
if (line === '') {
|
|
114
|
+
dispatchEvent();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (line.startsWith(':')) {
|
|
119
|
+
if (onComment) {
|
|
120
|
+
onComment(line.slice(line.startsWith(': ') ? 2 : 1));
|
|
121
|
+
}
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const fieldSeparatorIndex = line.indexOf(':');
|
|
126
|
+
if (fieldSeparatorIndex !== -1) {
|
|
127
|
+
const field = line.slice(0, fieldSeparatorIndex);
|
|
128
|
+
const offset = line[fieldSeparatorIndex + 1] === ' ' ? 2 : 1;
|
|
129
|
+
const value = line.slice(fieldSeparatorIndex + offset);
|
|
130
|
+
processField(field, value, line);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
processField(line, '', line);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function processField(field: string, value: string, line: string) {
|
|
138
|
+
switch (field) {
|
|
139
|
+
case 'event':
|
|
140
|
+
eventType = value;
|
|
141
|
+
break;
|
|
142
|
+
case 'data':
|
|
143
|
+
data = `${data}${value}\n`;
|
|
144
|
+
break;
|
|
145
|
+
case 'id':
|
|
146
|
+
id = value.includes('\0') ? undefined : value;
|
|
147
|
+
break;
|
|
148
|
+
case 'retry':
|
|
149
|
+
if (/^\d+$/.test(value)) {
|
|
150
|
+
onRetry(parseInt(value, 10));
|
|
151
|
+
} else {
|
|
152
|
+
onError(
|
|
153
|
+
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
154
|
+
type: 'invalid-retry',
|
|
155
|
+
value,
|
|
156
|
+
line,
|
|
157
|
+
}),
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
break;
|
|
161
|
+
default:
|
|
162
|
+
onError(
|
|
163
|
+
new ParseError(
|
|
164
|
+
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}…` : field}"`,
|
|
165
|
+
{ type: 'unknown-field', field, value, line },
|
|
166
|
+
),
|
|
167
|
+
);
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function dispatchEvent() {
|
|
173
|
+
const shouldDispatch = data.length > 0;
|
|
174
|
+
if (shouldDispatch) {
|
|
175
|
+
onEvent({
|
|
176
|
+
id,
|
|
177
|
+
event: eventType || undefined,
|
|
178
|
+
data: data.endsWith('\n') ? data.slice(0, -1) : data,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
id = undefined;
|
|
183
|
+
data = '';
|
|
184
|
+
eventType = '';
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function reset(options: { consume?: boolean } = {}) {
|
|
188
|
+
if (incompleteLine && options.consume) {
|
|
189
|
+
parseLine(incompleteLine);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
isFirstChunk = true;
|
|
193
|
+
id = undefined;
|
|
194
|
+
data = '';
|
|
195
|
+
eventType = '';
|
|
196
|
+
incompleteLine = '';
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return { feed, reset };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ============================================================================
|
|
203
|
+
// Line splitting (handles CR, LF, CRLF correctly per WHATWG spec)
|
|
204
|
+
// ============================================================================
|
|
205
|
+
|
|
206
|
+
function splitLines(chunk: string): [complete: Array<string>, incomplete: string] {
|
|
207
|
+
const lines: Array<string> = [];
|
|
208
|
+
let incompleteLine = '';
|
|
209
|
+
let searchIndex = 0;
|
|
210
|
+
|
|
211
|
+
while (searchIndex < chunk.length) {
|
|
212
|
+
const crIndex = chunk.indexOf('\r', searchIndex);
|
|
213
|
+
const lfIndex = chunk.indexOf('\n', searchIndex);
|
|
214
|
+
|
|
215
|
+
let lineEnd = -1;
|
|
216
|
+
if (crIndex !== -1 && lfIndex !== -1) {
|
|
217
|
+
lineEnd = Math.min(crIndex, lfIndex);
|
|
218
|
+
} else if (crIndex !== -1) {
|
|
219
|
+
if (crIndex === chunk.length - 1) {
|
|
220
|
+
lineEnd = -1;
|
|
221
|
+
} else {
|
|
222
|
+
lineEnd = crIndex;
|
|
223
|
+
}
|
|
224
|
+
} else if (lfIndex !== -1) {
|
|
225
|
+
lineEnd = lfIndex;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (lineEnd === -1) {
|
|
229
|
+
incompleteLine = chunk.slice(searchIndex);
|
|
230
|
+
break;
|
|
231
|
+
} else {
|
|
232
|
+
const line = chunk.slice(searchIndex, lineEnd);
|
|
233
|
+
lines.push(line);
|
|
234
|
+
|
|
235
|
+
searchIndex = lineEnd + 1;
|
|
236
|
+
if (chunk[searchIndex - 1] === '\r' && chunk[searchIndex] === '\n') {
|
|
237
|
+
searchIndex++;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return [lines, incompleteLine];
|
|
243
|
+
}
|