@enclave-vm/stream 0.0.1

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.
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @enclave-vm/stream - NDJSON Parser/Serializer
3
+ *
4
+ * Newline-delimited JSON (NDJSON) parsing and serialization for streaming events.
5
+ * NDJSON format: one JSON object per line, separated by newlines.
6
+ */
7
+ import { type StreamEvent, type MaybeEncrypted, type ParsedStreamEvent, type ParsedEncryptedEnvelope } from '@enclave-vm/types';
8
+ /**
9
+ * Result of parsing an NDJSON line.
10
+ */
11
+ export type ParseResult<T> = {
12
+ success: true;
13
+ data: T;
14
+ } | {
15
+ success: false;
16
+ error: string;
17
+ line: string;
18
+ };
19
+ /**
20
+ * Serialize an event to NDJSON format (single line).
21
+ */
22
+ export declare function serializeEvent(event: MaybeEncrypted<StreamEvent>): string;
23
+ /**
24
+ * Serialize multiple events to NDJSON format.
25
+ */
26
+ export declare function serializeEvents(events: MaybeEncrypted<StreamEvent>[]): string;
27
+ /**
28
+ * Parse a single NDJSON line into an event.
29
+ * Note: The returned type is from Zod parsing, which may have slightly different
30
+ * type inference than the interface types (e.g., string vs template literal).
31
+ */
32
+ export declare function parseLine(line: string): ParseResult<ParsedStreamEvent | ParsedEncryptedEnvelope>;
33
+ /**
34
+ * Parse multiple NDJSON lines into events.
35
+ * Returns successfully parsed events and any errors encountered.
36
+ */
37
+ export declare function parseLines(data: string): {
38
+ events: (ParsedStreamEvent | ParsedEncryptedEnvelope)[];
39
+ errors: Array<{
40
+ line: number;
41
+ error: string;
42
+ content: string;
43
+ }>;
44
+ };
45
+ /**
46
+ * NDJSON stream parser for incremental parsing.
47
+ * Handles partial lines across chunks.
48
+ */
49
+ export declare class NdjsonStreamParser {
50
+ private buffer;
51
+ private readonly onEvent;
52
+ private readonly onError;
53
+ private lineNumber;
54
+ constructor(options: {
55
+ onEvent: (event: ParsedStreamEvent | ParsedEncryptedEnvelope) => void;
56
+ onError: (error: {
57
+ line: number;
58
+ error: string;
59
+ content: string;
60
+ }) => void;
61
+ });
62
+ /**
63
+ * Feed a chunk of data into the parser.
64
+ * Complete lines are parsed and emitted immediately.
65
+ */
66
+ feed(chunk: string): void;
67
+ /**
68
+ * Flush any remaining buffered data.
69
+ * Should be called when the stream ends.
70
+ */
71
+ flush(): void;
72
+ /**
73
+ * Reset the parser state.
74
+ */
75
+ reset(): void;
76
+ /**
77
+ * Get the current line number.
78
+ */
79
+ getLineNumber(): number;
80
+ /**
81
+ * Check if there's pending data in the buffer.
82
+ */
83
+ hasPendingData(): boolean;
84
+ }
85
+ /**
86
+ * Create a transform stream that parses NDJSON.
87
+ * Works with browser fetch() streaming and Node.js streams.
88
+ */
89
+ export declare function createNdjsonParseStream(): TransformStream<string, ParsedStreamEvent | ParsedEncryptedEnvelope>;
90
+ /**
91
+ * Create a transform stream that serializes events to NDJSON.
92
+ */
93
+ export declare function createNdjsonSerializeStream(): TransformStream<MaybeEncrypted<StreamEvent>, string>;
94
+ /**
95
+ * Async generator that parses NDJSON from a ReadableStream.
96
+ */
97
+ export declare function parseNdjsonStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<ParsedStreamEvent | ParsedEncryptedEnvelope>;
package/src/ndjson.js ADDED
@@ -0,0 +1,263 @@
1
+ "use strict";
2
+ /**
3
+ * @enclave-vm/stream - NDJSON Parser/Serializer
4
+ *
5
+ * Newline-delimited JSON (NDJSON) parsing and serialization for streaming events.
6
+ * NDJSON format: one JSON object per line, separated by newlines.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.NdjsonStreamParser = void 0;
10
+ exports.serializeEvent = serializeEvent;
11
+ exports.serializeEvents = serializeEvents;
12
+ exports.parseLine = parseLine;
13
+ exports.parseLines = parseLines;
14
+ exports.createNdjsonParseStream = createNdjsonParseStream;
15
+ exports.createNdjsonSerializeStream = createNdjsonSerializeStream;
16
+ exports.parseNdjsonStream = parseNdjsonStream;
17
+ const types_1 = require("@enclave-vm/types");
18
+ /**
19
+ * Serialize an event to NDJSON format (single line).
20
+ */
21
+ function serializeEvent(event) {
22
+ return JSON.stringify(event);
23
+ }
24
+ /**
25
+ * Serialize multiple events to NDJSON format.
26
+ */
27
+ function serializeEvents(events) {
28
+ return events.map(serializeEvent).join('\n');
29
+ }
30
+ /**
31
+ * Parse a single NDJSON line into an event.
32
+ * Note: The returned type is from Zod parsing, which may have slightly different
33
+ * type inference than the interface types (e.g., string vs template literal).
34
+ */
35
+ function parseLine(line) {
36
+ const trimmed = line.trim();
37
+ // Skip empty lines
38
+ if (trimmed.length === 0) {
39
+ return { success: false, error: 'Empty line', line };
40
+ }
41
+ // Parse JSON
42
+ let parsed;
43
+ try {
44
+ parsed = JSON.parse(trimmed);
45
+ }
46
+ catch (err) {
47
+ return {
48
+ success: false,
49
+ error: `JSON parse error: ${err instanceof Error ? err.message : String(err)}`,
50
+ line,
51
+ };
52
+ }
53
+ // Validate against schema
54
+ const result = (0, types_1.parseStreamEventOrEncrypted)(parsed);
55
+ if (!result.success) {
56
+ return {
57
+ success: false,
58
+ error: `Validation error: ${result.error.message}`,
59
+ line,
60
+ };
61
+ }
62
+ return { success: true, data: result.data };
63
+ }
64
+ /**
65
+ * Parse multiple NDJSON lines into events.
66
+ * Returns successfully parsed events and any errors encountered.
67
+ */
68
+ function parseLines(data) {
69
+ const lines = data.split('\n');
70
+ const events = [];
71
+ const errors = [];
72
+ for (let i = 0; i < lines.length; i++) {
73
+ const line = lines[i];
74
+ if (!line)
75
+ continue;
76
+ const trimmed = line.trim();
77
+ if (trimmed.length === 0)
78
+ continue;
79
+ const result = parseLine(trimmed);
80
+ if (result.success) {
81
+ events.push(result.data);
82
+ }
83
+ else {
84
+ errors.push({
85
+ line: i + 1,
86
+ error: result.error,
87
+ content: trimmed.length > 100 ? trimmed.slice(0, 100) + '...' : trimmed,
88
+ });
89
+ }
90
+ }
91
+ return { events, errors };
92
+ }
93
+ /**
94
+ * NDJSON stream parser for incremental parsing.
95
+ * Handles partial lines across chunks.
96
+ */
97
+ class NdjsonStreamParser {
98
+ buffer = '';
99
+ onEvent;
100
+ onError;
101
+ lineNumber = 0;
102
+ constructor(options) {
103
+ this.onEvent = options.onEvent;
104
+ this.onError = options.onError;
105
+ }
106
+ /**
107
+ * Feed a chunk of data into the parser.
108
+ * Complete lines are parsed and emitted immediately.
109
+ */
110
+ feed(chunk) {
111
+ this.buffer += chunk;
112
+ // Process complete lines
113
+ let newlineIndex;
114
+ while ((newlineIndex = this.buffer.indexOf('\n')) !== -1) {
115
+ const line = this.buffer.slice(0, newlineIndex);
116
+ this.buffer = this.buffer.slice(newlineIndex + 1);
117
+ this.lineNumber++;
118
+ const trimmed = line.trim();
119
+ if (trimmed.length === 0)
120
+ continue;
121
+ const result = parseLine(trimmed);
122
+ if (result.success) {
123
+ this.onEvent(result.data);
124
+ }
125
+ else {
126
+ this.onError({
127
+ line: this.lineNumber,
128
+ error: result.error,
129
+ content: trimmed.length > 100 ? trimmed.slice(0, 100) + '...' : trimmed,
130
+ });
131
+ }
132
+ }
133
+ }
134
+ /**
135
+ * Flush any remaining buffered data.
136
+ * Should be called when the stream ends.
137
+ */
138
+ flush() {
139
+ const trimmed = this.buffer.trim();
140
+ if (trimmed.length > 0) {
141
+ this.lineNumber++;
142
+ const result = parseLine(trimmed);
143
+ if (result.success) {
144
+ this.onEvent(result.data);
145
+ }
146
+ else {
147
+ this.onError({
148
+ line: this.lineNumber,
149
+ error: result.error,
150
+ content: trimmed.length > 100 ? trimmed.slice(0, 100) + '...' : trimmed,
151
+ });
152
+ }
153
+ }
154
+ this.buffer = '';
155
+ }
156
+ /**
157
+ * Reset the parser state.
158
+ */
159
+ reset() {
160
+ this.buffer = '';
161
+ this.lineNumber = 0;
162
+ }
163
+ /**
164
+ * Get the current line number.
165
+ */
166
+ getLineNumber() {
167
+ return this.lineNumber;
168
+ }
169
+ /**
170
+ * Check if there's pending data in the buffer.
171
+ */
172
+ hasPendingData() {
173
+ return this.buffer.trim().length > 0;
174
+ }
175
+ }
176
+ exports.NdjsonStreamParser = NdjsonStreamParser;
177
+ /**
178
+ * Create a transform stream that parses NDJSON.
179
+ * Works with browser fetch() streaming and Node.js streams.
180
+ */
181
+ function createNdjsonParseStream() {
182
+ let buffer = '';
183
+ return new TransformStream({
184
+ transform(chunk, controller) {
185
+ buffer += chunk;
186
+ let newlineIndex;
187
+ while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
188
+ const line = buffer.slice(0, newlineIndex);
189
+ buffer = buffer.slice(newlineIndex + 1);
190
+ const trimmed = line.trim();
191
+ if (trimmed.length === 0)
192
+ continue;
193
+ const result = parseLine(trimmed);
194
+ if (result.success) {
195
+ controller.enqueue(result.data);
196
+ }
197
+ // Note: errors are silently dropped in transform stream
198
+ // Use NdjsonStreamParser for error handling
199
+ }
200
+ },
201
+ flush(controller) {
202
+ const trimmed = buffer.trim();
203
+ if (trimmed.length > 0) {
204
+ const result = parseLine(trimmed);
205
+ if (result.success) {
206
+ controller.enqueue(result.data);
207
+ }
208
+ }
209
+ },
210
+ });
211
+ }
212
+ /**
213
+ * Create a transform stream that serializes events to NDJSON.
214
+ */
215
+ function createNdjsonSerializeStream() {
216
+ return new TransformStream({
217
+ transform(event, controller) {
218
+ controller.enqueue(serializeEvent(event) + '\n');
219
+ },
220
+ });
221
+ }
222
+ /**
223
+ * Async generator that parses NDJSON from a ReadableStream.
224
+ */
225
+ async function* parseNdjsonStream(stream) {
226
+ const decoder = new TextDecoder();
227
+ const reader = stream.getReader();
228
+ let buffer = '';
229
+ try {
230
+ while (true) {
231
+ const { done, value } = await reader.read();
232
+ if (done) {
233
+ // Process any remaining data
234
+ const trimmed = buffer.trim();
235
+ if (trimmed.length > 0) {
236
+ const result = parseLine(trimmed);
237
+ if (result.success) {
238
+ yield result.data;
239
+ }
240
+ }
241
+ break;
242
+ }
243
+ buffer += decoder.decode(value, { stream: true });
244
+ // Process complete lines
245
+ let newlineIndex;
246
+ while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
247
+ const line = buffer.slice(0, newlineIndex);
248
+ buffer = buffer.slice(newlineIndex + 1);
249
+ const trimmed = line.trim();
250
+ if (trimmed.length === 0)
251
+ continue;
252
+ const result = parseLine(trimmed);
253
+ if (result.success) {
254
+ yield result.data;
255
+ }
256
+ }
257
+ }
258
+ }
259
+ finally {
260
+ reader.releaseLock();
261
+ }
262
+ }
263
+ //# sourceMappingURL=ndjson.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ndjson.js","sourceRoot":"","sources":["../../src/ndjson.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAkBH,wCAEC;AAKD,0CAEC;AAOD,8BA+BC;AAMD,gCA4BC;AAmGD,0DAkCC;AAKD,kEAMC;AAKD,8CA2CC;AAjSD,6CAM2B;AAO3B;;GAEG;AACH,SAAgB,cAAc,CAAC,KAAkC;IAC/D,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED;;GAEG;AACH,SAAgB,eAAe,CAAC,MAAqC;IACnE,OAAO,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC/C,CAAC;AAED;;;;GAIG;AACH,SAAgB,SAAS,CAAC,IAAY;IACpC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAE5B,mBAAmB;IACnB,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;IACvD,CAAC;IAED,aAAa;IACb,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,qBAAqB,GA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AM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC;gBAC3C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;gBAExC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;gBAC5B,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;gBAEnC,MAAM,MAAM,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;gBAClC,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;oBACnB,MAAM,MAAM,CAAC,IAAI,CAAC;gBACpB,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["/**\n * @enclave-vm/stream - NDJSON Parser/Serializer\n *\n * Newline-delimited JSON (NDJSON) parsing and serialization for streaming events.\n * NDJSON format: one JSON object per line, separated by newlines.\n */\n\nimport {\n parseStreamEventOrEncrypted,\n type StreamEvent,\n type MaybeEncrypted,\n type ParsedStreamEvent,\n type ParsedEncryptedEnvelope,\n} from '@enclave-vm/types';\n\n/**\n * Result of parsing an NDJSON line.\n */\nexport type ParseResult<T> = { success: true; data: T } | { success: false; error: string; line: string };\n\n/**\n * Serialize an event to NDJSON format (single line).\n */\nexport function serializeEvent(event: MaybeEncrypted<StreamEvent>): string {\n return JSON.stringify(event);\n}\n\n/**\n * Serialize multiple events to NDJSON format.\n */\nexport function serializeEvents(events: MaybeEncrypted<StreamEvent>[]): string {\n return events.map(serializeEvent).join('\\n');\n}\n\n/**\n * Parse a single NDJSON line into an event.\n * Note: The returned type is from Zod parsing, which may have slightly different\n * type inference than the interface types (e.g., string vs template literal).\n */\nexport function parseLine(line: string): ParseResult<ParsedStreamEvent | ParsedEncryptedEnvelope> {\n const trimmed = line.trim();\n\n // Skip empty lines\n if (trimmed.length === 0) {\n return { success: false, error: 'Empty line', line };\n }\n\n // Parse JSON\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch (err) {\n return {\n success: false,\n error: `JSON parse error: ${err instanceof Error ? err.message : String(err)}`,\n line,\n };\n }\n\n // Validate against schema\n const result = parseStreamEventOrEncrypted(parsed);\n if (!result.success) {\n return {\n success: false,\n error: `Validation error: ${result.error.message}`,\n line,\n };\n }\n\n return { success: true, data: result.data };\n}\n\n/**\n * Parse multiple NDJSON lines into events.\n * Returns successfully parsed events and any errors encountered.\n */\nexport function parseLines(data: string): {\n events: (ParsedStreamEvent | ParsedEncryptedEnvelope)[];\n errors: Array<{ line: number; error: string; content: string }>;\n} {\n const lines = data.split('\\n');\n const events: (ParsedStreamEvent | ParsedEncryptedEnvelope)[] = [];\n const errors: Array<{ line: number; error: string; content: string }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (!line) continue;\n\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n\n const result = parseLine(trimmed);\n if (result.success) {\n events.push(result.data);\n } else {\n errors.push({\n line: i + 1,\n error: result.error,\n content: trimmed.length > 100 ? trimmed.slice(0, 100) + '...' : trimmed,\n });\n }\n }\n\n return { events, errors };\n}\n\n/**\n * NDJSON stream parser for incremental parsing.\n * Handles partial lines across chunks.\n */\nexport class NdjsonStreamParser {\n private buffer = '';\n private readonly onEvent: (event: ParsedStreamEvent | ParsedEncryptedEnvelope) => void;\n private readonly onError: (error: { line: number; error: string; content: string }) => void;\n private lineNumber = 0;\n\n constructor(options: {\n onEvent: (event: ParsedStreamEvent | ParsedEncryptedEnvelope) => void;\n onError: (error: { line: number; error: string; content: string }) => void;\n }) {\n this.onEvent = options.onEvent;\n this.onError = options.onError;\n }\n\n /**\n * Feed a chunk of data into the parser.\n * Complete lines are parsed and emitted immediately.\n */\n feed(chunk: string): void {\n this.buffer += chunk;\n\n // Process complete lines\n let newlineIndex: number;\n while ((newlineIndex = this.buffer.indexOf('\\n')) !== -1) {\n const line = this.buffer.slice(0, newlineIndex);\n this.buffer = this.buffer.slice(newlineIndex + 1);\n this.lineNumber++;\n\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n\n const result = parseLine(trimmed);\n if (result.success) {\n this.onEvent(result.data);\n } else {\n this.onError({\n line: this.lineNumber,\n error: result.error,\n content: trimmed.length > 100 ? trimmed.slice(0, 100) + '...' : trimmed,\n });\n }\n }\n }\n\n /**\n * Flush any remaining buffered data.\n * Should be called when the stream ends.\n */\n flush(): void {\n const trimmed = this.buffer.trim();\n if (trimmed.length > 0) {\n this.lineNumber++;\n const result = parseLine(trimmed);\n if (result.success) {\n this.onEvent(result.data);\n } else {\n this.onError({\n line: this.lineNumber,\n error: result.error,\n content: trimmed.length > 100 ? trimmed.slice(0, 100) + '...' : trimmed,\n });\n }\n }\n this.buffer = '';\n }\n\n /**\n * Reset the parser state.\n */\n reset(): void {\n this.buffer = '';\n this.lineNumber = 0;\n }\n\n /**\n * Get the current line number.\n */\n getLineNumber(): number {\n return this.lineNumber;\n }\n\n /**\n * Check if there's pending data in the buffer.\n */\n hasPendingData(): boolean {\n return this.buffer.trim().length > 0;\n }\n}\n\n/**\n * Create a transform stream that parses NDJSON.\n * Works with browser fetch() streaming and Node.js streams.\n */\nexport function createNdjsonParseStream(): TransformStream<string, ParsedStreamEvent | ParsedEncryptedEnvelope> {\n let buffer = '';\n\n return new TransformStream({\n transform(chunk, controller) {\n buffer += chunk;\n\n let newlineIndex: number;\n while ((newlineIndex = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newlineIndex);\n buffer = buffer.slice(newlineIndex + 1);\n\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n\n const result = parseLine(trimmed);\n if (result.success) {\n controller.enqueue(result.data);\n }\n // Note: errors are silently dropped in transform stream\n // Use NdjsonStreamParser for error handling\n }\n },\n\n flush(controller) {\n const trimmed = buffer.trim();\n if (trimmed.length > 0) {\n const result = parseLine(trimmed);\n if (result.success) {\n controller.enqueue(result.data);\n }\n }\n },\n });\n}\n\n/**\n * Create a transform stream that serializes events to NDJSON.\n */\nexport function createNdjsonSerializeStream(): TransformStream<MaybeEncrypted<StreamEvent>, string> {\n return new TransformStream({\n transform(event, controller) {\n controller.enqueue(serializeEvent(event) + '\\n');\n },\n });\n}\n\n/**\n * Async generator that parses NDJSON from a ReadableStream.\n */\nexport async function* parseNdjsonStream(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<ParsedStreamEvent | ParsedEncryptedEnvelope> {\n const decoder = new TextDecoder();\n const reader = stream.getReader();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n // Process any remaining data\n const trimmed = buffer.trim();\n if (trimmed.length > 0) {\n const result = parseLine(trimmed);\n if (result.success) {\n yield result.data;\n }\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n // Process complete lines\n let newlineIndex: number;\n while ((newlineIndex = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newlineIndex);\n buffer = buffer.slice(newlineIndex + 1);\n\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n\n const result = parseLine(trimmed);\n if (result.success) {\n yield result.data;\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n"]}
@@ -0,0 +1,242 @@
1
+ /**
2
+ * @enclave-vm/stream - Reconnection State Machine
3
+ *
4
+ * Handles connection drops and automatic reconnection with exponential backoff.
5
+ */
6
+ import type { StreamEvent, EncryptedEnvelope } from '@enclave-vm/types';
7
+ /**
8
+ * Connection state.
9
+ */
10
+ export declare const ConnectionState: {
11
+ /** Not connected */
12
+ readonly Disconnected: "disconnected";
13
+ /** Attempting to connect */
14
+ readonly Connecting: "connecting";
15
+ /** Successfully connected */
16
+ readonly Connected: "connected";
17
+ /** Connection lost, will attempt reconnection */
18
+ readonly Reconnecting: "reconnecting";
19
+ /** Permanently failed (max retries exceeded or fatal error) */
20
+ readonly Failed: "failed";
21
+ /** Intentionally closed */
22
+ readonly Closed: "closed";
23
+ };
24
+ export type ConnectionState = (typeof ConnectionState)[keyof typeof ConnectionState];
25
+ /**
26
+ * Reconnection configuration.
27
+ */
28
+ export interface ReconnectionConfig {
29
+ /** Maximum number of reconnection attempts (default: 5) */
30
+ maxRetries: number;
31
+ /** Initial backoff delay in milliseconds (default: 1000) */
32
+ initialDelayMs: number;
33
+ /** Maximum backoff delay in milliseconds (default: 30000) */
34
+ maxDelayMs: number;
35
+ /** Backoff multiplier (default: 2) */
36
+ backoffMultiplier: number;
37
+ /** Add random jitter to backoff (default: true) */
38
+ jitter: boolean;
39
+ /** Jitter factor (0-1, default: 0.3) */
40
+ jitterFactor: number;
41
+ }
42
+ /**
43
+ * Default reconnection configuration.
44
+ */
45
+ export declare const DEFAULT_RECONNECTION_CONFIG: ReconnectionConfig;
46
+ /**
47
+ * Event emitted by the reconnection state machine.
48
+ */
49
+ export type ReconnectionEvent = {
50
+ type: 'state_change';
51
+ state: ConnectionState;
52
+ previousState: ConnectionState;
53
+ } | {
54
+ type: 'retry_scheduled';
55
+ attempt: number;
56
+ delayMs: number;
57
+ } | {
58
+ type: 'retry_started';
59
+ attempt: number;
60
+ } | {
61
+ type: 'connected';
62
+ } | {
63
+ type: 'disconnected';
64
+ reason?: string;
65
+ } | {
66
+ type: 'failed';
67
+ reason: string;
68
+ };
69
+ /**
70
+ * Reconnection state machine.
71
+ * Manages connection state and handles automatic reconnection.
72
+ */
73
+ export declare class ReconnectionStateMachine {
74
+ private state;
75
+ private retryCount;
76
+ private retryTimeoutId;
77
+ private readonly config;
78
+ private readonly onEvent;
79
+ constructor(options: {
80
+ config?: Partial<ReconnectionConfig>;
81
+ onEvent: (event: ReconnectionEvent) => void;
82
+ });
83
+ /**
84
+ * Get current connection state.
85
+ */
86
+ getState(): ConnectionState;
87
+ /**
88
+ * Get current retry count.
89
+ */
90
+ getRetryCount(): number;
91
+ /**
92
+ * Transition to a new state.
93
+ */
94
+ private transition;
95
+ /**
96
+ * Calculate backoff delay with optional jitter.
97
+ */
98
+ private calculateBackoff;
99
+ /**
100
+ * Start connecting.
101
+ */
102
+ connect(): void;
103
+ /**
104
+ * Called when connection succeeds.
105
+ */
106
+ onConnected(): void;
107
+ /**
108
+ * Called when connection is lost.
109
+ */
110
+ onDisconnected(reason?: string): void;
111
+ /**
112
+ * Called when connection fails with a fatal error.
113
+ */
114
+ onFatalError(reason: string): void;
115
+ /**
116
+ * Schedule a reconnection attempt.
117
+ */
118
+ private scheduleRetry;
119
+ /**
120
+ * Cancel any pending retry.
121
+ */
122
+ private cancelRetry;
123
+ /**
124
+ * Intentionally close the connection.
125
+ */
126
+ close(): void;
127
+ /**
128
+ * Reset to initial state.
129
+ */
130
+ reset(): void;
131
+ /**
132
+ * Check if reconnection is possible.
133
+ */
134
+ canReconnect(): boolean;
135
+ }
136
+ /**
137
+ * Sequence tracker for detecting gaps and enabling replay.
138
+ */
139
+ export declare class SequenceTracker {
140
+ private lastSeq;
141
+ private readonly gaps;
142
+ private readonly maxGaps;
143
+ constructor(maxGaps?: number);
144
+ /**
145
+ * Process a received sequence number.
146
+ * Returns any gaps detected.
147
+ */
148
+ receive(seq: number): {
149
+ gap: boolean;
150
+ missingStart?: number;
151
+ missingEnd?: number;
152
+ };
153
+ /**
154
+ * Get the last received sequence number.
155
+ */
156
+ getLastSeq(): number;
157
+ /**
158
+ * Get all detected gaps.
159
+ */
160
+ getGaps(): Array<{
161
+ start: number;
162
+ end: number;
163
+ }>;
164
+ /**
165
+ * Clear a gap after it's been filled.
166
+ */
167
+ clearGap(start: number, end: number): void;
168
+ /**
169
+ * Check if there are pending gaps.
170
+ */
171
+ hasGaps(): boolean;
172
+ /**
173
+ * Reset the tracker.
174
+ */
175
+ reset(): void;
176
+ }
177
+ /**
178
+ * Event buffer for storing events during reconnection.
179
+ */
180
+ export declare class EventBuffer {
181
+ private readonly buffer;
182
+ private readonly maxSize;
183
+ constructor(maxSize?: number);
184
+ /**
185
+ * Add an event to the buffer.
186
+ */
187
+ add(event: StreamEvent | EncryptedEnvelope): boolean;
188
+ /**
189
+ * Get all buffered events.
190
+ */
191
+ getAll(): (StreamEvent | EncryptedEnvelope)[];
192
+ /**
193
+ * Drain the buffer (get all events and clear).
194
+ */
195
+ drain(): (StreamEvent | EncryptedEnvelope)[];
196
+ /**
197
+ * Get buffer size.
198
+ */
199
+ size(): number;
200
+ /**
201
+ * Check if buffer is full.
202
+ */
203
+ isFull(): boolean;
204
+ /**
205
+ * Clear the buffer.
206
+ */
207
+ clear(): void;
208
+ }
209
+ /**
210
+ * Heartbeat monitor for detecting stale connections.
211
+ */
212
+ export declare class HeartbeatMonitor {
213
+ private lastHeartbeat;
214
+ private timeoutId;
215
+ private readonly timeoutMs;
216
+ private readonly onTimeout;
217
+ constructor(options: {
218
+ timeoutMs: number;
219
+ onTimeout: () => void;
220
+ });
221
+ /**
222
+ * Start monitoring.
223
+ */
224
+ start(): void;
225
+ /**
226
+ * Stop monitoring.
227
+ */
228
+ stop(): void;
229
+ /**
230
+ * Reset the heartbeat timer.
231
+ */
232
+ reset(): void;
233
+ /**
234
+ * Called when a heartbeat is received.
235
+ */
236
+ onHeartbeat(): void;
237
+ /**
238
+ * Get time since last heartbeat in milliseconds.
239
+ */
240
+ getTimeSinceLastHeartbeat(): number;
241
+ private scheduleCheck;
242
+ }