@spacelr/sdk 0.18.2 → 0.18.3

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();
@@ -1317,8 +1350,18 @@ var RealtimeClient = class {
1317
1350
  // setters (see authenticated handler).
1318
1351
  reconnection: false
1319
1352
  });
1320
- this.socket.on("authenticated", () => {
1353
+ this.socket = socket;
1354
+ const failInitialConnect = (message) => {
1355
+ socket.disconnect();
1356
+ if (this.socket === socket) {
1357
+ this.socket = null;
1358
+ this.setConnectionState("disconnected");
1359
+ }
1360
+ reject(new Error(message));
1361
+ };
1362
+ socket.on("authenticated", () => {
1321
1363
  if (this.disposed) return;
1364
+ if (this.socket !== socket) return;
1322
1365
  this.setConnectionState("connected");
1323
1366
  if (initialConnect) {
1324
1367
  initialConnect = false;
@@ -1357,29 +1400,29 @@ var RealtimeClient = class {
1357
1400
  }
1358
1401
  );
1359
1402
  }
1403
+ if (this.subscriptions.size > 0) this.resubscribeAll();
1404
+ if (this.streamSubscriptions.size > 0) void this.resubscribeAllStreams();
1360
1405
  resolve();
1361
1406
  } else {
1362
1407
  this.resubscribeAll();
1363
1408
  void this.resubscribeAllStreams();
1364
1409
  }
1365
1410
  });
1366
- this.socket.on("connect_error", (err) => {
1411
+ socket.on("connect_error", (err) => {
1367
1412
  if (initialConnect) {
1368
- reject(new Error(`WebSocket connection failed: ${err.message}`));
1413
+ failInitialConnect(`WebSocket connection failed: ${err.message}`);
1369
1414
  }
1370
1415
  });
1371
1416
  onInitialDisconnect = (reason) => {
1372
1417
  if (!initialConnect) return;
1373
- this.socket?.disconnect();
1374
- this.socket = null;
1375
- this.setConnectionState("disconnected");
1376
- reject(new Error(`WebSocket disconnected during handshake: ${reason}`));
1418
+ failInitialConnect(`WebSocket disconnected during handshake: ${reason}`);
1377
1419
  };
1378
- this.socket.on("disconnect", onInitialDisconnect);
1379
- this.socket.io.on("reconnect_failed", () => {
1420
+ socket.on("disconnect", onInitialDisconnect);
1421
+ socket.io.on("reconnect_failed", () => {
1422
+ if (this.socket !== socket) return;
1380
1423
  void this.rebuildSocket();
1381
1424
  });
1382
- this.socket.on("db:event", (event) => {
1425
+ socket.on("db:event", (event) => {
1383
1426
  const base = `db:${event.projectId}:${event.collectionName}`;
1384
1427
  const baseCallbacks = this.subscriptions.get(base);
1385
1428
  if (baseCallbacks) {
@@ -1401,7 +1444,7 @@ var RealtimeClient = class {
1401
1444
  }
1402
1445
  }
1403
1446
  });
1404
- this.socket.on(
1447
+ socket.on(
1405
1448
  "subscription-invalidated",
1406
1449
  (payload) => {
1407
1450
  if (!payload?.projectId || !payload?.collectionName) return;
@@ -1413,10 +1456,10 @@ var RealtimeClient = class {
1413
1456
  }
1414
1457
  }
1415
1458
  );
1416
- this.socket.on("event", (payload) => {
1459
+ socket.on("event", (payload) => {
1417
1460
  this.dispatchStreamEvent(payload).catch(() => void 0);
1418
1461
  });
1419
- this.socket.on("event-gap", (info) => {
1462
+ socket.on("event-gap", (info) => {
1420
1463
  const streamKey = `stream:${info.projectId}:${info.collectionName}`;
1421
1464
  for (const set of this.streamSetsForStreamKey(streamKey)) {
1422
1465
  for (const state of set) {
@@ -1424,7 +1467,7 @@ var RealtimeClient = class {
1424
1467
  }
1425
1468
  }
1426
1469
  });
1427
- this.socket.on("subscription-reset", (info) => {
1470
+ socket.on("subscription-reset", (info) => {
1428
1471
  if (!info || typeof info.projectId !== "string") return;
1429
1472
  for (const set of this.streamSubscriptions.values()) {
1430
1473
  for (const state of set) {
@@ -1439,10 +1482,10 @@ var RealtimeClient = class {
1439
1482
  }
1440
1483
  }
1441
1484
  });
1442
- this.socket.on("disconnect", () => {
1485
+ socket.on("disconnect", () => {
1443
1486
  if (this.disposed) return;
1444
1487
  if (initialConnect) return;
1445
- if (!this.socket) return;
1488
+ if (this.socket !== socket) return;
1446
1489
  this.setConnectionState("reconnecting");
1447
1490
  });
1448
1491
  });
@@ -1490,17 +1533,30 @@ var RealtimeClient = class {
1490
1533
  newSocket?.disconnect();
1491
1534
  return;
1492
1535
  }
1493
- if (this.subscriptions.size > 0) {
1494
- this.resubscribeAll();
1495
- }
1496
- if (this.streamSubscriptions.size > 0) {
1497
- void this.resubscribeAllStreams();
1536
+ }
1537
+ /**
1538
+ * A subscription was kept after a failed connect (#983): schedule the retry,
1539
+ * report 'reconnecting' (one is now pending; 'disconnected' means nothing
1540
+ * will retry), then tell the caller once. The handler runs last and guarded,
1541
+ * so a throwing consumer cannot cancel recovery or make subscribe reject.
1542
+ */
1543
+ keepRetrying(error, onError) {
1544
+ this.scheduleRebuildRetry();
1545
+ this.setConnectionState("reconnecting");
1546
+ try {
1547
+ onError?.(error);
1548
+ } catch {
1498
1549
  }
1499
1550
  }
1500
1551
  scheduleRebuildRetry() {
1501
1552
  if (this.disposed || this.rebuildRetryTimer) return;
1502
1553
  this.rebuildRetryTimer = setTimeout(() => {
1503
1554
  this.rebuildRetryTimer = null;
1555
+ if (this.connecting) {
1556
+ this.scheduleRebuildRetry();
1557
+ return;
1558
+ }
1559
+ if (this.socket?.connected) return;
1504
1560
  void this.rebuildSocket();
1505
1561
  }, REBUILD_RETRY_DELAY_MS);
1506
1562
  this.rebuildRetryTimer.unref?.();