@neta-art/cohub 1.33.0 → 1.33.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neta-art/cohub",
3
- "version": "1.33.0",
3
+ "version": "1.33.1",
4
4
  "description": "Cohub SDK for spaces, sessions, checkpoints, and realtime agent collaboration.",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -1,674 +0,0 @@
1
- import { c as resolveWebsocketUrl } from "./environment.js";
2
- //#region ../protocol/src/realtime/types.ts
3
- const WS_COMPACT_STREAM_CAPABILITY = "session.compact_stream.v1";
4
- const getNonEmptyString = (value) => typeof value === "string" && value.trim() ? value : null;
5
- const getSessionTurnPatchStreamKey = (input, options = {}) => {
6
- const turnId = getNonEmptyString(input.turnId);
7
- const messageKey = getNonEmptyString(input.messageId) ?? getNonEmptyString(input.sourceMessageId) ?? getNonEmptyString(input.anchorUserMessageId) ?? (typeof input.messageOrdinal === "number" && Number.isFinite(input.messageOrdinal) ? `ordinal:${input.messageOrdinal}` : null);
8
- if (turnId && messageKey) return `${turnId}:${messageKey}`;
9
- const streamKey = messageKey ?? turnId;
10
- if (streamKey) return streamKey;
11
- return options.includeSessionFallback ? getNonEmptyString(input.sessionId) : null;
12
- };
13
- //#endregion
14
- //#region src/websocket.ts
15
- const createEventMap = () => ({
16
- connecting: /* @__PURE__ */ new Set(),
17
- reconnecting: /* @__PURE__ */ new Set(),
18
- open: /* @__PURE__ */ new Set(),
19
- close: /* @__PURE__ */ new Set(),
20
- error: /* @__PURE__ */ new Set(),
21
- event: /* @__PURE__ */ new Set(),
22
- ready: /* @__PURE__ */ new Set(),
23
- auth: /* @__PURE__ */ new Set(),
24
- messageAccepted: /* @__PURE__ */ new Set(),
25
- serverError: /* @__PURE__ */ new Set(),
26
- pong: /* @__PURE__ */ new Set()
27
- });
28
- const toWebSocketUrl = (input, env) => resolveWebsocketUrl({
29
- url: input,
30
- env
31
- });
32
- const normalizeOptions = (options = {}) => ({
33
- url: toWebSocketUrl(options.url, options.env),
34
- autoReconnect: options.autoReconnect !== false,
35
- reconnectBaseDelayMs: options.reconnectBaseDelayMs ?? 1e3,
36
- reconnectMaxDelayMs: options.reconnectMaxDelayMs ?? 15e3,
37
- pingIntervalMs: options.pingIntervalMs ?? 2e4,
38
- pongTimeoutMs: options.pongTimeoutMs ?? 15e3,
39
- debug: options.debug === true
40
- });
41
- const formatCloseMessage = (code, reason) => `WebSocket closed: ${code ?? 0} ${reason || ""}`.trim();
42
- const isRetryableCloseCode = (code) => {
43
- if (code === 1e3) return false;
44
- if (code === 4003) return false;
45
- return true;
46
- };
47
- const AUTH_CLOSE_REASON = "authentication failed";
48
- const PATCH_STREAM_BUFFER_MAX_PENDING = 128;
49
- const isRecord = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
50
- const isRealtimeCompactFrame = (value) => {
51
- if (!isRecord(value)) return false;
52
- if (value.t !== "d" && value.t !== "p") return false;
53
- if (typeof value.sid !== "string" || !value.sid) return false;
54
- if (typeof value.s !== "number" || !Number.isInteger(value.s) || value.s < 0) return false;
55
- if (typeof value.b !== "number" || !Number.isInteger(value.b) || value.b < 0) return false;
56
- if (value.t === "d") return "v" in value;
57
- return (value.o === "append" || value.o === "replace" || value.o === "add" || value.o === "merge" || value.o === "remove") && typeof value.p === "string" && value.p.length > 0;
58
- };
59
- const isRealtimeEnvelope = (value) => {
60
- if (!isRecord(value)) return false;
61
- if (typeof value.id !== "string") return false;
62
- if (typeof value.timestamp !== "number") return false;
63
- if (value.domain !== "system" && value.domain !== "session" && value.domain !== "space" && value.domain !== "label") return false;
64
- if (typeof value.type !== "string") return false;
65
- if (!isRecord(value.payload)) return false;
66
- return true;
67
- };
68
- const compactFrameToPatchOperation = (frame) => {
69
- if (frame.t === "d") return { v: frame.v };
70
- if (frame.o === "remove") return {
71
- o: "remove",
72
- p: frame.p
73
- };
74
- if (frame.o === "merge") return isRecord(frame.v) ? {
75
- o: "merge",
76
- p: frame.p,
77
- v: frame.v
78
- } : null;
79
- if (!("v" in frame)) return null;
80
- switch (frame.o) {
81
- case "append": return {
82
- o: "append",
83
- p: frame.p,
84
- v: frame.v
85
- };
86
- case "replace": return {
87
- o: "replace",
88
- p: frame.p,
89
- v: frame.v
90
- };
91
- case "add": return {
92
- o: "add",
93
- p: frame.p,
94
- v: frame.v
95
- };
96
- default: return null;
97
- }
98
- };
99
- var WebsocketAuthError = class extends Error {
100
- constructor(message) {
101
- super(message);
102
- this.name = "WebsocketAuthError";
103
- }
104
- };
105
- var WebsocketClient = class {
106
- url;
107
- autoReconnect;
108
- reconnectBaseDelayMs;
109
- reconnectMaxDelayMs;
110
- pingIntervalMs;
111
- pongTimeoutMs;
112
- debug;
113
- getAccessToken;
114
- WebSocketImpl;
115
- ws = null;
116
- pingTimer = null;
117
- reconnectTimer = null;
118
- reconnectTimerResolver = null;
119
- reconnectAttempt = 0;
120
- manuallyClosed = false;
121
- connectPromise = null;
122
- authWaiter = null;
123
- awaitingPong = false;
124
- lastPingRequestId = null;
125
- pongDeadlineAt = 0;
126
- compactStreamContexts = /* @__PURE__ */ new Map();
127
- patchStreamBuffers = /* @__PURE__ */ new Map();
128
- state = "idle";
129
- connectionId = null;
130
- listeners = createEventMap();
131
- constructor(options = {}) {
132
- const normalized = normalizeOptions(options);
133
- this.url = normalized.url;
134
- this.autoReconnect = normalized.autoReconnect;
135
- this.reconnectBaseDelayMs = normalized.reconnectBaseDelayMs;
136
- this.reconnectMaxDelayMs = normalized.reconnectMaxDelayMs;
137
- this.pingIntervalMs = normalized.pingIntervalMs;
138
- this.pongTimeoutMs = normalized.pongTimeoutMs;
139
- this.debug = normalized.debug;
140
- this.getAccessToken = options.getAccessToken;
141
- this.WebSocketImpl = options.WebSocketImpl ?? WebSocket;
142
- }
143
- on(type, handler) {
144
- this.listeners[type].add(handler);
145
- return () => this.off(type, handler);
146
- }
147
- off(type, handler) {
148
- this.listeners[type].delete(handler);
149
- }
150
- emit(type, payload) {
151
- for (const handler of this.listeners[type]) handler(payload);
152
- }
153
- log(...args) {
154
- if (this.debug) console.log("[WebsocketClient]", ...args);
155
- }
156
- async connect() {
157
- if (this.connectPromise) return this.connectPromise;
158
- if (this.state === "open" && this.ws?.readyState === WebSocket.OPEN) return;
159
- const isReconnect = this.reconnectAttempt > 0 || this.state === "reconnecting";
160
- this.manuallyClosed = false;
161
- this.clearReconnectTimer();
162
- this.state = isReconnect ? "reconnecting" : "connecting";
163
- this.emit("connecting", {
164
- isReconnect,
165
- attempt: this.reconnectAttempt
166
- });
167
- this.connectPromise = new Promise((resolve, reject) => {
168
- const ws = new this.WebSocketImpl(this.url);
169
- this.ws = ws;
170
- let settled = false;
171
- const rejectOnce = (error) => {
172
- if (settled) return;
173
- settled = true;
174
- this.connectPromise = null;
175
- reject(error);
176
- };
177
- const resolveOnce = () => {
178
- if (settled) return;
179
- settled = true;
180
- this.connectPromise = null;
181
- resolve();
182
- };
183
- ws.onopen = async () => {
184
- try {
185
- this.log("connected", {
186
- url: this.url,
187
- isReconnect,
188
- attempt: this.reconnectAttempt
189
- });
190
- this.startPingLoop();
191
- await this.authenticate();
192
- this.state = "open";
193
- this.reconnectAttempt = 0;
194
- this.emit("open", { connectionId: this.connectionId });
195
- resolveOnce();
196
- } catch (error) {
197
- const authError = error instanceof Error ? error : /* @__PURE__ */ new Error("authentication failed");
198
- this.emit("error", {
199
- error: authError,
200
- recoverable: false
201
- });
202
- rejectOnce(authError);
203
- ws.close(4003, AUTH_CLOSE_REASON);
204
- }
205
- };
206
- ws.onmessage = (event) => {
207
- this.handleMessage(event.data);
208
- };
209
- ws.onerror = (error) => {
210
- this.emit("error", {
211
- error,
212
- recoverable: !this.manuallyClosed
213
- });
214
- };
215
- ws.onclose = (event) => {
216
- this.stopPingLoop();
217
- const wasConnecting = this.state === "connecting" || this.state === "reconnecting";
218
- this.state = "closed";
219
- this.ws = null;
220
- this.compactStreamContexts.clear();
221
- this.patchStreamBuffers.clear();
222
- const closeError = new Error(formatCloseMessage(event.code, event.reason));
223
- this.rejectAuthWaiter(closeError);
224
- const willReconnect = !this.manuallyClosed && this.autoReconnect && 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
- if (wasConnecting) rejectOnce(closeError);
237
- if (willReconnect) this.scheduleReconnect(event.code, event.reason);
238
- };
239
- });
240
- return this.connectPromise;
241
- }
242
- async disconnect(code = 1e3, reason = "manual") {
243
- this.manuallyClosed = true;
244
- this.clearReconnectTimer();
245
- this.stopPingLoop();
246
- this.state = "closed";
247
- this.rejectAuthWaiter(/* @__PURE__ */ new Error("disconnected"));
248
- this.ws?.close(code, reason);
249
- this.ws = null;
250
- this.connectPromise = null;
251
- this.compactStreamContexts.clear();
252
- this.patchStreamBuffers.clear();
253
- }
254
- async sendCanvasTransaction(input) {
255
- await this.ensureOpen();
256
- this.send({
257
- type: "canvas.tx",
258
- requestId: input.requestId,
259
- payload: {
260
- spaceId: input.spaceId,
261
- documentId: input.documentId,
262
- txId: input.txId,
263
- baseVersion: input.baseVersion ?? null,
264
- clientId: input.clientId ?? null,
265
- undoGroupId: input.undoGroupId ?? null,
266
- ops: input.ops
267
- }
268
- });
269
- }
270
- async sendMessage(input) {
271
- await this.ensureOpen();
272
- this.send({
273
- type: "session.message.create",
274
- requestId: input.requestId,
275
- payload: {
276
- spaceId: input.spaceId,
277
- sessionId: input.sessionId,
278
- content: input.content,
279
- clientMessageId: input.clientMessageId,
280
- model: input.model,
281
- provider: input.provider
282
- }
283
- });
284
- }
285
- ack(eventId, requestId) {
286
- this.send({
287
- type: "ack",
288
- requestId,
289
- payload: eventId ? { eventId } : void 0
290
- });
291
- }
292
- ping(requestId) {
293
- const effectiveRequestId = requestId ?? `ping-${Date.now()}`;
294
- this.awaitingPong = true;
295
- this.lastPingRequestId = effectiveRequestId;
296
- this.pongDeadlineAt = Date.now() + this.pongTimeoutMs;
297
- this.send({
298
- type: "ping",
299
- requestId: effectiveRequestId,
300
- payload: {}
301
- });
302
- }
303
- async ensureOpen() {
304
- if (this.state === "open" && this.ws?.readyState === WebSocket.OPEN) return;
305
- await this.connect();
306
- }
307
- send(event) {
308
- const ws = this.ws;
309
- if (!ws || ws.readyState !== WebSocket.OPEN) throw new Error("websocket is not open");
310
- ws.send(JSON.stringify(event));
311
- }
312
- async authenticate() {
313
- const token = this.getAccessToken ? await this.getAccessToken() : null;
314
- if (!token) throw new WebsocketAuthError("missing access token");
315
- const waiter = this.createAuthWaiter();
316
- this.send({
317
- type: "auth",
318
- payload: {
319
- token,
320
- capabilities: [WS_COMPACT_STREAM_CAPABILITY]
321
- }
322
- });
323
- await waiter.promise;
324
- }
325
- createAuthWaiter() {
326
- this.rejectAuthWaiter(/* @__PURE__ */ new Error("superseded auth waiter"));
327
- let resolve;
328
- let reject;
329
- const promise = new Promise((res, rej) => {
330
- resolve = res;
331
- reject = rej;
332
- });
333
- this.authWaiter = {
334
- promise,
335
- resolve,
336
- reject
337
- };
338
- return this.authWaiter;
339
- }
340
- resolveAuthWaiter() {
341
- if (!this.authWaiter) return;
342
- this.authWaiter.resolve();
343
- this.authWaiter = null;
344
- }
345
- rejectAuthWaiter(error) {
346
- if (!this.authWaiter) return;
347
- this.authWaiter.reject(error);
348
- this.authWaiter = null;
349
- }
350
- handleMessage(raw) {
351
- let parsed;
352
- try {
353
- parsed = typeof raw === "string" ? JSON.parse(raw) : JSON.parse(String(raw));
354
- } catch {
355
- this.emit("error", {
356
- error: /* @__PURE__ */ new Error("invalid websocket payload"),
357
- recoverable: true
358
- });
359
- return;
360
- }
361
- if (isRealtimeCompactFrame(parsed)) {
362
- this.handleCompactFrame(parsed);
363
- return;
364
- }
365
- if (!isRealtimeEnvelope(parsed)) {
366
- this.emit("error", {
367
- error: /* @__PURE__ */ new Error("invalid realtime envelope"),
368
- recoverable: true
369
- });
370
- return;
371
- }
372
- const envelope = parsed;
373
- this.rememberCompactStreamContext(envelope);
374
- if (envelope.type === "session.turn.patch") {
375
- this.handlePatchEnvelope(envelope);
376
- return;
377
- }
378
- switch (envelope.type) {
379
- case "system.ready": {
380
- const connectionId = typeof envelope.payload.connectionId === "string" ? envelope.payload.connectionId : null;
381
- if (connectionId) {
382
- this.connectionId = connectionId;
383
- this.emit("ready", { connectionId });
384
- }
385
- this.emit("event", envelope);
386
- return;
387
- }
388
- case "system.auth.ok": {
389
- const connectionId = typeof envelope.payload.connectionId === "string" ? envelope.payload.connectionId : this.connectionId;
390
- const user = envelope.payload.user && typeof envelope.payload.user === "object" ? envelope.payload.user : {};
391
- if (connectionId) {
392
- this.connectionId = connectionId;
393
- this.emit("auth", {
394
- connectionId,
395
- user
396
- });
397
- }
398
- this.resolveAuthWaiter();
399
- this.emit("event", envelope);
400
- return;
401
- }
402
- case "system.request.error": {
403
- const message = typeof envelope.payload.message === "string" ? envelope.payload.message : "request failed";
404
- const code = typeof envelope.payload.code === "string" ? envelope.payload.code : void 0;
405
- const error = new WebsocketAuthError(message);
406
- this.rejectAuthWaiter(error);
407
- this.emit("serverError", {
408
- code,
409
- message,
410
- requestId: envelope.requestId ?? null,
411
- sessionId: envelope.sessionId ?? null,
412
- spaceId: envelope.spaceId ?? null
413
- });
414
- this.emit("event", envelope);
415
- return;
416
- }
417
- case "session.request.accepted": {
418
- const payload = envelope.payload;
419
- this.emit("messageAccepted", {
420
- requestId: envelope.requestId ?? null,
421
- sessionId: envelope.sessionId ?? null,
422
- spaceId: envelope.spaceId ?? null,
423
- clientMessageId: typeof payload.clientMessageId === "string" ? payload.clientMessageId : null,
424
- turnId: typeof payload.turnId === "string" ? payload.turnId : null,
425
- userMessageId: typeof payload.userMessageId === "string" ? payload.userMessageId : null,
426
- traceId: typeof payload.traceId === "string" ? payload.traceId : null
427
- });
428
- this.emit("event", envelope);
429
- return;
430
- }
431
- case "session.request.error": {
432
- const payload = envelope.payload;
433
- this.emit("serverError", {
434
- code: typeof payload.code === "string" ? payload.code : void 0,
435
- message: typeof payload.message === "string" ? payload.message : void 0,
436
- requestId: envelope.requestId ?? null,
437
- sessionId: envelope.sessionId ?? null,
438
- spaceId: envelope.spaceId ?? null,
439
- clientMessageId: typeof payload.clientMessageId === "string" ? payload.clientMessageId : null
440
- });
441
- this.emit("event", envelope);
442
- return;
443
- }
444
- case "system.pong": {
445
- const requestId = envelope.requestId ?? null;
446
- if (!requestId || requestId === this.lastPingRequestId) {
447
- this.awaitingPong = false;
448
- this.lastPingRequestId = null;
449
- this.pongDeadlineAt = 0;
450
- }
451
- this.emit("pong", { requestId });
452
- return;
453
- }
454
- case "system.ack.ok": return;
455
- default:
456
- this.emit("event", envelope);
457
- return;
458
- }
459
- }
460
- rememberCompactStreamContext(envelope) {
461
- if (envelope.type === "session.turn.patch") {
462
- const payload = envelope.payload;
463
- const turnId = typeof payload.turnId === "string" ? payload.turnId : null;
464
- const messageId = typeof payload.messageId === "string" ? payload.messageId : null;
465
- const realtimeMeta = payload._rt && typeof payload._rt === "object" ? payload._rt : null;
466
- const sid = typeof realtimeMeta?.sid === "string" && realtimeMeta.sid.trim() ? realtimeMeta.sid : turnId ?? messageId;
467
- if (!sid) return;
468
- this.compactStreamContexts.set(sid, {
469
- spaceId: envelope.spaceId ?? null,
470
- sessionId: envelope.sessionId ?? null,
471
- turnId,
472
- messageId,
473
- messageOrdinal: typeof payload.messageOrdinal === "number" ? payload.messageOrdinal : null,
474
- anchorUserMessageId: typeof payload.anchorUserMessageId === "string" ? payload.anchorUserMessageId : null
475
- });
476
- return;
477
- }
478
- if (envelope.type !== "session.message.persisted") return;
479
- const message = envelope.payload.message;
480
- if (!message || typeof message !== "object") return;
481
- const meta = message.meta;
482
- const turnId = typeof meta?.turnId === "string" ? meta.turnId : null;
483
- if (!turnId) return;
484
- for (const [sid, context] of this.compactStreamContexts.entries()) if (context.turnId === turnId) {
485
- this.compactStreamContexts.delete(sid);
486
- this.patchStreamBuffers.delete(sid);
487
- }
488
- }
489
- getPatchStreamBufferKey(envelope) {
490
- if (envelope.type !== "session.turn.patch") return null;
491
- const payload = envelope.payload;
492
- const realtimeMeta = payload._rt && typeof payload._rt === "object" ? payload._rt : null;
493
- if (typeof realtimeMeta?.sid === "string" && realtimeMeta.sid.trim()) return realtimeMeta.sid;
494
- return getSessionTurnPatchStreamKey(payload, { includeSessionFallback: true });
495
- }
496
- handlePatchEnvelope(envelope) {
497
- const payload = envelope.payload;
498
- if (typeof payload.seq !== "number" || typeof payload.baseSeq !== "number" || !Number.isInteger(payload.seq) || !Number.isInteger(payload.baseSeq) || payload.seq < 0 || payload.baseSeq < 0) {
499
- this.emit("event", envelope);
500
- return;
501
- }
502
- const key = this.getPatchStreamBufferKey(envelope);
503
- if (!key) {
504
- this.emit("event", envelope);
505
- return;
506
- }
507
- if (payload.baseSeq === 0) {
508
- const buffer = {
509
- nextSeq: payload.seq + 1,
510
- pending: /* @__PURE__ */ new Map()
511
- };
512
- this.patchStreamBuffers.set(key, buffer);
513
- this.emit("event", envelope);
514
- this.flushPatchStreamBuffer(buffer);
515
- return;
516
- }
517
- const buffer = this.patchStreamBuffers.get(key);
518
- if (!buffer) {
519
- const newBuffer = {
520
- nextSeq: payload.baseSeq + 1,
521
- pending: new Map([[payload.seq, envelope]])
522
- };
523
- this.patchStreamBuffers.set(key, newBuffer);
524
- this.flushPatchStreamBuffer(newBuffer);
525
- return;
526
- }
527
- if (payload.seq < buffer.nextSeq) return;
528
- buffer.pending.set(payload.seq, envelope);
529
- if (!this.enforcePatchStreamBufferLimit(key, buffer)) return;
530
- this.flushPatchStreamBuffer(buffer);
531
- }
532
- enforcePatchStreamBufferLimit(key, buffer) {
533
- if (buffer.pending.size <= PATCH_STREAM_BUFFER_MAX_PENDING) return true;
534
- this.patchStreamBuffers.delete(key);
535
- this.emit("error", {
536
- error: /* @__PURE__ */ new Error(`patch stream buffer overflow: ${key}`),
537
- recoverable: true
538
- });
539
- return false;
540
- }
541
- flushPatchStreamBuffer(buffer) {
542
- while (true) {
543
- const envelope = buffer.pending.get(buffer.nextSeq);
544
- if (!envelope) return;
545
- const seq = envelope.payload.seq;
546
- if (typeof seq !== "number" || !Number.isInteger(seq)) return;
547
- buffer.pending.delete(buffer.nextSeq);
548
- buffer.nextSeq = seq + 1;
549
- this.emit("event", envelope);
550
- }
551
- }
552
- handleCompactFrame(frame) {
553
- const context = this.compactStreamContexts.get(frame.sid);
554
- if (!context?.sessionId) {
555
- this.emit("error", {
556
- error: /* @__PURE__ */ new Error(`unknown compact stream: ${frame.sid}`),
557
- recoverable: true
558
- });
559
- return;
560
- }
561
- const op = compactFrameToPatchOperation(frame);
562
- if (!op) {
563
- this.emit("error", {
564
- error: /* @__PURE__ */ new Error(`invalid compact stream frame: ${frame.sid}`),
565
- recoverable: true
566
- });
567
- return;
568
- }
569
- const envelope = {
570
- id: `compact:${frame.sid}:${frame.s}`,
571
- timestamp: Date.now(),
572
- domain: "session",
573
- type: "session.turn.patch",
574
- spaceId: context.spaceId,
575
- sessionId: context.sessionId,
576
- payload: {
577
- turnId: context.turnId,
578
- messageId: context.messageId,
579
- messageOrdinal: context.messageOrdinal,
580
- sourceMessageId: context.messageId,
581
- anchorUserMessageId: context.anchorUserMessageId,
582
- seq: frame.s,
583
- baseSeq: frame.b,
584
- ops: [op],
585
- _rt: { sid: frame.sid }
586
- }
587
- };
588
- this.handlePatchEnvelope(envelope);
589
- }
590
- startPingLoop() {
591
- this.stopPingLoop();
592
- this.pingTimer = setInterval(() => {
593
- if (this.ws?.readyState !== WebSocket.OPEN) return;
594
- if (this.awaitingPong && this.pongDeadlineAt > 0 && Date.now() > this.pongDeadlineAt) {
595
- this.emit("error", {
596
- error: /* @__PURE__ */ new Error("websocket pong timeout"),
597
- recoverable: true
598
- });
599
- this.ws.close(4002, "pong timeout");
600
- return;
601
- }
602
- this.ping();
603
- }, this.pingIntervalMs);
604
- }
605
- stopPingLoop() {
606
- if (this.pingTimer) {
607
- clearInterval(this.pingTimer);
608
- this.pingTimer = null;
609
- }
610
- this.awaitingPong = false;
611
- this.lastPingRequestId = null;
612
- this.pongDeadlineAt = 0;
613
- }
614
- clearReconnectTimer() {
615
- if (this.reconnectTimer) {
616
- clearTimeout(this.reconnectTimer);
617
- this.reconnectTimer = null;
618
- }
619
- if (this.reconnectTimerResolver) {
620
- const resolve = this.reconnectTimerResolver;
621
- this.reconnectTimerResolver = null;
622
- resolve();
623
- }
624
- }
625
- async scheduleReconnect(code, reason) {
626
- this.clearReconnectTimer();
627
- const attempt = this.reconnectAttempt + 1;
628
- const delay = Math.min(this.reconnectBaseDelayMs * 2 ** this.reconnectAttempt, this.reconnectMaxDelayMs);
629
- this.reconnectAttempt = attempt;
630
- this.state = "reconnecting";
631
- this.log("schedule reconnect", {
632
- attempt,
633
- delay,
634
- code,
635
- reason
636
- });
637
- this.emit("reconnecting", {
638
- attempt,
639
- delayMs: delay,
640
- code,
641
- reason
642
- });
643
- await new Promise((resolve) => {
644
- this.reconnectTimerResolver = resolve;
645
- this.reconnectTimer = setTimeout(() => {
646
- this.reconnectTimer = null;
647
- this.reconnectTimerResolver = null;
648
- resolve();
649
- }, delay);
650
- });
651
- if (this.manuallyClosed) return;
652
- if (typeof navigator !== "undefined" && navigator.onLine === false) {
653
- await new Promise((resolve) => {
654
- const fallbackTimer = setTimeout(resolve, this.reconnectMaxDelayMs);
655
- const handleOnline = () => {
656
- clearTimeout(fallbackTimer);
657
- globalThis.removeEventListener?.("online", handleOnline);
658
- resolve();
659
- };
660
- globalThis.addEventListener?.("online", handleOnline, { once: true });
661
- });
662
- if (this.manuallyClosed) return;
663
- }
664
- await this.connect().catch((error) => {
665
- this.emit("error", {
666
- error,
667
- recoverable: true
668
- });
669
- });
670
- }
671
- };
672
- const createWebsocketClient = (options) => new WebsocketClient(options);
673
- //#endregion
674
- export { createWebsocketClient as n, WebsocketClient as t };