@rebasepro/client 0.9.1-canary.f2f61da → 0.9.1-canary.ff338b5
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.ts +18 -0
- package/dist/index.es.js +489 -83
- package/dist/index.es.js.map +1 -1
- package/dist/realtime-channel.d.ts +102 -0
- package/dist/websocket.d.ts +82 -2
- package/package.json +7 -5
- package/src/index.ts +62 -2
- package/src/realtime-channel.test.ts +336 -0
- package/src/realtime-channel.ts +249 -0
- package/src/realtime-optout.test.ts +128 -2
- package/src/websocket.ts +442 -77
package/dist/index.es.js
CHANGED
|
@@ -1397,12 +1397,28 @@ var ClientStorageSourceRegistry = class ClientStorageSourceRegistry {
|
|
|
1397
1397
|
function extractMessageError(message) {
|
|
1398
1398
|
const payload = message.payload;
|
|
1399
1399
|
const errPayload = payload?.error;
|
|
1400
|
+
const errorMessage = typeof errPayload === "object" ? errPayload.message : payload?.message || (typeof errPayload === "string" ? errPayload : void 0) || message.error || "Unknown error";
|
|
1401
|
+
const errorCode = typeof errPayload === "object" ? errPayload.code : payload?.code;
|
|
1400
1402
|
return {
|
|
1401
|
-
errorMessage: typeof
|
|
1402
|
-
errorCode
|
|
1403
|
+
errorMessage: typeof errorMessage === "string" ? errorMessage : errorMessage == null ? "Unknown error" : JSON.stringify(errorMessage),
|
|
1404
|
+
errorCode
|
|
1403
1405
|
};
|
|
1404
1406
|
}
|
|
1405
1407
|
/**
|
|
1408
|
+
* Broadcast and presence frames.
|
|
1409
|
+
*
|
|
1410
|
+
* Fire-and-forget (the server sends no response envelope), and exempt from the
|
|
1411
|
+
* client-side auth gate — a public channel is usable without an account.
|
|
1412
|
+
*/
|
|
1413
|
+
var CHANNEL_MESSAGE_TYPES = new Set([
|
|
1414
|
+
"join_channel",
|
|
1415
|
+
"leave_channel",
|
|
1416
|
+
"broadcast",
|
|
1417
|
+
"presence_track",
|
|
1418
|
+
"presence_untrack",
|
|
1419
|
+
"presence_state"
|
|
1420
|
+
]);
|
|
1421
|
+
/**
|
|
1406
1422
|
* Low-level realtime WebSocket client.
|
|
1407
1423
|
*
|
|
1408
1424
|
* @internal Not a stable app-facing API. `createRebaseClient()` constructs and
|
|
@@ -1417,6 +1433,36 @@ var RebaseWebSocketClient = class {
|
|
|
1417
1433
|
getAuthToken;
|
|
1418
1434
|
subscriptions = /* @__PURE__ */ new Map();
|
|
1419
1435
|
listeners = /* @__PURE__ */ new Map();
|
|
1436
|
+
/** Channel-name → handlers, for broadcast and presence frames. */
|
|
1437
|
+
channelHandlers = /* @__PURE__ */ new Map();
|
|
1438
|
+
/** Set by `close()`. Blocks any later operation from silently redialling. */
|
|
1439
|
+
closedByCaller = false;
|
|
1440
|
+
/**
|
|
1441
|
+
* Whether a socket exists at all (open or still opening).
|
|
1442
|
+
*
|
|
1443
|
+
* Lets callers distinguish "authenticate the live socket" from "there is
|
|
1444
|
+
* nothing to authenticate yet", without that question forcing a dial.
|
|
1445
|
+
*/
|
|
1446
|
+
get hasSocket() {
|
|
1447
|
+
return this.ws !== null;
|
|
1448
|
+
}
|
|
1449
|
+
/** So the "no WebSocket in this environment" warning is said once, not per call. */
|
|
1450
|
+
warnedNoWebSocket = false;
|
|
1451
|
+
/** Subscribe to broadcast/presence frames for one channel. */
|
|
1452
|
+
onChannelMessage(channel, handler) {
|
|
1453
|
+
if (!this.channelHandlers.has(channel)) this.channelHandlers.set(channel, /* @__PURE__ */ new Set());
|
|
1454
|
+
this.channelHandlers.get(channel).add(handler);
|
|
1455
|
+
return () => {
|
|
1456
|
+
const handlers = this.channelHandlers.get(channel);
|
|
1457
|
+
if (!handlers) return;
|
|
1458
|
+
handlers.delete(handler);
|
|
1459
|
+
if (handlers.size === 0) this.channelHandlers.delete(channel);
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
/** Notified after the socket comes back, so channels can re-join. */
|
|
1463
|
+
onReconnect(handler) {
|
|
1464
|
+
return this.on("reconnect", handler);
|
|
1465
|
+
}
|
|
1420
1466
|
on(event, cb) {
|
|
1421
1467
|
if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
1422
1468
|
this.listeners.get(event).add(cb);
|
|
@@ -1435,6 +1481,7 @@ var RebaseWebSocketClient = class {
|
|
|
1435
1481
|
isConnected = false;
|
|
1436
1482
|
messageQueue = [];
|
|
1437
1483
|
requestTimeoutMs = 3e4;
|
|
1484
|
+
subscriptionTimeoutMs = 3e4;
|
|
1438
1485
|
reconnectTimeout = null;
|
|
1439
1486
|
isAuthenticated = false;
|
|
1440
1487
|
authPromise = null;
|
|
@@ -1446,8 +1493,25 @@ var RebaseWebSocketClient = class {
|
|
|
1446
1493
|
this.getAuthToken = config.getAuthToken;
|
|
1447
1494
|
this.onUnauthorized = config.onUnauthorized;
|
|
1448
1495
|
this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : void 0);
|
|
1449
|
-
|
|
1450
|
-
|
|
1496
|
+
}
|
|
1497
|
+
/**
|
|
1498
|
+
* Open the socket if it is not open (or opening) already.
|
|
1499
|
+
*
|
|
1500
|
+
* Idempotent, synchronous, and safe to call on every operation that needs a
|
|
1501
|
+
* live socket — `initWebSocket` already no-ops on an open socket and is
|
|
1502
|
+
* re-entrant, since the reconnect path has always called it.
|
|
1503
|
+
*/
|
|
1504
|
+
ensureConnected() {
|
|
1505
|
+
if (this.closedByCaller) return;
|
|
1506
|
+
if (!this.WebSocketConstructor) {
|
|
1507
|
+
if (!this.warnedNoWebSocket) {
|
|
1508
|
+
this.warnedNoWebSocket = true;
|
|
1509
|
+
console.warn("WebSocket is not defined in this environment. Realtime subscriptions will not work unless you provide a WebSocket implementation in the config.");
|
|
1510
|
+
}
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1513
|
+
if (this.ws || this.reconnectTimeout) return;
|
|
1514
|
+
this.initWebSocket();
|
|
1451
1515
|
}
|
|
1452
1516
|
/**
|
|
1453
1517
|
* Authenticate the WebSocket connection
|
|
@@ -1497,7 +1561,16 @@ var RebaseWebSocketClient = class {
|
|
|
1497
1561
|
});
|
|
1498
1562
|
}
|
|
1499
1563
|
}
|
|
1500
|
-
|
|
1564
|
+
/**
|
|
1565
|
+
* Drop the socket.
|
|
1566
|
+
*
|
|
1567
|
+
* `permanent` distinguishes the two callers. Signing out drops the socket
|
|
1568
|
+
* but the client stays usable — a later subscribe should reconnect
|
|
1569
|
+
* anonymously. `client.close()` is the caller saying they are done, and
|
|
1570
|
+
* must not be undone by a stray queued frame.
|
|
1571
|
+
*/
|
|
1572
|
+
disconnect(permanent = false) {
|
|
1573
|
+
if (permanent) this.closedByCaller = true;
|
|
1501
1574
|
this.isAuthenticated = false;
|
|
1502
1575
|
this.authPromise = null;
|
|
1503
1576
|
if (this.reconnectTimeout) {
|
|
@@ -1540,6 +1613,7 @@ var RebaseWebSocketClient = class {
|
|
|
1540
1613
|
this.emit(wasReconnect ? "reconnect" : "connect");
|
|
1541
1614
|
this.processMessageQueue();
|
|
1542
1615
|
if (wasReconnect) this.resubscribeAll();
|
|
1616
|
+
this.armPendingSubscribeWatchdogs();
|
|
1543
1617
|
};
|
|
1544
1618
|
this.ws.onmessage = (event) => {
|
|
1545
1619
|
try {
|
|
@@ -1554,6 +1628,7 @@ var RebaseWebSocketClient = class {
|
|
|
1554
1628
|
this.isConnected = false;
|
|
1555
1629
|
this.isAuthenticated = false;
|
|
1556
1630
|
this.authPromise = null;
|
|
1631
|
+
this.suspendSubscribeWatchdogs();
|
|
1557
1632
|
this.emit("disconnect");
|
|
1558
1633
|
for (const [reqId, request] of this.pendingRequests.entries()) {
|
|
1559
1634
|
if (reqId.startsWith("auth_")) request.reject(/* @__PURE__ */ new Error("Connection closed during authentication"));
|
|
@@ -1585,6 +1660,7 @@ var RebaseWebSocketClient = class {
|
|
|
1585
1660
|
attemptReconnect() {
|
|
1586
1661
|
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
1587
1662
|
console.error("Max reconnection attempts reached");
|
|
1663
|
+
this.failAllPendingSubscriptions(new RebaseApiError$1("Connection lost", { code: "CONNECTION_LOST" }));
|
|
1588
1664
|
return;
|
|
1589
1665
|
}
|
|
1590
1666
|
this.reconnectAttempts++;
|
|
@@ -1639,29 +1715,18 @@ var RebaseWebSocketClient = class {
|
|
|
1639
1715
|
subscription.backendSubscriptionId = newBackendId;
|
|
1640
1716
|
backendKeyMap.delete(oldBackendId);
|
|
1641
1717
|
backendKeyMap.set(newBackendId, subscriptionKey);
|
|
1642
|
-
this.
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
...subscription.props,
|
|
1646
|
-
subscriptionId: newBackendId
|
|
1647
|
-
}
|
|
1648
|
-
}).catch((error) => {
|
|
1649
|
-
console.error(`[WS] Failed to re-subscribe ${idPrefix} after auth refresh:`, subscriptionKey, error);
|
|
1650
|
-
subscription.callbacks.forEach((callback) => {
|
|
1651
|
-
if (callback.onError) callback.onError(error);
|
|
1652
|
-
});
|
|
1653
|
-
});
|
|
1654
|
-
} else {
|
|
1655
|
-
const { errorMessage, errorCode } = extractMessageError(message);
|
|
1656
|
-
const error = new RebaseApiError$1(errorMessage, { code: errorCode });
|
|
1657
|
-
subscription.callbacks.forEach((callback) => {
|
|
1658
|
-
if (callback.onError) callback.onError(error);
|
|
1659
|
-
});
|
|
1718
|
+
if (messageType === "subscribe_collection") this.sendCollectionSubscribe(subscriptionKey);
|
|
1719
|
+
else this.sendEntitySubscribe(subscriptionKey);
|
|
1720
|
+
return;
|
|
1660
1721
|
}
|
|
1722
|
+
const { errorMessage, errorCode } = extractMessageError(message);
|
|
1723
|
+
const error = new RebaseApiError$1(errorMessage, { code: errorCode });
|
|
1724
|
+
if (messageType === "subscribe_collection") this.failCollectionSubscription(subscriptionKey, error);
|
|
1725
|
+
else this.failEntitySubscription(subscriptionKey, error);
|
|
1661
1726
|
}).catch((err) => {
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1727
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
1728
|
+
if (messageType === "subscribe_collection") this.failCollectionSubscription(subscriptionKey, error);
|
|
1729
|
+
else this.failEntitySubscription(subscriptionKey, error);
|
|
1665
1730
|
});
|
|
1666
1731
|
}
|
|
1667
1732
|
handleWebSocketMessage(message) {
|
|
@@ -1690,6 +1755,15 @@ var RebaseWebSocketClient = class {
|
|
|
1690
1755
|
}
|
|
1691
1756
|
return;
|
|
1692
1757
|
}
|
|
1758
|
+
if (typeof message.channel === "string" && (type === "broadcast" || type === "presence_state" || type === "presence_diff")) {
|
|
1759
|
+
const handlers = this.channelHandlers.get(message.channel);
|
|
1760
|
+
if (handlers) for (const handler of [...handlers]) try {
|
|
1761
|
+
handler(message);
|
|
1762
|
+
} catch (error) {
|
|
1763
|
+
console.error("Error in channel handler:", error);
|
|
1764
|
+
}
|
|
1765
|
+
return;
|
|
1766
|
+
}
|
|
1693
1767
|
if (subscriptionId && type === "collection_update") {
|
|
1694
1768
|
const subscriptionKey = this.backendToCollectionKey.get(subscriptionId);
|
|
1695
1769
|
if (subscriptionKey) {
|
|
@@ -1702,6 +1776,9 @@ var RebaseWebSocketClient = class {
|
|
|
1702
1776
|
collectionSub.latestData = rows;
|
|
1703
1777
|
collectionSub.lastUpdated = Date.now();
|
|
1704
1778
|
collectionSub.isInitialDataReceived = true;
|
|
1779
|
+
if (collectionSub.subscribeTimeout) clearTimeout(collectionSub.subscribeTimeout);
|
|
1780
|
+
collectionSub.subscribeTimeout = void 0;
|
|
1781
|
+
collectionSub.subscribeInFlight = false;
|
|
1705
1782
|
collectionSub.callbacks.forEach((callback) => {
|
|
1706
1783
|
try {
|
|
1707
1784
|
callback.onUpdate(rows);
|
|
@@ -1757,6 +1834,9 @@ var RebaseWebSocketClient = class {
|
|
|
1757
1834
|
entitySub.latestData = row;
|
|
1758
1835
|
entitySub.lastUpdated = Date.now();
|
|
1759
1836
|
entitySub.isInitialDataReceived = true;
|
|
1837
|
+
if (entitySub.subscribeTimeout) clearTimeout(entitySub.subscribeTimeout);
|
|
1838
|
+
entitySub.subscribeTimeout = void 0;
|
|
1839
|
+
entitySub.subscribeInFlight = false;
|
|
1760
1840
|
entitySub.callbacks.forEach((callback) => {
|
|
1761
1841
|
try {
|
|
1762
1842
|
callback.onUpdate(row);
|
|
@@ -1778,6 +1858,9 @@ var RebaseWebSocketClient = class {
|
|
|
1778
1858
|
this.resubscribeAfterAuthRefresh(message, collectionSub, collectionKey, "collection", this.backendToCollectionKey, "subscribe_collection");
|
|
1779
1859
|
return;
|
|
1780
1860
|
}
|
|
1861
|
+
if (collectionSub.subscribeTimeout) clearTimeout(collectionSub.subscribeTimeout);
|
|
1862
|
+
collectionSub.subscribeTimeout = void 0;
|
|
1863
|
+
collectionSub.subscribeInFlight = false;
|
|
1781
1864
|
const { errorMessage, errorCode } = extractMessageError(message);
|
|
1782
1865
|
const error = new RebaseApiError$1(errorMessage, { code: errorCode });
|
|
1783
1866
|
collectionSub.callbacks.forEach((callback) => {
|
|
@@ -1794,6 +1877,9 @@ var RebaseWebSocketClient = class {
|
|
|
1794
1877
|
this.resubscribeAfterAuthRefresh(message, entitySub, entityKey, "row", this.backendToEntityKey, "subscribe_one");
|
|
1795
1878
|
return;
|
|
1796
1879
|
}
|
|
1880
|
+
if (entitySub.subscribeTimeout) clearTimeout(entitySub.subscribeTimeout);
|
|
1881
|
+
entitySub.subscribeTimeout = void 0;
|
|
1882
|
+
entitySub.subscribeInFlight = false;
|
|
1797
1883
|
const { errorMessage, errorCode } = extractMessageError(message);
|
|
1798
1884
|
const error = new RebaseApiError$1(errorMessage, { code: errorCode });
|
|
1799
1885
|
entitySub.callbacks.forEach((callback) => {
|
|
@@ -1866,21 +1952,28 @@ var RebaseWebSocketClient = class {
|
|
|
1866
1952
|
throw error;
|
|
1867
1953
|
}
|
|
1868
1954
|
}
|
|
1955
|
+
/**
|
|
1956
|
+
* Public because `RebaseRealtimeChannel` sends channel frames through it.
|
|
1957
|
+
* Not part of the stable surface — prefer `client.realtime.channel(name)`.
|
|
1958
|
+
*/
|
|
1869
1959
|
sendMessage(message) {
|
|
1870
1960
|
const queuedMsg = message;
|
|
1871
1961
|
if (queuedMsg._queuedResolve && queuedMsg._queuedReject) return this.doSendMessage(message, queuedMsg._queuedResolve, queuedMsg._queuedReject);
|
|
1872
|
-
if (!this.isConnected || !this.ws)
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1962
|
+
if (!this.isConnected || !this.ws) {
|
|
1963
|
+
this.ensureConnected();
|
|
1964
|
+
return new Promise((resolve, reject) => {
|
|
1965
|
+
const queueable = message;
|
|
1966
|
+
queueable._queuedResolve = resolve;
|
|
1967
|
+
queueable._queuedReject = reject;
|
|
1968
|
+
this.messageQueue.push(message);
|
|
1969
|
+
});
|
|
1970
|
+
}
|
|
1878
1971
|
return new Promise((resolve, reject) => {
|
|
1879
1972
|
this.doSendMessage(message, resolve, reject);
|
|
1880
1973
|
});
|
|
1881
1974
|
}
|
|
1882
1975
|
async doSendMessage(message, resolve, reject) {
|
|
1883
|
-
if (message.type !== "AUTHENTICATE" && this.getAuthToken && !this.isAuthenticated) try {
|
|
1976
|
+
if (message.type !== "AUTHENTICATE" && !CHANNEL_MESSAGE_TYPES.has(message.type) && this.getAuthToken && !this.isAuthenticated) try {
|
|
1884
1977
|
await this.ensureAuthenticated();
|
|
1885
1978
|
} catch (error) {
|
|
1886
1979
|
reject(new RebaseApiError$1(error instanceof Error ? error.message : "Authentication required"));
|
|
@@ -1888,17 +1981,7 @@ var RebaseWebSocketClient = class {
|
|
|
1888
1981
|
}
|
|
1889
1982
|
const requestId = message.requestId || `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
1890
1983
|
message.requestId = requestId;
|
|
1891
|
-
const expectsResponse = !
|
|
1892
|
-
"subscribe_collection",
|
|
1893
|
-
"subscribe_one",
|
|
1894
|
-
"unsubscribe",
|
|
1895
|
-
"join_channel",
|
|
1896
|
-
"leave_channel",
|
|
1897
|
-
"broadcast",
|
|
1898
|
-
"presence_track",
|
|
1899
|
-
"presence_untrack",
|
|
1900
|
-
"presence_state"
|
|
1901
|
-
].includes(message.type);
|
|
1984
|
+
const expectsResponse = !(message.type === "subscribe_collection" || message.type === "subscribe_one" || message.type === "unsubscribe" || CHANNEL_MESSAGE_TYPES.has(message.type));
|
|
1902
1985
|
if (expectsResponse && !this.pendingRequests.has(requestId)) {
|
|
1903
1986
|
const timeoutHandle = setTimeout(() => {
|
|
1904
1987
|
if (this.pendingRequests.has(requestId)) {
|
|
@@ -2127,6 +2210,7 @@ var RebaseWebSocketClient = class {
|
|
|
2127
2210
|
});
|
|
2128
2211
|
}
|
|
2129
2212
|
listenCollection(props, onUpdate, onError) {
|
|
2213
|
+
this.ensureConnected();
|
|
2130
2214
|
const subscriptionKey = this.createCollectionSubscriptionKey(props);
|
|
2131
2215
|
const callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
2132
2216
|
const existingSubscription = this.collectionSubscriptions.get(subscriptionKey);
|
|
@@ -2142,9 +2226,12 @@ var RebaseWebSocketClient = class {
|
|
|
2142
2226
|
console.error("Error in collection subscription callback:", error);
|
|
2143
2227
|
if (onError) onError(error instanceof Error ? error : new Error(String(error)));
|
|
2144
2228
|
}
|
|
2229
|
+
else if (!existingSubscription.subscribeInFlight) this.sendCollectionSubscribe(subscriptionKey);
|
|
2145
2230
|
return () => {
|
|
2146
2231
|
callbackMap.delete(callbackId);
|
|
2147
2232
|
if (callbackMap.size === 0) {
|
|
2233
|
+
if (this.collectionSubscriptions.get(subscriptionKey) !== existingSubscription) return;
|
|
2234
|
+
if (existingSubscription.subscribeTimeout) clearTimeout(existingSubscription.subscribeTimeout);
|
|
2148
2235
|
this.collectionSubscriptions.delete(subscriptionKey);
|
|
2149
2236
|
this.backendToCollectionKey.delete(existingSubscription.backendSubscriptionId);
|
|
2150
2237
|
if (this.isConnected && this.ws) this.sendMessage({
|
|
@@ -2166,21 +2253,14 @@ var RebaseWebSocketClient = class {
|
|
|
2166
2253
|
props
|
|
2167
2254
|
});
|
|
2168
2255
|
this.backendToCollectionKey.set(backendSubscriptionId, subscriptionKey);
|
|
2169
|
-
this.
|
|
2170
|
-
type: "subscribe_collection",
|
|
2171
|
-
payload: {
|
|
2172
|
-
...props,
|
|
2173
|
-
subscriptionId: backendSubscriptionId
|
|
2174
|
-
}
|
|
2175
|
-
}).catch((error) => {
|
|
2176
|
-
if (onError) onError(error);
|
|
2177
|
-
});
|
|
2256
|
+
this.sendCollectionSubscribe(subscriptionKey);
|
|
2178
2257
|
return () => {
|
|
2179
2258
|
const subscription = this.collectionSubscriptions.get(subscriptionKey);
|
|
2180
2259
|
if (subscription) {
|
|
2181
2260
|
const callbacks = subscription.callbacks;
|
|
2182
2261
|
callbacks.delete(callbackId);
|
|
2183
2262
|
if (callbacks.size === 0) {
|
|
2263
|
+
if (subscription.subscribeTimeout) clearTimeout(subscription.subscribeTimeout);
|
|
2184
2264
|
this.collectionSubscriptions.delete(subscriptionKey);
|
|
2185
2265
|
this.backendToCollectionKey.delete(subscription.backendSubscriptionId);
|
|
2186
2266
|
if (this.isConnected && this.ws) this.sendMessage({
|
|
@@ -2192,6 +2272,7 @@ var RebaseWebSocketClient = class {
|
|
|
2192
2272
|
};
|
|
2193
2273
|
}
|
|
2194
2274
|
listenOne(props, onUpdate, onError) {
|
|
2275
|
+
this.ensureConnected();
|
|
2195
2276
|
const subscriptionKey = this.createSingleSubscriptionKey(props);
|
|
2196
2277
|
const callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
2197
2278
|
const existingSubscription = this.singleSubscriptions.get(subscriptionKey);
|
|
@@ -2207,9 +2288,12 @@ var RebaseWebSocketClient = class {
|
|
|
2207
2288
|
console.error("Error in row subscription callback:", error);
|
|
2208
2289
|
if (onError) onError(error instanceof Error ? error : new Error(String(error)));
|
|
2209
2290
|
}
|
|
2291
|
+
else if (!existingSubscription.subscribeInFlight) this.sendEntitySubscribe(subscriptionKey);
|
|
2210
2292
|
return () => {
|
|
2211
2293
|
callbackMap.delete(callbackId);
|
|
2212
2294
|
if (callbackMap.size === 0) {
|
|
2295
|
+
if (this.singleSubscriptions.get(subscriptionKey) !== existingSubscription) return;
|
|
2296
|
+
if (existingSubscription.subscribeTimeout) clearTimeout(existingSubscription.subscribeTimeout);
|
|
2213
2297
|
this.singleSubscriptions.delete(subscriptionKey);
|
|
2214
2298
|
this.backendToEntityKey.delete(existingSubscription.backendSubscriptionId);
|
|
2215
2299
|
if (this.isConnected && this.ws) this.sendMessage({
|
|
@@ -2231,15 +2315,7 @@ var RebaseWebSocketClient = class {
|
|
|
2231
2315
|
props
|
|
2232
2316
|
});
|
|
2233
2317
|
this.backendToEntityKey.set(backendSubscriptionId, subscriptionKey);
|
|
2234
|
-
this.
|
|
2235
|
-
type: "subscribe_one",
|
|
2236
|
-
payload: {
|
|
2237
|
-
...props,
|
|
2238
|
-
subscriptionId: backendSubscriptionId
|
|
2239
|
-
}
|
|
2240
|
-
}).catch((error) => {
|
|
2241
|
-
if (onError) onError(error);
|
|
2242
|
-
});
|
|
2318
|
+
this.sendEntitySubscribe(subscriptionKey);
|
|
2243
2319
|
return () => {
|
|
2244
2320
|
const subscription = this.singleSubscriptions.get(subscriptionKey);
|
|
2245
2321
|
if (subscription) {
|
|
@@ -2257,6 +2333,157 @@ var RebaseWebSocketClient = class {
|
|
|
2257
2333
|
};
|
|
2258
2334
|
}
|
|
2259
2335
|
/**
|
|
2336
|
+
* Send a `subscribe_collection` for an already-registered subscription and
|
|
2337
|
+
* arm its watchdog.
|
|
2338
|
+
*
|
|
2339
|
+
* Every path that registers a collection subscription goes through here, so
|
|
2340
|
+
* that a subscribe which never lands — a rejected send, or a server that
|
|
2341
|
+
* never answers — always ends up in `failCollectionSubscription` rather than
|
|
2342
|
+
* leaving the entry parked with `isInitialDataReceived === false` forever.
|
|
2343
|
+
*/
|
|
2344
|
+
sendCollectionSubscribe(subscriptionKey) {
|
|
2345
|
+
const subscription = this.collectionSubscriptions.get(subscriptionKey);
|
|
2346
|
+
if (!subscription) return;
|
|
2347
|
+
const backendSubscriptionId = subscription.backendSubscriptionId;
|
|
2348
|
+
subscription.subscribeInFlight = true;
|
|
2349
|
+
if (subscription.subscribeTimeout) clearTimeout(subscription.subscribeTimeout);
|
|
2350
|
+
subscription.subscribeTimeout = void 0;
|
|
2351
|
+
if (this.isConnected) this.sendCollectionSubscribeWatchdog(subscriptionKey);
|
|
2352
|
+
this.sendMessage({
|
|
2353
|
+
type: "subscribe_collection",
|
|
2354
|
+
payload: {
|
|
2355
|
+
...subscription.props,
|
|
2356
|
+
subscriptionId: backendSubscriptionId
|
|
2357
|
+
}
|
|
2358
|
+
}).catch((error) => {
|
|
2359
|
+
const current = this.collectionSubscriptions.get(subscriptionKey);
|
|
2360
|
+
if (!current || current.backendSubscriptionId !== backendSubscriptionId) return;
|
|
2361
|
+
this.failCollectionSubscription(subscriptionKey, error instanceof Error ? error : new Error(String(error)));
|
|
2362
|
+
});
|
|
2363
|
+
}
|
|
2364
|
+
/** The `listenOne` counterpart of {@link sendCollectionSubscribe}. */
|
|
2365
|
+
sendEntitySubscribe(subscriptionKey) {
|
|
2366
|
+
const subscription = this.singleSubscriptions.get(subscriptionKey);
|
|
2367
|
+
if (!subscription) return;
|
|
2368
|
+
const backendSubscriptionId = subscription.backendSubscriptionId;
|
|
2369
|
+
subscription.subscribeInFlight = true;
|
|
2370
|
+
if (subscription.subscribeTimeout) clearTimeout(subscription.subscribeTimeout);
|
|
2371
|
+
subscription.subscribeTimeout = void 0;
|
|
2372
|
+
if (this.isConnected) this.sendEntitySubscribeWatchdog(subscriptionKey);
|
|
2373
|
+
this.sendMessage({
|
|
2374
|
+
type: "subscribe_one",
|
|
2375
|
+
payload: {
|
|
2376
|
+
...subscription.props,
|
|
2377
|
+
subscriptionId: backendSubscriptionId
|
|
2378
|
+
}
|
|
2379
|
+
}).catch((error) => {
|
|
2380
|
+
const current = this.singleSubscriptions.get(subscriptionKey);
|
|
2381
|
+
if (!current || current.backendSubscriptionId !== backendSubscriptionId) return;
|
|
2382
|
+
this.failEntitySubscription(subscriptionKey, error instanceof Error ? error : new Error(String(error)));
|
|
2383
|
+
});
|
|
2384
|
+
}
|
|
2385
|
+
/**
|
|
2386
|
+
* Report a subscribe failure to every listener and drop the registration.
|
|
2387
|
+
*
|
|
2388
|
+
* Dropping it is the point: the callbacks stay live (their components are
|
|
2389
|
+
* still mounted and have been told), but the next `listenCollection` for
|
|
2390
|
+
* these params finds no entry and issues a fresh subscribe instead of
|
|
2391
|
+
* silently attaching to a dead one.
|
|
2392
|
+
*/
|
|
2393
|
+
failCollectionSubscription(subscriptionKey, error) {
|
|
2394
|
+
const subscription = this.collectionSubscriptions.get(subscriptionKey);
|
|
2395
|
+
if (!subscription) return;
|
|
2396
|
+
if (subscription.subscribeTimeout) clearTimeout(subscription.subscribeTimeout);
|
|
2397
|
+
subscription.subscribeInFlight = false;
|
|
2398
|
+
this.collectionSubscriptions.delete(subscriptionKey);
|
|
2399
|
+
this.backendToCollectionKey.delete(subscription.backendSubscriptionId);
|
|
2400
|
+
subscription.callbacks.forEach((callback) => {
|
|
2401
|
+
if (callback.onError) try {
|
|
2402
|
+
callback.onError(error);
|
|
2403
|
+
} catch (callbackError) {
|
|
2404
|
+
console.error("Error in collection subscription error callback:", callbackError);
|
|
2405
|
+
}
|
|
2406
|
+
});
|
|
2407
|
+
}
|
|
2408
|
+
/** The `listenOne` counterpart of {@link failCollectionSubscription}. */
|
|
2409
|
+
failEntitySubscription(subscriptionKey, error) {
|
|
2410
|
+
const subscription = this.singleSubscriptions.get(subscriptionKey);
|
|
2411
|
+
if (!subscription) return;
|
|
2412
|
+
if (subscription.subscribeTimeout) clearTimeout(subscription.subscribeTimeout);
|
|
2413
|
+
subscription.subscribeInFlight = false;
|
|
2414
|
+
this.singleSubscriptions.delete(subscriptionKey);
|
|
2415
|
+
this.backendToEntityKey.delete(subscription.backendSubscriptionId);
|
|
2416
|
+
subscription.callbacks.forEach((callback) => {
|
|
2417
|
+
if (callback.onError) try {
|
|
2418
|
+
callback.onError(error);
|
|
2419
|
+
} catch (callbackError) {
|
|
2420
|
+
console.error("Error in row subscription error callback:", callbackError);
|
|
2421
|
+
}
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
/**
|
|
2425
|
+
* Stop the watchdogs without failing anything — used when the socket drops,
|
|
2426
|
+
* since the reconnect path re-subscribes everything anyway and a watchdog
|
|
2427
|
+
* firing mid-reconnect would tear down healthy subscriptions.
|
|
2428
|
+
*/
|
|
2429
|
+
suspendSubscribeWatchdogs() {
|
|
2430
|
+
for (const sub of this.collectionSubscriptions.values()) {
|
|
2431
|
+
if (sub.subscribeTimeout) clearTimeout(sub.subscribeTimeout);
|
|
2432
|
+
sub.subscribeTimeout = void 0;
|
|
2433
|
+
sub.subscribeInFlight = false;
|
|
2434
|
+
}
|
|
2435
|
+
for (const sub of this.singleSubscriptions.values()) {
|
|
2436
|
+
if (sub.subscribeTimeout) clearTimeout(sub.subscribeTimeout);
|
|
2437
|
+
sub.subscribeTimeout = void 0;
|
|
2438
|
+
sub.subscribeInFlight = false;
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
/**
|
|
2442
|
+
* Arm watchdogs for subscribes that were requested while offline and have
|
|
2443
|
+
* just been flushed to the socket. Their timers were deliberately not set at
|
|
2444
|
+
* request time, so without this they would have no timeout at all.
|
|
2445
|
+
*/
|
|
2446
|
+
armPendingSubscribeWatchdogs() {
|
|
2447
|
+
for (const [key, sub] of this.collectionSubscriptions.entries()) if (sub.subscribeInFlight && !sub.subscribeTimeout) this.sendCollectionSubscribeWatchdog(key);
|
|
2448
|
+
for (const [key, sub] of this.singleSubscriptions.entries()) if (sub.subscribeInFlight && !sub.subscribeTimeout) this.sendEntitySubscribeWatchdog(key);
|
|
2449
|
+
}
|
|
2450
|
+
sendCollectionSubscribeWatchdog(subscriptionKey) {
|
|
2451
|
+
const subscription = this.collectionSubscriptions.get(subscriptionKey);
|
|
2452
|
+
if (!subscription) return;
|
|
2453
|
+
const backendSubscriptionId = subscription.backendSubscriptionId;
|
|
2454
|
+
subscription.subscribeTimeout = setTimeout(() => {
|
|
2455
|
+
const current = this.collectionSubscriptions.get(subscriptionKey);
|
|
2456
|
+
if (!current || current.backendSubscriptionId !== backendSubscriptionId) return;
|
|
2457
|
+
if (!current.subscribeInFlight) return;
|
|
2458
|
+
this.failCollectionSubscription(subscriptionKey, new RebaseApiError$1("Subscription timed out", { code: "SUBSCRIPTION_TIMEOUT" }));
|
|
2459
|
+
}, this.subscriptionTimeoutMs);
|
|
2460
|
+
}
|
|
2461
|
+
sendEntitySubscribeWatchdog(subscriptionKey) {
|
|
2462
|
+
const subscription = this.singleSubscriptions.get(subscriptionKey);
|
|
2463
|
+
if (!subscription) return;
|
|
2464
|
+
const backendSubscriptionId = subscription.backendSubscriptionId;
|
|
2465
|
+
subscription.subscribeTimeout = setTimeout(() => {
|
|
2466
|
+
const current = this.singleSubscriptions.get(subscriptionKey);
|
|
2467
|
+
if (!current || current.backendSubscriptionId !== backendSubscriptionId) return;
|
|
2468
|
+
if (!current.subscribeInFlight) return;
|
|
2469
|
+
this.failEntitySubscription(subscriptionKey, new RebaseApiError$1("Subscription timed out", { code: "SUBSCRIPTION_TIMEOUT" }));
|
|
2470
|
+
}, this.subscriptionTimeoutMs);
|
|
2471
|
+
}
|
|
2472
|
+
/**
|
|
2473
|
+
* Fail every subscription that never received data. Called when reconnection
|
|
2474
|
+
* is given up on, so views surface an error instead of spinning forever.
|
|
2475
|
+
*/
|
|
2476
|
+
failAllPendingSubscriptions(error) {
|
|
2477
|
+
for (const key of [...this.collectionSubscriptions.keys()]) {
|
|
2478
|
+
const sub = this.collectionSubscriptions.get(key);
|
|
2479
|
+
if (sub && !sub.isInitialDataReceived) this.failCollectionSubscription(key, error);
|
|
2480
|
+
}
|
|
2481
|
+
for (const key of [...this.singleSubscriptions.keys()]) {
|
|
2482
|
+
const sub = this.singleSubscriptions.get(key);
|
|
2483
|
+
if (sub && !sub.isInitialDataReceived) this.failEntitySubscription(key, error);
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
/**
|
|
2260
2487
|
* Re-send all active subscriptions to the backend after a reconnect.
|
|
2261
2488
|
* The server wipes subscription state when a client disconnects, so
|
|
2262
2489
|
* we need to re-register everything to resume receiving updates.
|
|
@@ -2269,15 +2496,7 @@ var RebaseWebSocketClient = class {
|
|
|
2269
2496
|
sub.backendSubscriptionId = newBackendId;
|
|
2270
2497
|
this.backendToCollectionKey.delete(oldBackendId);
|
|
2271
2498
|
this.backendToCollectionKey.set(newBackendId, key);
|
|
2272
|
-
this.
|
|
2273
|
-
type: "subscribe_collection",
|
|
2274
|
-
payload: {
|
|
2275
|
-
...sub.props,
|
|
2276
|
-
subscriptionId: newBackendId
|
|
2277
|
-
}
|
|
2278
|
-
}).catch((error) => {
|
|
2279
|
-
console.error("[WS] Failed to re-subscribe collection:", key, error);
|
|
2280
|
-
});
|
|
2499
|
+
this.sendCollectionSubscribe(key);
|
|
2281
2500
|
}
|
|
2282
2501
|
for (const [key, sub] of this.singleSubscriptions.entries()) {
|
|
2283
2502
|
const oldBackendId = sub.backendSubscriptionId;
|
|
@@ -2285,15 +2504,7 @@ var RebaseWebSocketClient = class {
|
|
|
2285
2504
|
sub.backendSubscriptionId = newBackendId;
|
|
2286
2505
|
this.backendToEntityKey.delete(oldBackendId);
|
|
2287
2506
|
this.backendToEntityKey.set(newBackendId, key);
|
|
2288
|
-
this.
|
|
2289
|
-
type: "subscribe_one",
|
|
2290
|
-
payload: {
|
|
2291
|
-
...sub.props,
|
|
2292
|
-
subscriptionId: newBackendId
|
|
2293
|
-
}
|
|
2294
|
-
}).catch((error) => {
|
|
2295
|
-
console.error("[WS] Failed to re-subscribe row:", key, error);
|
|
2296
|
-
});
|
|
2507
|
+
this.sendEntitySubscribe(key);
|
|
2297
2508
|
}
|
|
2298
2509
|
}
|
|
2299
2510
|
createCollectionSubscriptionKey(props) {
|
|
@@ -2320,6 +2531,179 @@ var RebaseWebSocketClient = class {
|
|
|
2320
2531
|
}
|
|
2321
2532
|
};
|
|
2322
2533
|
//#endregion
|
|
2534
|
+
//#region src/realtime-channel.ts
|
|
2535
|
+
/**
|
|
2536
|
+
* Re-send presence comfortably inside the server's 30s expiry.
|
|
2537
|
+
*
|
|
2538
|
+
* Two-thirds of the window: one lost heartbeat still leaves time for the next
|
|
2539
|
+
* before the entry is reaped, so a single dropped frame is not a disappearance.
|
|
2540
|
+
*/
|
|
2541
|
+
var PRESENCE_HEARTBEAT_MS = 2e4;
|
|
2542
|
+
var RebaseRealtimeChannel = class {
|
|
2543
|
+
name;
|
|
2544
|
+
transport;
|
|
2545
|
+
presenceHandlers = /* @__PURE__ */ new Set();
|
|
2546
|
+
broadcastHandlers = /* @__PURE__ */ new Set();
|
|
2547
|
+
unsubscribers = [];
|
|
2548
|
+
/** Last known roster, kept so handlers always get a full picture. */
|
|
2549
|
+
presences = {};
|
|
2550
|
+
/** What this client last tracked, replayed on reconnect and heartbeat. */
|
|
2551
|
+
trackedState = null;
|
|
2552
|
+
heartbeat = null;
|
|
2553
|
+
joined = false;
|
|
2554
|
+
constructor(name, transport) {
|
|
2555
|
+
this.name = name;
|
|
2556
|
+
this.transport = transport;
|
|
2557
|
+
}
|
|
2558
|
+
/**
|
|
2559
|
+
* Join the channel and ask for the current roster.
|
|
2560
|
+
*
|
|
2561
|
+
* Called automatically by `track`, `broadcast`, `onPresence` and
|
|
2562
|
+
* `onBroadcast`; calling it directly is only needed to start receiving
|
|
2563
|
+
* before there is anything to send.
|
|
2564
|
+
*/
|
|
2565
|
+
/**
|
|
2566
|
+
* Send a channel message.
|
|
2567
|
+
*
|
|
2568
|
+
* Every channel message is read by the server out of a `payload` envelope
|
|
2569
|
+
* (`payload?.channel`, `payload?.state`, `payload?.event`). Sending those
|
|
2570
|
+
* fields flat does not error: `payload?.channel` simply reads as
|
|
2571
|
+
* `undefined`, so the client is registered into channel `undefined` with
|
|
2572
|
+
* empty state, and the echo comes back with no `channel` for
|
|
2573
|
+
* `onChannelMessage` to match — presence and broadcast both go quiet with
|
|
2574
|
+
* nothing logged. Funnelled through one place so a new message type cannot
|
|
2575
|
+
* reintroduce that.
|
|
2576
|
+
*/
|
|
2577
|
+
send(type, fields = {}) {
|
|
2578
|
+
return this.transport.sendMessage({
|
|
2579
|
+
type,
|
|
2580
|
+
payload: {
|
|
2581
|
+
channel: this.name,
|
|
2582
|
+
...fields
|
|
2583
|
+
}
|
|
2584
|
+
});
|
|
2585
|
+
}
|
|
2586
|
+
async join() {
|
|
2587
|
+
if (this.joined) return;
|
|
2588
|
+
this.joined = true;
|
|
2589
|
+
this.unsubscribers.push(this.transport.onChannelMessage(this.name, (message) => this.handle(message)));
|
|
2590
|
+
this.unsubscribers.push(this.transport.onReconnect(() => {
|
|
2591
|
+
this.rejoin();
|
|
2592
|
+
}));
|
|
2593
|
+
await this.send("join_channel");
|
|
2594
|
+
await this.send("presence_state");
|
|
2595
|
+
}
|
|
2596
|
+
async rejoin() {
|
|
2597
|
+
try {
|
|
2598
|
+
await this.send("join_channel");
|
|
2599
|
+
await this.send("presence_state");
|
|
2600
|
+
if (this.trackedState) await this.send("presence_track", { state: this.trackedState });
|
|
2601
|
+
} catch {}
|
|
2602
|
+
}
|
|
2603
|
+
/**
|
|
2604
|
+
* Publish this client's presence state, and keep publishing it.
|
|
2605
|
+
*
|
|
2606
|
+
* Calling `track` again replaces the state (and restarts the heartbeat),
|
|
2607
|
+
* which is how you update e.g. a cursor position.
|
|
2608
|
+
*/
|
|
2609
|
+
async track(state) {
|
|
2610
|
+
await this.join();
|
|
2611
|
+
this.trackedState = state;
|
|
2612
|
+
await this.send("presence_track", { state });
|
|
2613
|
+
if (!this.heartbeat) {
|
|
2614
|
+
this.heartbeat = setInterval(() => {
|
|
2615
|
+
if (!this.trackedState) return;
|
|
2616
|
+
this.send("presence_track", { state: this.trackedState }).catch(() => {});
|
|
2617
|
+
}, PRESENCE_HEARTBEAT_MS);
|
|
2618
|
+
this.heartbeat.unref?.();
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
/** Stop publishing presence, without leaving the channel. */
|
|
2622
|
+
async untrack() {
|
|
2623
|
+
this.stopHeartbeat();
|
|
2624
|
+
this.trackedState = null;
|
|
2625
|
+
if (this.joined) await this.send("presence_untrack");
|
|
2626
|
+
}
|
|
2627
|
+
/**
|
|
2628
|
+
* Observe the roster. The handler fires immediately with what is already
|
|
2629
|
+
* known, then on every change.
|
|
2630
|
+
*/
|
|
2631
|
+
onPresence(handler) {
|
|
2632
|
+
this.presenceHandlers.add(handler);
|
|
2633
|
+
this.join();
|
|
2634
|
+
if (Object.keys(this.presences).length > 0) handler({ ...this.presences });
|
|
2635
|
+
return () => this.presenceHandlers.delete(handler);
|
|
2636
|
+
}
|
|
2637
|
+
/** Send a broadcast. The sender does not receive its own message. */
|
|
2638
|
+
async broadcast(event, payload) {
|
|
2639
|
+
await this.join();
|
|
2640
|
+
await this.send("broadcast", {
|
|
2641
|
+
event,
|
|
2642
|
+
payload
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
onBroadcast(eventOrHandler, maybeHandler) {
|
|
2646
|
+
const wrapped = typeof eventOrHandler === "string" ? (e) => {
|
|
2647
|
+
if (e.event === eventOrHandler) maybeHandler(e.payload);
|
|
2648
|
+
} : eventOrHandler;
|
|
2649
|
+
this.broadcastHandlers.add(wrapped);
|
|
2650
|
+
this.join();
|
|
2651
|
+
return () => this.broadcastHandlers.delete(wrapped);
|
|
2652
|
+
}
|
|
2653
|
+
/** Leave the channel and release every listener and timer. */
|
|
2654
|
+
async leave() {
|
|
2655
|
+
this.stopHeartbeat();
|
|
2656
|
+
this.trackedState = null;
|
|
2657
|
+
this.presences = {};
|
|
2658
|
+
this.presenceHandlers.clear();
|
|
2659
|
+
this.broadcastHandlers.clear();
|
|
2660
|
+
for (const off of this.unsubscribers) off();
|
|
2661
|
+
this.unsubscribers = [];
|
|
2662
|
+
if (this.joined) {
|
|
2663
|
+
this.joined = false;
|
|
2664
|
+
await this.send("leave_channel");
|
|
2665
|
+
}
|
|
2666
|
+
}
|
|
2667
|
+
stopHeartbeat() {
|
|
2668
|
+
if (this.heartbeat) {
|
|
2669
|
+
clearInterval(this.heartbeat);
|
|
2670
|
+
this.heartbeat = null;
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
/** Fold an incoming frame into the roster and fan it out. */
|
|
2674
|
+
handle(message) {
|
|
2675
|
+
switch (message.type) {
|
|
2676
|
+
case "presence_state":
|
|
2677
|
+
this.presences = message.presences ?? {};
|
|
2678
|
+
this.emitPresence();
|
|
2679
|
+
break;
|
|
2680
|
+
case "presence_diff": {
|
|
2681
|
+
const joins = message.joins ?? {};
|
|
2682
|
+
const leaves = message.leaves ?? {};
|
|
2683
|
+
for (const [id, state] of Object.entries(joins)) this.presences[id] = state;
|
|
2684
|
+
for (const id of Object.keys(leaves)) delete this.presences[id];
|
|
2685
|
+
this.emitPresence({
|
|
2686
|
+
joins,
|
|
2687
|
+
leaves
|
|
2688
|
+
});
|
|
2689
|
+
break;
|
|
2690
|
+
}
|
|
2691
|
+
case "broadcast": {
|
|
2692
|
+
const event = {
|
|
2693
|
+
event: message.event,
|
|
2694
|
+
payload: message.payload
|
|
2695
|
+
};
|
|
2696
|
+
for (const handler of this.broadcastHandlers) handler(event);
|
|
2697
|
+
break;
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
}
|
|
2701
|
+
emitPresence(diff) {
|
|
2702
|
+
const snapshot = { ...this.presences };
|
|
2703
|
+
for (const handler of this.presenceHandlers) handler(snapshot, diff);
|
|
2704
|
+
}
|
|
2705
|
+
};
|
|
2706
|
+
//#endregion
|
|
2323
2707
|
//#region src/index.ts
|
|
2324
2708
|
/**
|
|
2325
2709
|
* Derive a WebSocket URL from an HTTP base URL.
|
|
@@ -2370,6 +2754,8 @@ function createRebaseClient(options) {
|
|
|
2370
2754
|
};
|
|
2371
2755
|
const resolvedWsUrl = options.realtime !== false ? options.websocketUrl ?? deriveWebSocketUrl(options.baseUrl) : void 0;
|
|
2372
2756
|
let ws;
|
|
2757
|
+
/** One channel object per name — see `realtime.channel`. */
|
|
2758
|
+
const realtimeChannels = /* @__PURE__ */ new Map();
|
|
2373
2759
|
if (resolvedWsUrl) {
|
|
2374
2760
|
ws = new RebaseWebSocketClient({
|
|
2375
2761
|
websocketUrl: resolvedWsUrl,
|
|
@@ -2393,7 +2779,7 @@ function createRebaseClient(options) {
|
|
|
2393
2779
|
if (!ws) return;
|
|
2394
2780
|
if (event === "SIGNED_OUT") ws.disconnect();
|
|
2395
2781
|
else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
|
|
2396
|
-
if (session?.accessToken) ws.authenticate(session.accessToken).catch(console.warn);
|
|
2782
|
+
if (session?.accessToken && ws.hasSocket) ws.authenticate(session.accessToken).catch(console.warn);
|
|
2397
2783
|
}
|
|
2398
2784
|
});
|
|
2399
2785
|
}
|
|
@@ -2480,6 +2866,24 @@ function createRebaseClient(options) {
|
|
|
2480
2866
|
createStorageSource,
|
|
2481
2867
|
fetchStorageSources,
|
|
2482
2868
|
ws,
|
|
2869
|
+
realtime: {
|
|
2870
|
+
/**
|
|
2871
|
+
* Join a broadcast/presence channel.
|
|
2872
|
+
*
|
|
2873
|
+
* Repeated calls with the same name return the same channel, so
|
|
2874
|
+
* separate components can attach handlers without each opening its
|
|
2875
|
+
* own membership — and `leave()` from one would otherwise silently
|
|
2876
|
+
* cut off the others.
|
|
2877
|
+
*/
|
|
2878
|
+
channel: (name) => {
|
|
2879
|
+
if (!ws) throw new RebaseClientError("Realtime is disabled on this client (realtime: false), so channels are unavailable.");
|
|
2880
|
+
let existing = realtimeChannels.get(name);
|
|
2881
|
+
if (!existing) {
|
|
2882
|
+
existing = new RebaseRealtimeChannel(name, ws);
|
|
2883
|
+
realtimeChannels.set(name, existing);
|
|
2884
|
+
}
|
|
2885
|
+
return existing;
|
|
2886
|
+
} },
|
|
2483
2887
|
/**
|
|
2484
2888
|
* Release the realtime socket and its reconnect timer.
|
|
2485
2889
|
*
|
|
@@ -2488,7 +2892,9 @@ function createRebaseClient(options) {
|
|
|
2488
2892
|
* was never started, and safe to call twice.
|
|
2489
2893
|
*/
|
|
2490
2894
|
close: () => {
|
|
2491
|
-
|
|
2895
|
+
for (const channel of realtimeChannels.values()) channel.leave();
|
|
2896
|
+
realtimeChannels.clear();
|
|
2897
|
+
ws?.disconnect(true);
|
|
2492
2898
|
},
|
|
2493
2899
|
setToken: transport.setToken,
|
|
2494
2900
|
setAuthTokenGetter: transport.setAuthTokenGetter,
|
|
@@ -2508,6 +2914,6 @@ function createRebaseClient(options) {
|
|
|
2508
2914
|
};
|
|
2509
2915
|
}
|
|
2510
2916
|
//#endregion
|
|
2511
|
-
export { QueryBuilder, RebaseApiError, RebaseClientError, RebaseWebSocketClient, and, cond, createBackups, createCookieStorage, createMemoryStorage, createRebaseClient, or };
|
|
2917
|
+
export { QueryBuilder, RebaseApiError, RebaseClientError, RebaseRealtimeChannel, RebaseWebSocketClient, and, cond, createBackups, createCookieStorage, createMemoryStorage, createRebaseClient, or };
|
|
2512
2918
|
|
|
2513
2919
|
//# sourceMappingURL=index.es.js.map
|