@neta-art/cohub 12.0.0 → 12.1.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.
Files changed (37) hide show
  1. package/dist/board/export/index.js +1 -1
  2. package/dist/board/export/node/index.d.ts +1 -0
  3. package/dist/board/export/node/index.js +5 -0
  4. package/dist/board/export/scene.js +2 -1
  5. package/dist/board/render/card-tag.d.ts +0 -1
  6. package/dist/board/render/card-tag.js +15 -17
  7. package/dist/board/render/index.d.ts +2 -2
  8. package/dist/board/render/index.js +6 -6
  9. package/dist/board/render/renderers/arrow-card-renderer.js +5 -7
  10. package/dist/board/render/renderers/audio-card-renderer.js +8 -7
  11. package/dist/board/render/renderers/base-card-renderer.d.ts +1 -1
  12. package/dist/board/render/renderers/base-card-renderer.js +2 -3
  13. package/dist/board/render/renderers/board-renderer-registry.d.ts +3 -1
  14. package/dist/board/render/renderers/custom-card-renderer.js +19 -17
  15. package/dist/board/render/renderers/file-card-renderer.js +10 -8
  16. package/dist/board/render/renderers/frame-card-renderer.js +5 -6
  17. package/dist/board/render/renderers/shape-card-renderer.js +5 -7
  18. package/dist/board/render/renderers/task-card-renderer.js +9 -9
  19. package/dist/board/render/renderers/text-card-renderer.js +5 -7
  20. package/dist/board/render/renderers/unknown-card-renderer.js +5 -7
  21. package/dist/board/render/text-resolution.d.ts +4 -7
  22. package/dist/board/render/text-resolution.js +20 -22
  23. package/dist/board/stage/canvas-size.d.ts +18 -0
  24. package/dist/board/stage/canvas-size.js +31 -0
  25. package/dist/board/stage/scene.d.ts +5 -1
  26. package/dist/board/stage/scene.js +35 -9
  27. package/dist/board/stage/stage.js +34 -13
  28. package/dist/board/stage/text-resolution-tracker.d.ts +8 -0
  29. package/dist/board/stage/text-resolution-tracker.js +33 -0
  30. package/dist/chunks/app-realtime.js +1 -1
  31. package/dist/chunks/{transport.js → http-error.js} +37 -1
  32. package/dist/chunks/http.js +30 -10
  33. package/dist/http.js +1 -1
  34. package/dist/index.js +2 -2
  35. package/dist/websocket.js +951 -1
  36. package/package.json +1 -1
  37. package/dist/chunks/websocket.js +0 -988
package/dist/websocket.js CHANGED
@@ -1,2 +1,952 @@
1
- import { n as createWebsocketClient, t as WebsocketClient } from "./chunks/websocket.js";
1
+ import { C as getSessionTurnPatchStreamKey, S as getRealtimeSpaceRoom, T as normalizeRealtimeRooms, _ as WS_REALTIME_ROOM_CAPABILITY, b as WS_ROOM_SUBSCRIPTION_CAPABILITY, g as WS_COMPACT_STREAM_CAPABILITY, h as WS_BOARD_AWARENESS_CAPABILITY, r as extractBillingPayload, v as WS_REALTIME_ROOM_HISTORY_CAPABILITY, w as isRealtimeDomain } from "./chunks/http-error.js";
2
+ import { f as resolveWebsocketUrl } from "./chunks/environment.js";
3
+ //#region src/websocket.ts
4
+ const createEventMap = () => ({
5
+ connecting: /* @__PURE__ */ new Set(),
6
+ reconnecting: /* @__PURE__ */ new Set(),
7
+ open: /* @__PURE__ */ new Set(),
8
+ close: /* @__PURE__ */ new Set(),
9
+ error: /* @__PURE__ */ new Set(),
10
+ event: /* @__PURE__ */ new Set(),
11
+ ready: /* @__PURE__ */ new Set(),
12
+ auth: /* @__PURE__ */ new Set(),
13
+ messageAccepted: /* @__PURE__ */ new Set(),
14
+ serverError: /* @__PURE__ */ new Set(),
15
+ subscribed: /* @__PURE__ */ new Set(),
16
+ subscribeError: /* @__PURE__ */ new Set(),
17
+ pong: /* @__PURE__ */ new Set()
18
+ });
19
+ const toWebSocketUrl = (input, env) => resolveWebsocketUrl({
20
+ url: input,
21
+ env
22
+ });
23
+ const normalizeOptions = (options = {}) => ({
24
+ url: toWebSocketUrl(options.url, options.env),
25
+ autoReconnect: options.autoReconnect !== false,
26
+ reconnectBaseDelayMs: options.reconnectBaseDelayMs ?? 1e3,
27
+ reconnectMaxDelayMs: options.reconnectMaxDelayMs ?? 15e3,
28
+ connectTimeoutMs: normalizeConnectTimeoutMs(options.connectTimeoutMs ?? 15e3),
29
+ pingIntervalMs: options.pingIntervalMs ?? 2e4,
30
+ pongTimeoutMs: options.pongTimeoutMs ?? 15e3,
31
+ debug: options.debug === true
32
+ });
33
+ const formatCloseMessage = (code, reason) => `WebSocket closed: ${code ?? 0} ${reason || ""}`.trim();
34
+ const normalizeConnectTimeoutMs = (value) => {
35
+ if (!Number.isInteger(value) || value < 1 || value > 2147483647) throw new Error("connectTimeoutMs must be an integer between 1 and 2147483647");
36
+ return value;
37
+ };
38
+ const AUTH_CLOSE_CODE = 4003;
39
+ const AUTH_CLOSE_REASON = "authentication failed";
40
+ const isRetryableCloseCode = (code) => {
41
+ if (code === 1e3) return false;
42
+ if (code === AUTH_CLOSE_CODE) return false;
43
+ return true;
44
+ };
45
+ const PATCH_STREAM_BUFFER_MAX_PENDING = 128;
46
+ const isRecord = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
47
+ const isRealtimeCompactFrame = (value) => {
48
+ if (!isRecord(value)) return false;
49
+ if (value.t !== "d" && value.t !== "p") return false;
50
+ if (typeof value.sid !== "string" || !value.sid) return false;
51
+ if (typeof value.s !== "number" || !Number.isInteger(value.s) || value.s < 0) return false;
52
+ if (typeof value.b !== "number" || !Number.isInteger(value.b) || value.b < 0) return false;
53
+ if (value.t === "d") return "v" in value;
54
+ return (value.o === "append" || value.o === "replace" || value.o === "add" || value.o === "merge" || value.o === "remove") && typeof value.p === "string" && value.p.length > 0;
55
+ };
56
+ const isRealtimeEnvelope = (value) => {
57
+ if (!isRecord(value)) return false;
58
+ if (typeof value.id !== "string") return false;
59
+ if (typeof value.timestamp !== "number") return false;
60
+ if (!isRealtimeDomain(value.domain)) return false;
61
+ if (typeof value.type !== "string") return false;
62
+ if (!isRecord(value.payload)) return false;
63
+ return true;
64
+ };
65
+ const compactFrameToPatchOperation = (frame) => {
66
+ if (frame.t === "d") return { v: frame.v };
67
+ if (frame.o === "remove") return {
68
+ o: "remove",
69
+ p: frame.p
70
+ };
71
+ if (frame.o === "merge") return isRecord(frame.v) ? {
72
+ o: "merge",
73
+ p: frame.p,
74
+ v: frame.v
75
+ } : null;
76
+ if (!("v" in frame)) return null;
77
+ switch (frame.o) {
78
+ case "append": return {
79
+ o: "append",
80
+ p: frame.p,
81
+ v: frame.v
82
+ };
83
+ case "replace": return {
84
+ o: "replace",
85
+ p: frame.p,
86
+ v: frame.v
87
+ };
88
+ case "add": return {
89
+ o: "add",
90
+ p: frame.p,
91
+ v: frame.v
92
+ };
93
+ default: return null;
94
+ }
95
+ };
96
+ var WebsocketAuthError = class extends Error {
97
+ constructor(message) {
98
+ super(message);
99
+ this.name = "WebsocketAuthError";
100
+ }
101
+ };
102
+ var WebsocketClient = class {
103
+ url;
104
+ autoReconnect;
105
+ reconnectBaseDelayMs;
106
+ reconnectMaxDelayMs;
107
+ connectTimeoutMs;
108
+ pingIntervalMs;
109
+ pongTimeoutMs;
110
+ debug;
111
+ getAccessToken;
112
+ WebSocketImpl;
113
+ ws = null;
114
+ pingTimer = null;
115
+ reconnectTimer = null;
116
+ reconnectTimerResolver = null;
117
+ reconnectAttempt = 0;
118
+ authReconnectAttempted = false;
119
+ forceRefreshOnNextAuth = false;
120
+ retryAuthClose = false;
121
+ manuallyClosed = false;
122
+ connectPromise = null;
123
+ pendingConnectReject = null;
124
+ authWaiter = null;
125
+ awaitingPong = false;
126
+ lastPingRequestId = null;
127
+ pongDeadlineAt = 0;
128
+ compactStreamContexts = /* @__PURE__ */ new Map();
129
+ patchStreamBuffers = /* @__PURE__ */ new Map();
130
+ roomSubscriptions = /* @__PURE__ */ new Map();
131
+ serverCapabilities = /* @__PURE__ */ new Set();
132
+ state = "idle";
133
+ connectionId = null;
134
+ supportsCapability(capability) {
135
+ return this.serverCapabilities.has(capability);
136
+ }
137
+ listeners = createEventMap();
138
+ constructor(options = {}) {
139
+ const normalized = normalizeOptions(options);
140
+ this.url = normalized.url;
141
+ this.autoReconnect = normalized.autoReconnect;
142
+ this.reconnectBaseDelayMs = normalized.reconnectBaseDelayMs;
143
+ this.reconnectMaxDelayMs = normalized.reconnectMaxDelayMs;
144
+ this.connectTimeoutMs = normalized.connectTimeoutMs;
145
+ this.pingIntervalMs = normalized.pingIntervalMs;
146
+ this.pongTimeoutMs = normalized.pongTimeoutMs;
147
+ this.debug = normalized.debug;
148
+ this.getAccessToken = options.getAccessToken;
149
+ this.WebSocketImpl = options.WebSocketImpl ?? WebSocket;
150
+ }
151
+ on(type, handler) {
152
+ this.listeners[type].add(handler);
153
+ return () => this.off(type, handler);
154
+ }
155
+ off(type, handler) {
156
+ this.listeners[type].delete(handler);
157
+ }
158
+ emit(type, payload) {
159
+ for (const handler of this.listeners[type]) handler(payload);
160
+ }
161
+ log(...args) {
162
+ if (this.debug) console.log("[WebsocketClient]", ...args);
163
+ }
164
+ async connect() {
165
+ if (this.connectPromise) return this.connectPromise;
166
+ if (this.state === "open" && this.ws?.readyState === WebSocket.OPEN) return;
167
+ const isReconnect = this.reconnectAttempt > 0 || this.state === "reconnecting";
168
+ this.manuallyClosed = false;
169
+ this.clearReconnectTimer();
170
+ this.state = isReconnect ? "reconnecting" : "connecting";
171
+ this.emit("connecting", {
172
+ isReconnect,
173
+ attempt: this.reconnectAttempt
174
+ });
175
+ this.connectPromise = new Promise((resolve, reject) => {
176
+ const ws = new this.WebSocketImpl(this.url);
177
+ this.ws = ws;
178
+ let settled = false;
179
+ let closed = false;
180
+ let connectTimer = null;
181
+ const clearConnectTimer = () => {
182
+ if (connectTimer === null) return;
183
+ clearTimeout(connectTimer);
184
+ connectTimer = null;
185
+ };
186
+ const rejectOnce = (error) => {
187
+ if (settled) return;
188
+ clearConnectTimer();
189
+ settled = true;
190
+ this.connectPromise = null;
191
+ if (this.pendingConnectReject === rejectOnce) this.pendingConnectReject = null;
192
+ reject(error);
193
+ };
194
+ const resolveOnce = () => {
195
+ if (settled) return;
196
+ clearConnectTimer();
197
+ settled = true;
198
+ this.connectPromise = null;
199
+ if (this.pendingConnectReject === rejectOnce) this.pendingConnectReject = null;
200
+ resolve();
201
+ };
202
+ const isCurrentConnection = () => this.ws === ws && !closed;
203
+ const cleanupSocket = () => {
204
+ ws.onopen = null;
205
+ ws.onmessage = null;
206
+ ws.onerror = null;
207
+ ws.onclose = null;
208
+ };
209
+ const handleClose = (event) => {
210
+ if (closed || this.ws !== ws) return;
211
+ closed = true;
212
+ clearConnectTimer();
213
+ this.stopPingLoop();
214
+ const wasConnecting = this.state === "connecting" || this.state === "reconnecting";
215
+ this.state = "closed";
216
+ this.ws = null;
217
+ this.compactStreamContexts.clear();
218
+ this.patchStreamBuffers.clear();
219
+ this.resetRoomSubscriptions();
220
+ const closeError = new Error(formatCloseMessage(event.code, event.reason));
221
+ this.rejectAuthWaiter(closeError);
222
+ const retryAuthClose = event.code === AUTH_CLOSE_CODE && this.retryAuthClose;
223
+ this.retryAuthClose = false;
224
+ const willReconnect = !this.manuallyClosed && this.autoReconnect && (retryAuthClose || isRetryableCloseCode(event.code));
225
+ this.log("closed", {
226
+ code: event.code,
227
+ reason: event.reason,
228
+ willReconnect,
229
+ wasConnecting
230
+ });
231
+ this.emit("close", {
232
+ code: event.code,
233
+ reason: event.reason,
234
+ willReconnect
235
+ });
236
+ cleanupSocket();
237
+ if (wasConnecting) rejectOnce(closeError);
238
+ if (willReconnect) this.scheduleReconnect(event.code, event.reason);
239
+ };
240
+ ws.onopen = async () => {
241
+ if (!isCurrentConnection()) return;
242
+ clearConnectTimer();
243
+ try {
244
+ this.log("connected", {
245
+ url: this.url,
246
+ isReconnect,
247
+ attempt: this.reconnectAttempt
248
+ });
249
+ this.startPingLoop();
250
+ await this.authenticate();
251
+ if (!isCurrentConnection()) return;
252
+ this.state = "open";
253
+ this.restoreRoomSubscriptions();
254
+ this.reconnectAttempt = 0;
255
+ this.emit("open", { connectionId: this.connectionId });
256
+ resolveOnce();
257
+ } catch (error) {
258
+ if (!isCurrentConnection()) return;
259
+ const authError = error instanceof Error ? error : /* @__PURE__ */ new Error("authentication failed");
260
+ const recoverable = Boolean(this.getAccessToken && this.autoReconnect && !this.manuallyClosed && !this.authReconnectAttempted);
261
+ this.retryAuthClose = recoverable;
262
+ if (recoverable) {
263
+ this.authReconnectAttempted = true;
264
+ this.forceRefreshOnNextAuth = true;
265
+ }
266
+ this.emit("error", {
267
+ error: authError,
268
+ recoverable
269
+ });
270
+ rejectOnce(authError);
271
+ ws.close(AUTH_CLOSE_CODE, AUTH_CLOSE_REASON);
272
+ }
273
+ };
274
+ ws.onmessage = (event) => {
275
+ if (!isCurrentConnection()) return;
276
+ this.handleMessage(event.data);
277
+ };
278
+ ws.onerror = (error) => {
279
+ if (!isCurrentConnection()) return;
280
+ this.emit("error", {
281
+ error,
282
+ recoverable: !this.manuallyClosed
283
+ });
284
+ };
285
+ ws.onclose = (event) => {
286
+ handleClose(event);
287
+ };
288
+ this.pendingConnectReject = rejectOnce;
289
+ connectTimer = setTimeout(() => {
290
+ if (!isCurrentConnection() || settled) return;
291
+ const reason = "connect timeout";
292
+ const error = /* @__PURE__ */ new Error(`WebSocket ${reason} after ${this.connectTimeoutMs}ms`);
293
+ this.emit("error", {
294
+ error,
295
+ recoverable: !this.manuallyClosed && this.autoReconnect
296
+ });
297
+ try {
298
+ ws.close(4002, reason);
299
+ } finally {
300
+ handleClose({
301
+ code: 4002,
302
+ reason
303
+ });
304
+ }
305
+ }, this.connectTimeoutMs);
306
+ });
307
+ return this.connectPromise;
308
+ }
309
+ async disconnect(code = 1e3, reason = "manual") {
310
+ this.manuallyClosed = true;
311
+ this.clearReconnectTimer();
312
+ this.stopPingLoop();
313
+ this.state = "closed";
314
+ this.rejectAuthWaiter(/* @__PURE__ */ new Error("disconnected"));
315
+ const ws = this.ws;
316
+ this.ws = null;
317
+ ws?.close(code, reason);
318
+ this.pendingConnectReject?.(/* @__PURE__ */ new Error(`WebSocket disconnected: ${reason}`));
319
+ this.pendingConnectReject = null;
320
+ this.connectPromise = null;
321
+ if (ws) {
322
+ ws.onopen = null;
323
+ ws.onmessage = null;
324
+ ws.onerror = null;
325
+ ws.onclose = null;
326
+ this.emit("close", {
327
+ code,
328
+ reason,
329
+ willReconnect: false
330
+ });
331
+ }
332
+ this.authReconnectAttempted = false;
333
+ this.forceRefreshOnNextAuth = false;
334
+ this.retryAuthClose = false;
335
+ this.compactStreamContexts.clear();
336
+ this.patchStreamBuffers.clear();
337
+ this.resetRoomSubscriptions();
338
+ }
339
+ async updatePresence(input) {
340
+ await this.ensureOpen();
341
+ this.send({
342
+ type: "presence.update",
343
+ requestId: input.requestId,
344
+ payload: {
345
+ spaceId: input.spaceId,
346
+ meta: input.meta ?? null
347
+ }
348
+ });
349
+ }
350
+ async updateBoardAwareness(input) {
351
+ await this.ensureOpen();
352
+ this.send({
353
+ type: "board.awareness.update",
354
+ requestId: input.requestId,
355
+ payload: {
356
+ spaceId: input.spaceId,
357
+ boardId: input.boardId,
358
+ seq: input.seq,
359
+ update: input.update
360
+ }
361
+ });
362
+ }
363
+ async joinRealtimeRoom(input) {
364
+ await this.ensureOpen();
365
+ this.send({
366
+ type: "realtime.room.join",
367
+ requestId: input.requestId,
368
+ payload: {
369
+ roomId: input.roomId,
370
+ ticket: input.ticket,
371
+ ...input.instanceId ? { instanceId: input.instanceId } : {},
372
+ ...input.after !== void 0 ? { after: input.after } : {}
373
+ }
374
+ });
375
+ }
376
+ async readRealtimeRoomHistory(input) {
377
+ await this.ensureOpen();
378
+ this.send({
379
+ type: "realtime.room.history",
380
+ requestId: input.requestId,
381
+ payload: {
382
+ roomId: input.roomId,
383
+ ...input.after !== void 0 ? { after: input.after } : {},
384
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
385
+ }
386
+ });
387
+ }
388
+ async publishRealtimeRoom(input) {
389
+ await this.ensureOpen();
390
+ this.send({
391
+ type: "realtime.room.publish",
392
+ requestId: input.requestId,
393
+ payload: {
394
+ roomId: input.roomId,
395
+ event: input.event,
396
+ data: input.data,
397
+ clientEventId: input.clientEventId
398
+ }
399
+ });
400
+ }
401
+ async detachRealtimeRoom(input) {
402
+ await this.ensureOpen();
403
+ this.send({
404
+ type: "realtime.room.detach",
405
+ requestId: input.requestId,
406
+ payload: { roomId: input.roomId }
407
+ });
408
+ }
409
+ async leaveRealtimeRoom(input) {
410
+ await this.ensureOpen();
411
+ this.send({
412
+ type: "realtime.room.leave",
413
+ requestId: input.requestId,
414
+ payload: { roomId: input.roomId }
415
+ });
416
+ }
417
+ async updateRealtimeRoomPresence(input) {
418
+ await this.ensureOpen();
419
+ this.send({
420
+ type: "realtime.room.presence.update",
421
+ requestId: input.requestId,
422
+ payload: {
423
+ roomId: input.roomId,
424
+ presence: input.presence
425
+ }
426
+ });
427
+ }
428
+ async sendMessage(input) {
429
+ await this.ensureOpen();
430
+ this.send({
431
+ type: "session.message.create",
432
+ requestId: input.requestId,
433
+ payload: {
434
+ spaceId: input.spaceId,
435
+ sessionId: input.sessionId,
436
+ content: input.content,
437
+ clientMessageId: input.clientMessageId,
438
+ model: input.model,
439
+ provider: input.provider,
440
+ thinkingLevel: input.thinkingLevel
441
+ }
442
+ });
443
+ }
444
+ retainRooms(rooms) {
445
+ const normalized = normalizeRealtimeRooms(rooms);
446
+ if (normalized.length === 0) return () => void 0;
447
+ for (const room of normalized) {
448
+ const state = this.roomSubscriptions.get(room) ?? {
449
+ refCount: 0,
450
+ subscribed: false,
451
+ pending: false
452
+ };
453
+ state.refCount += 1;
454
+ this.roomSubscriptions.set(room, state);
455
+ }
456
+ this.flushRoomSubscriptions();
457
+ if (this.state !== "open" && this.state !== "connecting" && this.state !== "reconnecting") this.connect().then(() => this.flushRoomSubscriptions()).catch((error) => this.emit("error", {
458
+ error,
459
+ recoverable: true
460
+ }));
461
+ let released = false;
462
+ return () => {
463
+ if (released) return;
464
+ released = true;
465
+ const roomsToRelease = [];
466
+ for (const room of normalized) {
467
+ const state = this.roomSubscriptions.get(room);
468
+ if (!state) continue;
469
+ state.refCount -= 1;
470
+ if (state.refCount > 0) {
471
+ this.roomSubscriptions.set(room, state);
472
+ continue;
473
+ }
474
+ this.roomSubscriptions.delete(room);
475
+ if (state.subscribed) roomsToRelease.push(room);
476
+ }
477
+ if (roomsToRelease.length === 0) return;
478
+ if (this.ws?.readyState === WebSocket.OPEN) this.send({
479
+ type: "unsubscribe",
480
+ payload: { rooms: roomsToRelease }
481
+ });
482
+ };
483
+ }
484
+ subscribeRooms(rooms) {
485
+ return this.retainRooms(rooms);
486
+ }
487
+ subscribeSpace(spaceId) {
488
+ return this.retainRooms([getRealtimeSpaceRoom(spaceId)]);
489
+ }
490
+ ack(eventId, requestId) {
491
+ this.send({
492
+ type: "ack",
493
+ requestId,
494
+ payload: eventId ? { eventId } : void 0
495
+ });
496
+ }
497
+ ping(requestId) {
498
+ const effectiveRequestId = requestId ?? `ping-${Date.now()}`;
499
+ this.awaitingPong = true;
500
+ this.lastPingRequestId = effectiveRequestId;
501
+ this.pongDeadlineAt = Date.now() + this.pongTimeoutMs;
502
+ this.send({
503
+ type: "ping",
504
+ requestId: effectiveRequestId,
505
+ payload: {}
506
+ });
507
+ }
508
+ async ensureOpen() {
509
+ if (this.state === "open" && this.ws?.readyState === WebSocket.OPEN) return;
510
+ await this.connect();
511
+ }
512
+ send(event) {
513
+ const ws = this.ws;
514
+ if (!ws || ws.readyState !== WebSocket.OPEN) throw new Error("websocket is not open");
515
+ ws.send(JSON.stringify(event));
516
+ }
517
+ async authenticate() {
518
+ const forceRefresh = this.forceRefreshOnNextAuth;
519
+ this.forceRefreshOnNextAuth = false;
520
+ const token = this.getAccessToken ? await this.getAccessToken(forceRefresh ? { forceRefresh: true } : void 0) : null;
521
+ if (!token) throw new WebsocketAuthError("missing access token");
522
+ const waiter = this.createAuthWaiter();
523
+ this.send({
524
+ type: "auth",
525
+ payload: {
526
+ token,
527
+ capabilities: [
528
+ WS_COMPACT_STREAM_CAPABILITY,
529
+ WS_ROOM_SUBSCRIPTION_CAPABILITY,
530
+ WS_BOARD_AWARENESS_CAPABILITY,
531
+ WS_REALTIME_ROOM_CAPABILITY,
532
+ WS_REALTIME_ROOM_HISTORY_CAPABILITY
533
+ ]
534
+ }
535
+ });
536
+ await waiter.promise;
537
+ this.authReconnectAttempted = false;
538
+ }
539
+ flushRoomSubscriptions() {
540
+ if (this.state !== "open" || this.ws?.readyState !== WebSocket.OPEN) return;
541
+ const rooms = [...this.roomSubscriptions.entries()].filter(([, state]) => state.refCount > 0 && !state.subscribed && !state.pending).map(([room]) => room);
542
+ if (rooms.length === 0) return;
543
+ this.send({
544
+ type: "subscribe",
545
+ payload: { rooms }
546
+ });
547
+ for (const room of rooms) {
548
+ const state = this.roomSubscriptions.get(room);
549
+ if (state) state.pending = true;
550
+ }
551
+ }
552
+ restoreRoomSubscriptions() {
553
+ this.resetRoomSubscriptions();
554
+ this.flushRoomSubscriptions();
555
+ }
556
+ resetRoomSubscriptions() {
557
+ for (const state of this.roomSubscriptions.values()) {
558
+ state.subscribed = false;
559
+ state.pending = false;
560
+ }
561
+ }
562
+ createAuthWaiter() {
563
+ this.rejectAuthWaiter(/* @__PURE__ */ new Error("superseded auth waiter"));
564
+ let resolve;
565
+ let reject;
566
+ const promise = new Promise((res, rej) => {
567
+ resolve = res;
568
+ reject = rej;
569
+ });
570
+ this.authWaiter = {
571
+ promise,
572
+ resolve,
573
+ reject
574
+ };
575
+ return this.authWaiter;
576
+ }
577
+ resolveAuthWaiter() {
578
+ if (!this.authWaiter) return;
579
+ this.authWaiter.resolve();
580
+ this.authWaiter = null;
581
+ }
582
+ rejectAuthWaiter(error) {
583
+ if (!this.authWaiter) return;
584
+ this.authWaiter.reject(error);
585
+ this.authWaiter = null;
586
+ }
587
+ handleMessage(raw) {
588
+ let parsed;
589
+ try {
590
+ parsed = typeof raw === "string" ? JSON.parse(raw) : JSON.parse(String(raw));
591
+ } catch {
592
+ this.emit("error", {
593
+ error: /* @__PURE__ */ new Error("invalid websocket payload"),
594
+ recoverable: true
595
+ });
596
+ return;
597
+ }
598
+ if (isRealtimeCompactFrame(parsed)) {
599
+ this.handleCompactFrame(parsed);
600
+ return;
601
+ }
602
+ if (!isRealtimeEnvelope(parsed)) {
603
+ this.emit("error", {
604
+ error: /* @__PURE__ */ new Error("invalid realtime envelope"),
605
+ recoverable: true
606
+ });
607
+ return;
608
+ }
609
+ const envelope = parsed;
610
+ this.rememberCompactStreamContext(envelope);
611
+ if (envelope.type === "session.turn.patch") {
612
+ this.handlePatchEnvelope(envelope);
613
+ return;
614
+ }
615
+ switch (envelope.type) {
616
+ case "system.ready": {
617
+ const connectionId = typeof envelope.payload.connectionId === "string" ? envelope.payload.connectionId : null;
618
+ if (connectionId) {
619
+ this.connectionId = connectionId;
620
+ this.emit("ready", { connectionId });
621
+ }
622
+ this.emit("event", envelope);
623
+ return;
624
+ }
625
+ case "system.auth.ok": {
626
+ const connectionId = typeof envelope.payload.connectionId === "string" ? envelope.payload.connectionId : this.connectionId;
627
+ const user = envelope.payload.user && typeof envelope.payload.user === "object" ? envelope.payload.user : {};
628
+ const capabilities = Array.isArray(envelope.payload.capabilities) ? envelope.payload.capabilities.filter((value) => typeof value === "string") : [];
629
+ this.serverCapabilities.clear();
630
+ for (const capability of capabilities) this.serverCapabilities.add(capability);
631
+ if (connectionId) {
632
+ this.connectionId = connectionId;
633
+ this.emit("auth", {
634
+ connectionId,
635
+ user,
636
+ capabilities
637
+ });
638
+ }
639
+ this.resolveAuthWaiter();
640
+ this.emit("event", envelope);
641
+ return;
642
+ }
643
+ case "system.request.error": {
644
+ const message = typeof envelope.payload.message === "string" ? envelope.payload.message : "request failed";
645
+ const code = typeof envelope.payload.code === "string" ? envelope.payload.code : void 0;
646
+ const error = new WebsocketAuthError(message);
647
+ this.rejectAuthWaiter(error);
648
+ this.emit("serverError", {
649
+ code,
650
+ message,
651
+ requestId: envelope.requestId ?? null,
652
+ sessionId: envelope.sessionId ?? null,
653
+ spaceId: envelope.spaceId ?? null
654
+ });
655
+ this.emit("event", envelope);
656
+ return;
657
+ }
658
+ case "session.request.accepted": {
659
+ const payload = envelope.payload;
660
+ this.emit("messageAccepted", {
661
+ requestId: envelope.requestId ?? null,
662
+ sessionId: envelope.sessionId ?? null,
663
+ spaceId: envelope.spaceId ?? null,
664
+ clientMessageId: typeof payload.clientMessageId === "string" ? payload.clientMessageId : null,
665
+ turnId: typeof payload.turnId === "string" ? payload.turnId : null,
666
+ userMessageId: typeof payload.userMessageId === "string" ? payload.userMessageId : null,
667
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null
668
+ });
669
+ this.emit("event", envelope);
670
+ return;
671
+ }
672
+ case "session.request.error": {
673
+ const payload = envelope.payload;
674
+ this.emit("serverError", {
675
+ code: typeof payload.code === "string" ? payload.code : void 0,
676
+ message: typeof payload.message === "string" ? payload.message : void 0,
677
+ requestId: envelope.requestId ?? null,
678
+ sessionId: envelope.sessionId ?? null,
679
+ spaceId: envelope.spaceId ?? null,
680
+ clientMessageId: typeof payload.clientMessageId === "string" ? payload.clientMessageId : null,
681
+ billing: extractBillingPayload(payload.billing)
682
+ });
683
+ this.emit("event", envelope);
684
+ return;
685
+ }
686
+ case "system.pong": {
687
+ const requestId = envelope.requestId ?? null;
688
+ if (!requestId || requestId === this.lastPingRequestId) {
689
+ this.awaitingPong = false;
690
+ this.lastPingRequestId = null;
691
+ this.pongDeadlineAt = 0;
692
+ }
693
+ this.emit("pong", { requestId });
694
+ return;
695
+ }
696
+ case "system.subscribe.ok": {
697
+ const payload = envelope.payload;
698
+ const rooms = normalizeRealtimeRooms(Array.isArray(payload.rooms) ? payload.rooms.filter((room) => typeof room === "string") : []);
699
+ for (const room of rooms) {
700
+ const state = this.roomSubscriptions.get(room);
701
+ if (state) {
702
+ state.subscribed = true;
703
+ state.pending = false;
704
+ }
705
+ }
706
+ this.emit("subscribed", {
707
+ rooms,
708
+ requestId: envelope.requestId ?? null
709
+ });
710
+ this.emit("event", envelope);
711
+ return;
712
+ }
713
+ case "system.subscribe.error": {
714
+ const payload = envelope.payload;
715
+ const rejected = Array.isArray(payload.rejected) ? payload.rejected.filter((entry) => Boolean(entry && typeof entry === "object")).map((entry) => ({
716
+ room: typeof entry.room === "string" ? entry.room : "",
717
+ code: typeof entry.code === "string" ? entry.code : "UNKNOWN",
718
+ message: typeof entry.message === "string" ? entry.message : "Subscription failed"
719
+ })).filter((entry) => entry.room) : [];
720
+ for (const item of rejected) {
721
+ const room = normalizeRealtimeRooms([item.room])[0];
722
+ if (!room) continue;
723
+ this.roomSubscriptions.delete(room);
724
+ }
725
+ this.emit("subscribeError", {
726
+ rejected,
727
+ requestId: envelope.requestId ?? null
728
+ });
729
+ this.emit("event", envelope);
730
+ return;
731
+ }
732
+ case "system.ack.ok": return;
733
+ default:
734
+ this.emit("event", envelope);
735
+ return;
736
+ }
737
+ }
738
+ rememberCompactStreamContext(envelope) {
739
+ if (envelope.type === "session.turn.patch") {
740
+ const payload = envelope.payload;
741
+ const turnId = typeof payload.turnId === "string" ? payload.turnId : null;
742
+ const messageId = typeof payload.messageId === "string" ? payload.messageId : null;
743
+ const realtimeMeta = payload._rt && typeof payload._rt === "object" ? payload._rt : null;
744
+ const sid = typeof realtimeMeta?.sid === "string" && realtimeMeta.sid.trim() ? realtimeMeta.sid : turnId ?? messageId;
745
+ if (!sid) return;
746
+ this.compactStreamContexts.set(sid, {
747
+ spaceId: envelope.spaceId ?? null,
748
+ sessionId: envelope.sessionId ?? null,
749
+ turnId,
750
+ messageId,
751
+ messageOrdinal: typeof payload.messageOrdinal === "number" ? payload.messageOrdinal : null,
752
+ anchorUserMessageId: typeof payload.anchorUserMessageId === "string" ? payload.anchorUserMessageId : null
753
+ });
754
+ return;
755
+ }
756
+ if (envelope.type !== "session.message.persisted") return;
757
+ const message = envelope.payload.message;
758
+ if (!message || typeof message !== "object") return;
759
+ const meta = message.meta;
760
+ const turnId = typeof meta?.turnId === "string" ? meta.turnId : null;
761
+ if (!turnId) return;
762
+ for (const [sid, context] of this.compactStreamContexts.entries()) if (context.turnId === turnId) {
763
+ this.compactStreamContexts.delete(sid);
764
+ this.patchStreamBuffers.delete(sid);
765
+ }
766
+ }
767
+ getPatchStreamBufferKey(envelope) {
768
+ if (envelope.type !== "session.turn.patch") return null;
769
+ const payload = envelope.payload;
770
+ const realtimeMeta = payload._rt && typeof payload._rt === "object" ? payload._rt : null;
771
+ if (typeof realtimeMeta?.sid === "string" && realtimeMeta.sid.trim()) return realtimeMeta.sid;
772
+ return getSessionTurnPatchStreamKey(payload, { includeSessionFallback: true });
773
+ }
774
+ handlePatchEnvelope(envelope) {
775
+ const payload = envelope.payload;
776
+ if (typeof payload.seq !== "number" || typeof payload.baseSeq !== "number" || !Number.isInteger(payload.seq) || !Number.isInteger(payload.baseSeq) || payload.seq < 0 || payload.baseSeq < 0) {
777
+ this.emit("event", envelope);
778
+ return;
779
+ }
780
+ const key = this.getPatchStreamBufferKey(envelope);
781
+ if (!key) {
782
+ this.emit("event", envelope);
783
+ return;
784
+ }
785
+ if (payload.baseSeq === 0) {
786
+ const buffer = {
787
+ nextSeq: payload.seq + 1,
788
+ pending: /* @__PURE__ */ new Map()
789
+ };
790
+ this.patchStreamBuffers.set(key, buffer);
791
+ this.emit("event", envelope);
792
+ this.flushPatchStreamBuffer(buffer);
793
+ return;
794
+ }
795
+ const buffer = this.patchStreamBuffers.get(key);
796
+ if (!buffer) {
797
+ const newBuffer = {
798
+ nextSeq: payload.baseSeq + 1,
799
+ pending: /* @__PURE__ */ new Map([[payload.seq, envelope]])
800
+ };
801
+ this.patchStreamBuffers.set(key, newBuffer);
802
+ this.flushPatchStreamBuffer(newBuffer);
803
+ return;
804
+ }
805
+ if (payload.seq < buffer.nextSeq) return;
806
+ buffer.pending.set(payload.seq, envelope);
807
+ if (!this.enforcePatchStreamBufferLimit(key, buffer)) return;
808
+ this.flushPatchStreamBuffer(buffer);
809
+ }
810
+ enforcePatchStreamBufferLimit(key, buffer) {
811
+ if (buffer.pending.size <= PATCH_STREAM_BUFFER_MAX_PENDING) return true;
812
+ this.patchStreamBuffers.delete(key);
813
+ this.emit("error", {
814
+ error: /* @__PURE__ */ new Error(`patch stream buffer overflow: ${key}`),
815
+ recoverable: true
816
+ });
817
+ return false;
818
+ }
819
+ flushPatchStreamBuffer(buffer) {
820
+ while (true) {
821
+ const envelope = buffer.pending.get(buffer.nextSeq);
822
+ if (!envelope) return;
823
+ const seq = envelope.payload.seq;
824
+ if (typeof seq !== "number" || !Number.isInteger(seq)) return;
825
+ buffer.pending.delete(buffer.nextSeq);
826
+ buffer.nextSeq = seq + 1;
827
+ this.emit("event", envelope);
828
+ }
829
+ }
830
+ handleCompactFrame(frame) {
831
+ const context = this.compactStreamContexts.get(frame.sid);
832
+ if (!context?.sessionId) {
833
+ this.emit("error", {
834
+ error: /* @__PURE__ */ new Error(`unknown compact stream: ${frame.sid}`),
835
+ recoverable: true
836
+ });
837
+ return;
838
+ }
839
+ const op = compactFrameToPatchOperation(frame);
840
+ if (!op) {
841
+ this.emit("error", {
842
+ error: /* @__PURE__ */ new Error(`invalid compact stream frame: ${frame.sid}`),
843
+ recoverable: true
844
+ });
845
+ return;
846
+ }
847
+ const envelope = {
848
+ id: `compact:${frame.sid}:${frame.s}`,
849
+ timestamp: Date.now(),
850
+ domain: "session",
851
+ type: "session.turn.patch",
852
+ spaceId: context.spaceId,
853
+ sessionId: context.sessionId,
854
+ payload: {
855
+ turnId: context.turnId,
856
+ messageId: context.messageId,
857
+ messageOrdinal: context.messageOrdinal,
858
+ sourceMessageId: context.messageId,
859
+ anchorUserMessageId: context.anchorUserMessageId,
860
+ seq: frame.s,
861
+ baseSeq: frame.b,
862
+ ops: [op],
863
+ _rt: { sid: frame.sid }
864
+ }
865
+ };
866
+ this.handlePatchEnvelope(envelope);
867
+ }
868
+ startPingLoop() {
869
+ this.stopPingLoop();
870
+ this.pingTimer = setInterval(() => {
871
+ if (this.ws?.readyState !== WebSocket.OPEN) return;
872
+ if (this.awaitingPong && this.pongDeadlineAt > 0 && Date.now() > this.pongDeadlineAt) {
873
+ this.emit("error", {
874
+ error: /* @__PURE__ */ new Error("websocket pong timeout"),
875
+ recoverable: true
876
+ });
877
+ this.ws.close(4002, "pong timeout");
878
+ return;
879
+ }
880
+ this.ping();
881
+ }, this.pingIntervalMs);
882
+ }
883
+ stopPingLoop() {
884
+ if (this.pingTimer) {
885
+ clearInterval(this.pingTimer);
886
+ this.pingTimer = null;
887
+ }
888
+ this.awaitingPong = false;
889
+ this.lastPingRequestId = null;
890
+ this.pongDeadlineAt = 0;
891
+ }
892
+ clearReconnectTimer() {
893
+ if (this.reconnectTimer) {
894
+ clearTimeout(this.reconnectTimer);
895
+ this.reconnectTimer = null;
896
+ }
897
+ if (this.reconnectTimerResolver) {
898
+ const resolve = this.reconnectTimerResolver;
899
+ this.reconnectTimerResolver = null;
900
+ resolve();
901
+ }
902
+ }
903
+ async scheduleReconnect(code, reason) {
904
+ this.clearReconnectTimer();
905
+ const attempt = this.reconnectAttempt + 1;
906
+ const delay = Math.min(this.reconnectBaseDelayMs * 2 ** this.reconnectAttempt, this.reconnectMaxDelayMs);
907
+ this.reconnectAttempt = attempt;
908
+ this.state = "reconnecting";
909
+ this.log("schedule reconnect", {
910
+ attempt,
911
+ delay,
912
+ code,
913
+ reason
914
+ });
915
+ this.emit("reconnecting", {
916
+ attempt,
917
+ delayMs: delay,
918
+ code,
919
+ reason
920
+ });
921
+ await new Promise((resolve) => {
922
+ this.reconnectTimerResolver = resolve;
923
+ this.reconnectTimer = setTimeout(() => {
924
+ this.reconnectTimer = null;
925
+ this.reconnectTimerResolver = null;
926
+ resolve();
927
+ }, delay);
928
+ });
929
+ if (this.manuallyClosed) return;
930
+ if (typeof navigator !== "undefined" && navigator.onLine === false) {
931
+ await new Promise((resolve) => {
932
+ const fallbackTimer = setTimeout(resolve, this.reconnectMaxDelayMs);
933
+ const handleOnline = () => {
934
+ clearTimeout(fallbackTimer);
935
+ globalThis.removeEventListener?.("online", handleOnline);
936
+ resolve();
937
+ };
938
+ globalThis.addEventListener?.("online", handleOnline, { once: true });
939
+ });
940
+ if (this.manuallyClosed) return;
941
+ }
942
+ await this.connect().catch((error) => {
943
+ this.emit("error", {
944
+ error,
945
+ recoverable: this.state === "reconnecting"
946
+ });
947
+ });
948
+ }
949
+ };
950
+ const createWebsocketClient = (options) => new WebsocketClient(options);
951
+ //#endregion
2
952
  export { WebsocketClient, createWebsocketClient };