@spacelr/sdk 0.18.2 → 0.18.4

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/index.d.mts CHANGED
@@ -929,6 +929,11 @@ declare class RealtimeClient {
929
929
  */
930
930
  private eventMatchesStreamWhere;
931
931
  private ensureConnected;
932
+ /**
933
+ * `ensureConnected` that returns the failure instead of throwing (#983).
934
+ * A disposed client still throws: nothing may be kept or retried on it.
935
+ */
936
+ private tryEnsureConnected;
932
937
  private connect;
933
938
  private eventMatchesRoom;
934
939
  /**
@@ -941,6 +946,13 @@ declare class RealtimeClient {
941
946
  */
942
947
  private rebuildSocket;
943
948
  private handlePostRebuild;
949
+ /**
950
+ * A subscription was kept after a failed connect (#983): schedule the retry,
951
+ * report 'reconnecting' (one is now pending; 'disconnected' means nothing
952
+ * will retry), then tell the caller once. The handler runs last and guarded,
953
+ * so a throwing consumer cannot cancel recovery or make subscribe reject.
954
+ */
955
+ private keepRetrying;
944
956
  private scheduleRebuildRetry;
945
957
  private ensureWakeListeners;
946
958
  private detachWakeListeners;
package/dist/index.d.ts CHANGED
@@ -929,6 +929,11 @@ declare class RealtimeClient {
929
929
  */
930
930
  private eventMatchesStreamWhere;
931
931
  private ensureConnected;
932
+ /**
933
+ * `ensureConnected` that returns the failure instead of throwing (#983).
934
+ * A disposed client still throws: nothing may be kept or retried on it.
935
+ */
936
+ private tryEnsureConnected;
932
937
  private connect;
933
938
  private eventMatchesRoom;
934
939
  /**
@@ -941,6 +946,13 @@ declare class RealtimeClient {
941
946
  */
942
947
  private rebuildSocket;
943
948
  private handlePostRebuild;
949
+ /**
950
+ * A subscription was kept after a failed connect (#983): schedule the retry,
951
+ * report 'reconnecting' (one is now pending; 'disconnected' means nothing
952
+ * will retry), then tell the caller once. The handler runs last and guarded,
953
+ * so a throwing consumer cannot cancel recovery or make subscribe reject.
954
+ */
955
+ private keepRetrying;
944
956
  private scheduleRebuildRetry;
945
957
  private ensureWakeListeners;
946
958
  private detachWakeListeners;
package/dist/index.js CHANGED
@@ -978,7 +978,7 @@ var RealtimeClient = class {
978
978
  if (this.connectionState === "disconnected") {
979
979
  this.setConnectionState("reconnecting");
980
980
  }
981
- await this.ensureConnected();
981
+ const connectError = await this.tryEnsureConnected();
982
982
  const room = this.buildRoomKey(projectId, collectionName, where);
983
983
  if (!this.subscriptions.has(room)) {
984
984
  this.subscriptions.set(room, /* @__PURE__ */ new Set());
@@ -1003,16 +1003,19 @@ var RealtimeClient = class {
1003
1003
  if (where && Object.keys(where).length > 0) {
1004
1004
  payload["where"] = where;
1005
1005
  }
1006
- this.socket?.emit(
1007
- "subscribe",
1008
- payload,
1009
- (response) => {
1010
- if (response.error && this.roomGeneration.get(room) === generation) {
1011
- this.notifyRoomError(room, this.toSubscribeError(response));
1006
+ if (!connectError) {
1007
+ this.socket?.emit(
1008
+ "subscribe",
1009
+ payload,
1010
+ (response) => {
1011
+ if (response.error && this.roomGeneration.get(room) === generation) {
1012
+ this.notifyRoomError(room, this.toSubscribeError(response));
1013
+ }
1012
1014
  }
1013
- }
1014
- );
1015
+ );
1016
+ }
1015
1017
  }
1018
+ if (connectError) this.keepRetrying(connectError, onError);
1016
1019
  return () => {
1017
1020
  const callbacks2 = this.subscriptions.get(room);
1018
1021
  if (callbacks2) {
@@ -1043,7 +1046,7 @@ var RealtimeClient = class {
1043
1046
  * event rather than the originally-subscribed `sinceId`.
1044
1047
  */
1045
1048
  async subscribeWithCursor(options) {
1046
- const { unsubscribe } = await this._subscribeInternal(options);
1049
+ const { unsubscribe } = await this._subscribeInternal(options, true);
1047
1050
  return unsubscribe;
1048
1051
  }
1049
1052
  /**
@@ -1104,12 +1107,17 @@ var RealtimeClient = class {
1104
1107
  * only — `emitSubscribeEvents` itself always resolves, so this
1105
1108
  * catch should never fire on the success path.
1106
1109
  */
1107
- async _subscribeInternal(options) {
1110
+ async _subscribeInternal(options, keepOnConnectFailure = false) {
1108
1111
  this.ensureWakeListeners();
1109
1112
  if (this.connectionState === "disconnected") {
1110
1113
  this.setConnectionState("reconnecting");
1111
1114
  }
1112
- await this.ensureConnected();
1115
+ let connectError = null;
1116
+ if (keepOnConnectFailure) {
1117
+ connectError = await this.tryEnsureConnected();
1118
+ } else {
1119
+ await this.ensureConnected();
1120
+ }
1113
1121
  const streamKey = `stream:${options.projectId}:${options.collectionName}`;
1114
1122
  const subscriptionKey = this.streamSubscriptionKey(
1115
1123
  streamKey,
@@ -1135,14 +1143,21 @@ var RealtimeClient = class {
1135
1143
  subscriptionKey,
1136
1144
  dispatchQueue: Promise.resolve()
1137
1145
  };
1146
+ const syntheticAck = {
1147
+ subscribed: streamKey,
1148
+ realtimeMode: "stream",
1149
+ latestStreamId: null
1150
+ };
1151
+ if (connectError) {
1152
+ const kept = this.streamSubscriptions.get(subscriptionKey) ?? /* @__PURE__ */ new Set();
1153
+ kept.add(state);
1154
+ this.streamSubscriptions.set(subscriptionKey, kept);
1155
+ this.keepRetrying(connectError, options.onError);
1156
+ return { unsubscribe: () => this.unsubscribeStream(state), ack: syntheticAck };
1157
+ }
1138
1158
  const existing = this.streamSubscriptions.get(subscriptionKey);
1139
1159
  if (existing && existing.size > 0) {
1140
1160
  existing.add(state);
1141
- const syntheticAck = {
1142
- subscribed: streamKey,
1143
- realtimeMode: "stream",
1144
- latestStreamId: null
1145
- };
1146
1161
  return {
1147
1162
  unsubscribe: () => this.unsubscribeStream(state),
1148
1163
  ack: syntheticAck
@@ -1292,7 +1307,25 @@ var RealtimeClient = class {
1292
1307
  this.connecting = null;
1293
1308
  }
1294
1309
  }
1310
+ /**
1311
+ * `ensureConnected` that returns the failure instead of throwing (#983).
1312
+ * A disposed client still throws: nothing may be kept or retried on it.
1313
+ */
1314
+ async tryEnsureConnected() {
1315
+ try {
1316
+ await this.ensureConnected();
1317
+ return null;
1318
+ } catch (err) {
1319
+ if (this.disposed) throw err;
1320
+ return err instanceof Error ? err : new Error(String(err));
1321
+ }
1322
+ }
1295
1323
  async connect() {
1324
+ const previous = this.socket;
1325
+ if (previous) {
1326
+ this.socket = null;
1327
+ previous.disconnect();
1328
+ }
1296
1329
  const token = await this.config.getToken();
1297
1330
  if (!token) {
1298
1331
  throw new Error("No authentication token available");
@@ -1301,7 +1334,7 @@ var RealtimeClient = class {
1301
1334
  return new Promise((resolve, reject) => {
1302
1335
  let initialConnect = true;
1303
1336
  let onInitialDisconnect = null;
1304
- this.socket = (0, import_socket.io)(`${wsUrl}/database`, {
1337
+ const socket = (0, import_socket.io)(`${wsUrl}/database`, {
1305
1338
  auth: async (cb) => {
1306
1339
  try {
1307
1340
  const freshToken = await this.config.getToken();
@@ -1315,10 +1348,24 @@ var RealtimeClient = class {
1315
1348
  // rejects on connect_error and they decide whether to retry. Once the
1316
1349
  // first authentication succeeds we re-enable it via the Manager's
1317
1350
  // setters (see authenticated handler).
1318
- reconnection: false
1351
+ reconnection: false,
1352
+ // #1000 — socket.io's 20 s default left a connect that hangs without
1353
+ // a close (browser offline mid-handshake) pending for 20 s before the
1354
+ // retry could start. Also applies to the later auto-reconnects.
1355
+ timeout: 5e3
1319
1356
  });
1320
- this.socket.on("authenticated", () => {
1357
+ this.socket = socket;
1358
+ const failInitialConnect = (message) => {
1359
+ socket.disconnect();
1360
+ if (this.socket === socket) {
1361
+ this.socket = null;
1362
+ this.setConnectionState("disconnected");
1363
+ }
1364
+ reject(new Error(message));
1365
+ };
1366
+ socket.on("authenticated", () => {
1321
1367
  if (this.disposed) return;
1368
+ if (this.socket !== socket) return;
1322
1369
  this.setConnectionState("connected");
1323
1370
  if (initialConnect) {
1324
1371
  initialConnect = false;
@@ -1357,29 +1404,29 @@ var RealtimeClient = class {
1357
1404
  }
1358
1405
  );
1359
1406
  }
1407
+ if (this.subscriptions.size > 0) this.resubscribeAll();
1408
+ if (this.streamSubscriptions.size > 0) void this.resubscribeAllStreams();
1360
1409
  resolve();
1361
1410
  } else {
1362
1411
  this.resubscribeAll();
1363
1412
  void this.resubscribeAllStreams();
1364
1413
  }
1365
1414
  });
1366
- this.socket.on("connect_error", (err) => {
1415
+ socket.on("connect_error", (err) => {
1367
1416
  if (initialConnect) {
1368
- reject(new Error(`WebSocket connection failed: ${err.message}`));
1417
+ failInitialConnect(`WebSocket connection failed: ${err.message}`);
1369
1418
  }
1370
1419
  });
1371
1420
  onInitialDisconnect = (reason) => {
1372
1421
  if (!initialConnect) return;
1373
- this.socket?.disconnect();
1374
- this.socket = null;
1375
- this.setConnectionState("disconnected");
1376
- reject(new Error(`WebSocket disconnected during handshake: ${reason}`));
1422
+ failInitialConnect(`WebSocket disconnected during handshake: ${reason}`);
1377
1423
  };
1378
- this.socket.on("disconnect", onInitialDisconnect);
1379
- this.socket.io.on("reconnect_failed", () => {
1424
+ socket.on("disconnect", onInitialDisconnect);
1425
+ socket.io.on("reconnect_failed", () => {
1426
+ if (this.socket !== socket) return;
1380
1427
  void this.rebuildSocket();
1381
1428
  });
1382
- this.socket.on("db:event", (event) => {
1429
+ socket.on("db:event", (event) => {
1383
1430
  const base = `db:${event.projectId}:${event.collectionName}`;
1384
1431
  const baseCallbacks = this.subscriptions.get(base);
1385
1432
  if (baseCallbacks) {
@@ -1401,7 +1448,7 @@ var RealtimeClient = class {
1401
1448
  }
1402
1449
  }
1403
1450
  });
1404
- this.socket.on(
1451
+ socket.on(
1405
1452
  "subscription-invalidated",
1406
1453
  (payload) => {
1407
1454
  if (!payload?.projectId || !payload?.collectionName) return;
@@ -1413,10 +1460,10 @@ var RealtimeClient = class {
1413
1460
  }
1414
1461
  }
1415
1462
  );
1416
- this.socket.on("event", (payload) => {
1463
+ socket.on("event", (payload) => {
1417
1464
  this.dispatchStreamEvent(payload).catch(() => void 0);
1418
1465
  });
1419
- this.socket.on("event-gap", (info) => {
1466
+ socket.on("event-gap", (info) => {
1420
1467
  const streamKey = `stream:${info.projectId}:${info.collectionName}`;
1421
1468
  for (const set of this.streamSetsForStreamKey(streamKey)) {
1422
1469
  for (const state of set) {
@@ -1424,7 +1471,7 @@ var RealtimeClient = class {
1424
1471
  }
1425
1472
  }
1426
1473
  });
1427
- this.socket.on("subscription-reset", (info) => {
1474
+ socket.on("subscription-reset", (info) => {
1428
1475
  if (!info || typeof info.projectId !== "string") return;
1429
1476
  for (const set of this.streamSubscriptions.values()) {
1430
1477
  for (const state of set) {
@@ -1439,10 +1486,10 @@ var RealtimeClient = class {
1439
1486
  }
1440
1487
  }
1441
1488
  });
1442
- this.socket.on("disconnect", () => {
1489
+ socket.on("disconnect", () => {
1443
1490
  if (this.disposed) return;
1444
1491
  if (initialConnect) return;
1445
- if (!this.socket) return;
1492
+ if (this.socket !== socket) return;
1446
1493
  this.setConnectionState("reconnecting");
1447
1494
  });
1448
1495
  });
@@ -1490,17 +1537,30 @@ var RealtimeClient = class {
1490
1537
  newSocket?.disconnect();
1491
1538
  return;
1492
1539
  }
1493
- if (this.subscriptions.size > 0) {
1494
- this.resubscribeAll();
1495
- }
1496
- if (this.streamSubscriptions.size > 0) {
1497
- void this.resubscribeAllStreams();
1540
+ }
1541
+ /**
1542
+ * A subscription was kept after a failed connect (#983): schedule the retry,
1543
+ * report 'reconnecting' (one is now pending; 'disconnected' means nothing
1544
+ * will retry), then tell the caller once. The handler runs last and guarded,
1545
+ * so a throwing consumer cannot cancel recovery or make subscribe reject.
1546
+ */
1547
+ keepRetrying(error, onError) {
1548
+ this.scheduleRebuildRetry();
1549
+ this.setConnectionState("reconnecting");
1550
+ try {
1551
+ onError?.(error);
1552
+ } catch {
1498
1553
  }
1499
1554
  }
1500
1555
  scheduleRebuildRetry() {
1501
1556
  if (this.disposed || this.rebuildRetryTimer) return;
1502
1557
  this.rebuildRetryTimer = setTimeout(() => {
1503
1558
  this.rebuildRetryTimer = null;
1559
+ if (this.connecting) {
1560
+ this.scheduleRebuildRetry();
1561
+ return;
1562
+ }
1563
+ if (this.socket?.connected) return;
1504
1564
  void this.rebuildSocket();
1505
1565
  }, REBUILD_RETRY_DELAY_MS);
1506
1566
  this.rebuildRetryTimer.unref?.();