@rebasepro/client 0.25.1 → 0.27.0

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.es.js CHANGED
@@ -1,7 +1,119 @@
1
1
  import { c as invalidBulkBody, d as RebaseApiError, h as parseRebaseJson, i as isOfflineError, l as SDKQueryBuilder, m as defaultCodeForStatus, n as MemoryOfflineStore, o as createCollectionClient, p as createTransport, s as etagOf, u as RebaseClientError } from "./offline-store-BhYXViha.js";
2
- import { DEFAULT_STORAGE_SOURCE_KEY, PUBLIC_STORAGE_PREFIX, RebaseApiError as RebaseApiError$1, RebaseClientError as RebaseClientError$1, STORAGE_REFERENCE_SCHEME, isPublicStoragePath, isStorageReference, isUnsupported, parseStorageReference, resolveStorageReferences, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText } from "@rebasepro/types";
2
+ import { DEFAULT_STORAGE_SOURCE_KEY, PUBLIC_STORAGE_PREFIX, RebaseApiError as RebaseApiError$1, RebaseClientError as RebaseClientError$1, STORAGE_REFERENCE_SCHEME, isPublicStoragePath, isStorageReference, isUnsupported, parseStorageReference, resolveStorageReferences, simulationHeaders, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText } from "@rebasepro/types";
3
3
  import { COMPOSITE_ID_SEPARATOR, DOWNLOAD_URL_CONCURRENCY, RESUMABLE_UPLOAD_THRESHOLD, RebasePaginationError, and, buildCompositeId, cond, createBatchLoader, createConcurrencyLimit, createDownloadUrlCache, not, or, warnDeprecated, withETag } from "@rebasepro/common";
4
4
  import { toSnakeCase, unref } from "@rebasepro/utils";
5
+ //#region src/apple-sign-in.ts
6
+ /**
7
+ * The browser half of Sign in with Apple.
8
+ *
9
+ * Apple is the one provider a single-page app cannot take through the usual
10
+ * redirect: asking for the `name` or `email` scope obliges
11
+ * `response_mode=form_post`, so Apple answers with a cross-site POST to the
12
+ * redirect URI — a request a static page never sees. Apple's own JS SDK has a
13
+ * popup mode that hands the answer back to the opening page with
14
+ * `postMessage` instead, and that is what this uses. The redirect URI still
15
+ * has to be listed under the Services ID's Return URLs (HTTPS, no
16
+ * `localhost`), because Apple matches it and the token exchange repeats it.
17
+ *
18
+ * `state` is generated and checked here, which is what binds the code that
19
+ * comes back to the click that started it.
20
+ */
21
+ /** Apple's JS SDK, the only way into its popup mode. */
22
+ var APPLE_JS_SDK_URL = "https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleauth.js";
23
+ /** Apple's popup answers with `{ error }` when the visitor backs out. */
24
+ var APPLE_CANCELLATIONS = /* @__PURE__ */ new Set(["popup_closed_by_user", "user_cancelled_authorize"]);
25
+ var sdkLoad = null;
26
+ function appleIdGlobal() {
27
+ return globalThis.AppleID;
28
+ }
29
+ /**
30
+ * Load Apple's SDK once per page. A failed load is forgotten, so a retry tries
31
+ * again. A tag someone else added and that has not finished yet is not waited
32
+ * on — it may already have failed, and its events would never come — so a
33
+ * second, cached copy is added instead, which is harmless.
34
+ */
35
+ function loadAppleSdk() {
36
+ const loaded = appleIdGlobal();
37
+ if (loaded) return Promise.resolve(loaded);
38
+ if (sdkLoad) return sdkLoad;
39
+ sdkLoad = new Promise((resolve, reject) => {
40
+ const script = document.createElement("script");
41
+ script.src = APPLE_JS_SDK_URL;
42
+ script.async = true;
43
+ script.onload = () => {
44
+ const apple = appleIdGlobal();
45
+ if (apple) resolve(apple);
46
+ else reject(/* @__PURE__ */ new Error("Apple's sign-in script loaded without defining AppleID"));
47
+ };
48
+ script.onerror = () => reject(/* @__PURE__ */ new Error("Apple's sign-in script could not be loaded"));
49
+ document.head.appendChild(script);
50
+ }).catch((err) => {
51
+ sdkLoad = null;
52
+ throw new RebaseClientError("Sign in with Apple could not be loaded. Check your connection or any script blockers, then try again.", {
53
+ code: "APPLE_SIGN_IN_UNAVAILABLE",
54
+ cause: err
55
+ });
56
+ });
57
+ return sdkLoad;
58
+ }
59
+ /**
60
+ * Start loading Apple's SDK ahead of the click. Worth calling when the sign-in
61
+ * button mounts: with the SDK already on the page, the popup opens in the same
62
+ * task as the click, and Safari blocks a popup that opens later than that.
63
+ */
64
+ async function preloadAppleSignIn() {
65
+ if (typeof document === "undefined") return;
66
+ await loadAppleSdk();
67
+ }
68
+ function randomState() {
69
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
70
+ crypto.getRandomValues(bytes);
71
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
72
+ }
73
+ /**
74
+ * Open Apple's sign-in popup and return the authorization code, without
75
+ * spending it. Call it from a click handler: browsers block a popup that no
76
+ * gesture opened. Call {@link preloadAppleSignIn} first (on mount) so the
77
+ * popup does not wait on a script download.
78
+ *
79
+ * Throws a `RebaseClientError` whose `code` is `APPLE_SIGN_IN_CANCELLED` when
80
+ * the visitor closes the popup or declines, `APPLE_SIGN_IN_UNAVAILABLE` when
81
+ * Apple's script cannot load or this is not a browser, and
82
+ * `APPLE_SIGN_IN_FAILED` otherwise.
83
+ */
84
+ async function requestAppleAuthorization(request) {
85
+ if (typeof window === "undefined" || typeof document === "undefined") throw new RebaseClientError("Sign in with Apple's popup needs a browser. A native app gets the code from ASAuthorizationController and passes it to signInWithApple({ code, bundleId }).", { code: "APPLE_SIGN_IN_UNAVAILABLE" });
86
+ const apple = appleIdGlobal() ?? await loadAppleSdk();
87
+ const redirectUri = request.redirectUri ?? `${window.location.origin}/`;
88
+ const state = randomState();
89
+ apple.auth.init({
90
+ clientId: request.clientId,
91
+ scope: "name email",
92
+ redirectURI: redirectUri,
93
+ state,
94
+ usePopup: true
95
+ });
96
+ let response;
97
+ try {
98
+ response = await apple.auth.signIn();
99
+ } catch (err) {
100
+ const reason = typeof err === "object" && err !== null && "error" in err && typeof err.error === "string" ? err.error : void 0;
101
+ if (reason && APPLE_CANCELLATIONS.has(reason)) throw new RebaseClientError("Sign in with Apple was cancelled.", { code: "APPLE_SIGN_IN_CANCELLED" });
102
+ throw new RebaseClientError(reason ? `Sign in with Apple failed: ${reason}` : "Sign in with Apple failed. Please try again.", {
103
+ code: "APPLE_SIGN_IN_FAILED",
104
+ cause: err
105
+ });
106
+ }
107
+ const authorization = response.authorization;
108
+ if (!authorization?.code) throw new RebaseClientError("Apple returned no authorization code.", { code: "APPLE_SIGN_IN_FAILED" });
109
+ if (authorization.state !== state) throw new RebaseClientError("This Apple sign-in could not be verified as one started on this page. Please try again.", { code: "APPLE_SIGN_IN_FAILED" });
110
+ return {
111
+ code: authorization.code,
112
+ redirectUri,
113
+ ...response.user?.name ? { user: { name: response.user.name } } : {}
114
+ };
115
+ }
116
+ //#endregion
5
117
  //#region src/auth.ts
6
118
  /** Map a raw user object from an auth response (`/login`, `/refresh`, `/me`) to a `User`. */
7
119
  function mapRawUser(raw) {
@@ -51,13 +163,31 @@ function detectStorage() {
51
163
  } catch (e) {}
52
164
  return createMemoryStorage();
53
165
  }
166
+ /**
167
+ * The flow mode a client uses when `authFlowMode` is not set.
168
+ *
169
+ * Cookie in a browser. A backend run by the Rebase runtime always keeps the
170
+ * refresh token in a cookie and answers the body's with `""`, so a browser
171
+ * client defaulting to json held nothing to renew with, and was signed out
172
+ * without a word once its access token expired, about an hour after sign-in.
173
+ *
174
+ * Json off the browser (Node, a worker, React Native), where there is no
175
+ * cookie jar to keep it in — and in a browser that passes its own `storage`,
176
+ * which says where the session is to be kept: a second client on the page
177
+ * that keeps its own sign-in apart from the page's cookie. In cookie mode
178
+ * nothing would be kept there, and every reload would lose that sign-in.
179
+ */
180
+ function resolveAuthFlowMode(options) {
181
+ if (options?.authFlowMode) return options.authFlowMode;
182
+ return typeof document !== "undefined" && !options?.storage ? "cookie" : "json";
183
+ }
54
184
  function createAuth(transport, options) {
55
185
  const opts = options || {};
56
186
  const storage = opts.storage || detectStorage();
57
187
  const authPath = opts.authPath || "/auth";
58
188
  const autoRefresh = opts.autoRefresh !== false;
59
189
  const persistSession = opts.persistSession !== false;
60
- const authFlowMode = opts.authFlowMode || "json";
190
+ const authFlowMode = resolveAuthFlowMode(opts);
61
191
  const STORAGE_KEY = "rebase_auth";
62
192
  const REFRESH_BUFFER_MS = 12e4;
63
193
  /**
@@ -129,6 +259,25 @@ function createAuth(transport, options) {
129
259
  if (authFlowMode === "cookie") return "";
130
260
  return received || currentSession?.refreshToken || "";
131
261
  }
262
+ let flowMismatchReported = false;
263
+ /**
264
+ * Say so at sign-in, once, when the server's answer shows this client
265
+ * cannot renew the session it is starting.
266
+ *
267
+ * A server with `cookieAuth` answers `refreshToken: ""` and puts the token
268
+ * in the cookie; one without it puts the token in the body. A client in
269
+ * the other mode holds nothing it can renew with, and finds out when the
270
+ * access token expires — in json mode by dropping the session without a
271
+ * word. The answer to the sign-in is the first moment it is known.
272
+ */
273
+ function reportFlowMismatch(received, expiresAt) {
274
+ if (flowMismatchReported || received === void 0) return;
275
+ const serverUsesCookie = received === "";
276
+ if (serverUsesCookie === (authFlowMode === "cookie")) return;
277
+ flowMismatchReported = true;
278
+ const ends = Number.isFinite(expiresAt) ? `in about ${Math.max(1, Math.round((expiresAt - Date.now()) / 6e4))} minutes` : "when its access token expires";
279
+ console.error(serverUsesCookie ? `[rebase] This server keeps the refresh token in an HttpOnly cookie (its \`auth.cookieAuth\`), but this client is in json mode and was handed none, so the session it just started cannot be renewed and ends ${ends}. Create the client with \`auth: { authFlowMode: "cookie" }\`.` : `[rebase] This server returned the refresh token in the response body, so it does not use \`auth.cookieAuth\`, and this client, in cookie mode, cannot renew the session it just started: it ends ${ends}. Turn on \`auth.cookieAuth\` on the server, or create the client with \`auth: { authFlowMode: "json" }\`.`);
280
+ }
132
281
  /**
133
282
  * Whether the server refused a refresh as malformed: a 400, which says the
134
283
  * request this client built is not one that server accepts.
@@ -267,6 +416,15 @@ function createAuth(transport, options) {
267
416
  */
268
417
  const SPENT_TOKEN_MARGIN_MS = 1e4;
269
418
  /**
419
+ * Whether a request about to carry this session's token should first get a
420
+ * fresh one: the token has expired or is about to, and can be renewed.
421
+ */
422
+ function needsFreshToken(session) {
423
+ if (!Number.isFinite(session.expiresAt)) return false;
424
+ if (session.expiresAt > Date.now() + SPENT_TOKEN_MARGIN_MS) return false;
425
+ return authFlowMode === "cookie" || !!session.refreshToken;
426
+ }
427
+ /**
270
428
  * The transport's {@link TokenRefresher}: whether a request should wait for
271
429
  * a fresher token than the one held, and which token to send when it does.
272
430
  *
@@ -294,9 +452,7 @@ function createAuth(transport, options) {
294
452
  if (refreshOwnRequests > 0) return void 0;
295
453
  const session = currentSession;
296
454
  if (!session) return cookieRestore?.then(() => void 0);
297
- if (!Number.isFinite(session.expiresAt)) return void 0;
298
- if (session.expiresAt > Date.now() + SPENT_TOKEN_MARGIN_MS) return void 0;
299
- if (authFlowMode !== "cookie" && !session.refreshToken) return void 0;
455
+ if (!needsFreshToken(session)) return void 0;
300
456
  const epoch = sessionEpoch;
301
457
  return refreshSession().then((fresh) => epoch === sessionEpoch ? fresh.accessToken : void 0, () => epoch === sessionEpoch ? session.accessToken : void 0);
302
458
  }
@@ -368,6 +524,7 @@ function createAuth(transport, options) {
368
524
  }
369
525
  function handleAuthResponse(data, event) {
370
526
  sessionEpoch++;
527
+ reportFlowMismatch(data.tokens.refreshToken, data.tokens.accessTokenExpiresAt);
371
528
  const user = mapRawUser(data.user);
372
529
  const session = {
373
530
  accessToken: data.tokens.accessToken,
@@ -505,13 +662,55 @@ function createAuth(transport, options) {
505
662
  redirectUri
506
663
  });
507
664
  }
508
- async function signInWithApple(code, redirectUri, user) {
509
- return signInWithOAuth("apple", {
510
- code,
665
+ /**
666
+ * Sign in with an Apple authorization code.
667
+ *
668
+ * - Web: `signInWithApple({ code, redirectUri, user })` — or let
669
+ * {@link signInWithApplePopup} obtain the code for you.
670
+ * - Native (iOS, iPadOS, macOS): `signInWithApple({ code, bundleId, user })`
671
+ * with the `authorizationCode` from `ASAuthorizationController`. The
672
+ * bundle id must be in the backend's `APPLE_BUNDLE_IDS`.
673
+ *
674
+ * `user` carries the name Apple reports on the first authorization only.
675
+ * The positional `(code, redirectUri, user)` form is the web call, kept for
676
+ * existing callers.
677
+ */
678
+ async function signInWithApple(payloadOrCode, redirectUri, user) {
679
+ const payload = typeof payloadOrCode === "string" ? {
680
+ code: payloadOrCode,
511
681
  redirectUri,
512
682
  user
683
+ } : payloadOrCode;
684
+ return signInWithOAuth("apple", {
685
+ code: payload.code,
686
+ ...payload.redirectUri !== void 0 ? { redirectUri: payload.redirectUri } : {},
687
+ ...payload.bundleId !== void 0 ? { bundleId: payload.bundleId } : {},
688
+ ...payload.user?.name ? { user: { name: payload.user.name } } : {}
513
689
  });
514
690
  }
691
+ /**
692
+ * Sign in with Apple in a browser: opens Apple's popup, then spends the
693
+ * code it returns. Call it from a click handler, since browsers block a
694
+ * popup that no gesture opened.
695
+ *
696
+ * `clientId` defaults to the Services ID the backend publishes in
697
+ * `GET /auth/config` — but pass it when you can: fetching it first delays
698
+ * the popup past the click, which Safari blocks. Call
699
+ * `preloadAppleSignIn()` on mount for the same reason. `redirectUri`
700
+ * defaults to this page's origin plus `/`; either way it must be a Return
701
+ * URL registered on the Services ID.
702
+ *
703
+ * A closed popup rejects with a `RebaseClientError` whose `code` is
704
+ * `APPLE_SIGN_IN_CANCELLED` — an answer, not a failure.
705
+ */
706
+ async function signInWithApplePopup(options = {}) {
707
+ const clientId = options.clientId ?? (await getAuthConfig()).providerClientIds?.apple;
708
+ if (!clientId) throw new RebaseClientError$1("Sign in with Apple needs a Services ID: set APPLE_CLIENT_ID on the backend, or pass clientId.", { code: "APPLE_SIGN_IN_UNAVAILABLE" });
709
+ return signInWithApple(await requestAppleAuthorization({
710
+ clientId,
711
+ redirectUri: options.redirectUri
712
+ }));
713
+ }
515
714
  async function signInWithFacebook(code, redirectUri) {
516
715
  return signInWithOAuth("facebook", {
517
716
  code,
@@ -1208,9 +1407,49 @@ function createAuth(transport, options) {
1208
1407
  if (!res.ok) throwApiError(res.status, body, res.statusText);
1209
1408
  return body;
1210
1409
  }
1410
+ /**
1411
+ * The session as it is now, or `null`.
1412
+ *
1413
+ * A snapshot: every renewal of the access token (about hourly) replaces
1414
+ * the session with a new object, so one kept from an earlier call carries
1415
+ * a token the server refuses once it expires. Read it when you need it.
1416
+ * For a token to send, use {@link getAccessToken}.
1417
+ */
1211
1418
  function getSession() {
1212
1419
  return currentSession;
1213
1420
  }
1421
+ /**
1422
+ * The access token to put on a request of your own — a route outside
1423
+ * Rebase, a header for an upload — renewed first when it has expired or
1424
+ * is about to. `null` when no one is signed in.
1425
+ *
1426
+ * Ask for it for each request rather than keeping it: every renewal
1427
+ * replaces it. A Rebase function needs none of this, since
1428
+ * `functions.invoke` renews before sending and retries once on a 401.
1429
+ *
1430
+ * Waits for the session restored on load, and calls made together share
1431
+ * one renewal. A renewal the server refuses ends the session, as a refused
1432
+ * request does, and answers `null`. One that cannot reach the server
1433
+ * answers the token held, for the server to judge.
1434
+ */
1435
+ async function getAccessToken() {
1436
+ await isInitialized;
1437
+ const session = currentSession;
1438
+ if (!session) return null;
1439
+ if (!needsFreshToken(session)) return session.accessToken;
1440
+ const epoch = sessionEpoch;
1441
+ try {
1442
+ const fresh = await refreshSession();
1443
+ return epoch === sessionEpoch ? fresh.accessToken : currentSession?.accessToken ?? null;
1444
+ } catch (err) {
1445
+ if (epoch !== sessionEpoch) return currentSession?.accessToken ?? null;
1446
+ if (isFatalRefreshError(err)) {
1447
+ abandonSessionLocally();
1448
+ return null;
1449
+ }
1450
+ return session.accessToken;
1451
+ }
1452
+ }
1214
1453
  function onAuthStateChange(callback) {
1215
1454
  listeners.add(callback);
1216
1455
  return () => listeners.delete(callback);
@@ -1261,6 +1500,7 @@ function createAuth(transport, options) {
1261
1500
  signInWithGitHub,
1262
1501
  signInWithMicrosoft,
1263
1502
  signInWithApple,
1503
+ signInWithApplePopup,
1264
1504
  signInWithFacebook,
1265
1505
  signInWithTwitter,
1266
1506
  signInWithDiscord,
@@ -1295,6 +1535,7 @@ function createAuth(transport, options) {
1295
1535
  revokeAllSessions,
1296
1536
  getAuthConfig,
1297
1537
  getSession,
1538
+ getAccessToken,
1298
1539
  onAuthStateChange,
1299
1540
  canRestoreSession: () => persistSession || authFlowMode === "cookie",
1300
1541
  isInitialized: () => isInitialized,
@@ -1346,6 +1587,7 @@ function createCookieStorage(options = {}) {
1346
1587
  }
1347
1588
  //#endregion
1348
1589
  //#region src/admin.ts
1590
+ var isoDate = (date) => date instanceof Date ? date.toISOString() : date;
1349
1591
  function createAdmin(transport, options) {
1350
1592
  const adminPath = (options || {}).adminPath || "/admin";
1351
1593
  /**
@@ -1364,6 +1606,8 @@ function createAdmin(transport, options) {
1364
1606
  if (options?.search) params.set("search", options.search);
1365
1607
  if (options?.orderBy) params.set("orderBy", options.orderBy);
1366
1608
  if (options?.orderDir) params.set("orderDir", options.orderDir);
1609
+ if (options?.role) params.set("role", options.role);
1610
+ if (options?.ids) params.set("ids", options.ids.join(","));
1367
1611
  const qs = params.toString();
1368
1612
  return transport.request(adminPath + "/users" + (qs ? "?" + qs : ""), { method: "GET" });
1369
1613
  }
@@ -1407,6 +1651,29 @@ function createAdmin(transport, options) {
1407
1651
  async function resetMfa(userId) {
1408
1652
  return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/mfa", { method: "DELETE" });
1409
1653
  }
1654
+ /** One page of guests, the ones last seen longest ago first, with the `total` matching. */
1655
+ async function listGuests(options) {
1656
+ const params = new URLSearchParams();
1657
+ if (options?.limit !== void 0) params.set("limit", String(options.limit));
1658
+ if (options?.offset !== void 0) params.set("offset", String(options.offset));
1659
+ if (options?.lastSeenBefore !== void 0) params.set("lastSeenBefore", isoDate(options.lastSeenBefore));
1660
+ const qs = params.toString();
1661
+ return transport.request(adminPath + "/guests" + (qs ? "?" + qs : ""), { method: "GET" });
1662
+ }
1663
+ /** Delete one guest. An account is refused with `NOT_ANONYMOUS`; {@link deleteUser} deletes those. */
1664
+ async function deleteGuest(userId) {
1665
+ return transport.request(adminPath + "/guests/" + encodeURIComponent(userId), { method: "DELETE" });
1666
+ }
1667
+ /**
1668
+ * Delete one batch of the guests last seen before a date. It can only ever
1669
+ * touch guests. Repeat it while `remaining` is not 0, passing how many have
1670
+ * been skipped so far as `offset`.
1671
+ */
1672
+ async function deleteGuests(options) {
1673
+ const params = new URLSearchParams({ lastSeenBefore: isoDate(options.lastSeenBefore) });
1674
+ if (options.offset) params.set("offset", String(options.offset));
1675
+ return transport.request(adminPath + "/guests?" + params.toString(), { method: "DELETE" });
1676
+ }
1410
1677
  async function resetPassword(userId, options) {
1411
1678
  return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/reset-password", {
1412
1679
  method: "POST",
@@ -1427,6 +1694,9 @@ function createAdmin(transport, options) {
1427
1694
  updateUser,
1428
1695
  deleteUser,
1429
1696
  resetMfa,
1697
+ listGuests,
1698
+ deleteGuest,
1699
+ deleteGuests,
1430
1700
  resetPassword,
1431
1701
  listRoles,
1432
1702
  bootstrap
@@ -2139,10 +2409,23 @@ function requestTimeoutError(written) {
2139
2409
  * connection has been down for longer than a blip. The registration is kept and
2140
2410
  * resumes when the socket is back.
2141
2411
  */
2142
- function realtimeLostError() {
2412
+ function realtimeLostError(refusal) {
2413
+ if (refusal) return new RebaseApiError$1(`The server refused this realtime connection (${refusal.code}: ${refusal.message}), so live data is not updating. The client keeps retrying, more slowly each time, and refreshes this subscription once it is let in.`, {
2414
+ code: "CONNECTION_LOST",
2415
+ details: { reason: refusal.code },
2416
+ cause: refusal
2417
+ });
2143
2418
  return new RebaseApiError$1("The realtime connection is down, so live data is not updating. The client keeps reconnecting and refreshes this subscription when the connection is back.", { code: "CONNECTION_LOST" });
2144
2419
  }
2145
2420
  /**
2421
+ * Whether `error` is the server refusing this socket for its per-user ceiling
2422
+ * (`REALTIME_MAX_SOCKETS_PER_USER`): it answers AUTHENTICATE with
2423
+ * `TOO_MANY_SOCKETS` and closes the socket.
2424
+ */
2425
+ function isSocketCeilingRefusal(error) {
2426
+ return error instanceof RebaseApiError$1 && error.code === "TOO_MANY_SOCKETS";
2427
+ }
2428
+ /**
2146
2429
  * Whether realtime debugging is on: `globalThis.__REBASE_DEBUG_REALTIME__ = true`,
2147
2430
  * set from a console or a test. While it is, each refetched row that differs
2148
2431
  * from the one held is explained key by key with `console.debug`.
@@ -2151,17 +2434,28 @@ function realtimeDebugOn() {
2151
2434
  return Reflect.get(globalThis, "__REBASE_DEBUG_REALTIME__") === true;
2152
2435
  }
2153
2436
  /**
2154
- * Connection chatter: the socket opened, signed in, closed, is redialling.
2155
- *
2156
- * `console.debug` where that is a debug level — a browser's console hides it
2157
- * unless Verbose is asked for. Not in Node, where `console.debug` is
2158
- * `console.log`: a script's `listen()` opened its stdout with "Connected to
2159
- * PostgreSQL backend" and "WebSocket auto-authenticated", ahead of what the
2160
- * script prints. There it is written only while realtime debugging is on.
2437
+ * The `localStorage` key that turns connection logging on for one browser,
2438
+ * without a code change or a rebuild: `localStorage.setItem("rebase_debug", "1")`
2439
+ * in its console. For a page that loads the client as a plain script, where
2440
+ * `createRebaseClient({ debug: true })` means editing and redeploying the site.
2161
2441
  */
2162
- function connectionDebug(...args) {
2163
- if (!(typeof window !== "undefined" || typeof document !== "undefined") && !realtimeDebugOn()) return;
2164
- console.debug(...args);
2442
+ var DEBUG_STORAGE_KEY = "rebase_debug";
2443
+ /**
2444
+ * Whether connection logging was switched on from outside the code:
2445
+ * `globalThis.__REBASE_DEBUG__`, `globalThis.__REBASE_DEBUG_REALTIME__` (which
2446
+ * also explains refetched rows), or {@link DEBUG_STORAGE_KEY} in this
2447
+ * browser's `localStorage`. Read at each line, so it can be switched on in a
2448
+ * console without reloading a page whose socket is already open.
2449
+ */
2450
+ function debugSwitchedOn() {
2451
+ if (Reflect.get(globalThis, "__REBASE_DEBUG__") === true || realtimeDebugOn()) return true;
2452
+ if (typeof window === "undefined" || typeof localStorage === "undefined") return false;
2453
+ try {
2454
+ const value = localStorage.getItem(DEBUG_STORAGE_KEY);
2455
+ return value === "1" || value === "true";
2456
+ } catch {
2457
+ return false;
2458
+ }
2165
2459
  }
2166
2460
  /**
2167
2461
  * The codes an `AUTHENTICATE` is refused with when the server will not honour
@@ -2212,15 +2506,31 @@ var SOCKET_OPT_INS = [
2212
2506
  "channel_seq",
2213
2507
  "cancel_sql"
2214
2508
  ];
2509
+ /**
2510
+ * The query parameter naming the group a socket belongs to. A platform that
2511
+ * routes on it sends sockets with the same value to the same instance; the
2512
+ * server itself never reads it.
2513
+ */
2514
+ var SOCKET_AFFINITY_PARAM = "affinity";
2215
2515
  /** Slack on top of two heartbeat intervals before a silent socket is given up on. */
2216
2516
  var HEARTBEAT_GRACE_MS = 5e3;
2217
2517
  /**
2218
- * `url` with the opt-ins named on it. Appended rather than rebuilt through
2219
- * `URL`, which would rewrite the address the caller gave (a bare origin gains
2220
- * a `/`).
2518
+ * `url` with the opt-ins named on it, and `affinity` when there is one.
2519
+ * Appended rather than rebuilt through `URL`, which would rewrite the address
2520
+ * the caller gave (a bare origin gains a `/`).
2521
+ *
2522
+ * `affinity` replaces one already in `url`: a router takes one value, and it
2523
+ * may not be the last.
2221
2524
  */
2222
- function withOptIns(url) {
2223
- return `${url}${url.includes("?") ? "&" : "?"}${SOCKET_OPT_IN_PARAM}=${SOCKET_OPT_INS.join(",")}`;
2525
+ function withOptIns(url, affinity) {
2526
+ const queryAt = url.indexOf("?");
2527
+ const address = queryAt === -1 ? url : url.slice(0, queryAt);
2528
+ const params = queryAt === -1 ? [] : url.slice(queryAt + 1).split("&");
2529
+ return `${address}?${[
2530
+ ...affinity ? params.filter((param) => !param.startsWith(`${SOCKET_AFFINITY_PARAM}=`)) : params,
2531
+ ...affinity ? [`${SOCKET_AFFINITY_PARAM}=${encodeURIComponent(affinity)}`] : [],
2532
+ `${SOCKET_OPT_IN_PARAM}=${SOCKET_OPT_INS.join(",")}`
2533
+ ].join("&")}`;
2224
2534
  }
2225
2535
  /**
2226
2536
  * Broadcast and presence frames.
@@ -2308,8 +2618,15 @@ function isCollectionUpdate(message) {
2308
2618
  function isChannelMessage(message) {
2309
2619
  return typeof message.channel === "string" && CHANNEL_FRAME_TYPES.has(message.type);
2310
2620
  }
2621
+ /** The code of a channel `ERROR` frame, if it is one and carries a code. */
2622
+ function channelErrorCode(message) {
2623
+ if (message.type !== "ERROR" && message.type !== "error") return void 0;
2624
+ const raw = message.payload?.error;
2625
+ if (raw && typeof raw === "object" && "code" in raw && typeof raw.code === "string") return raw.code;
2626
+ }
2311
2627
  var RebaseWebSocketClient = class {
2312
2628
  websocketUrl;
2629
+ affinity;
2313
2630
  ws = null;
2314
2631
  /**
2315
2632
  * Where the socket's token comes from. A client built by
@@ -2483,14 +2800,39 @@ var RebaseWebSocketClient = class {
2483
2800
  onUnauthorized;
2484
2801
  refreshInProgress = null;
2485
2802
  impersonate;
2803
+ debug;
2804
+ /**
2805
+ * Connection chatter: the socket opened, signed in, closed, is redialling.
2806
+ *
2807
+ * Silent unless asked for, with the `debug` option or
2808
+ * {@link debugSwitchedOn}. It used to go to `console.debug` in every
2809
+ * browser: a public page printed "Connected to PostgreSQL backend" and
2810
+ * "WebSocket auto-authenticated" to each visitor's console, naming the
2811
+ * backend on every load. In Node, where `console.debug` is `console.log`,
2812
+ * it opened a script's stdout ahead of what the script prints. Warnings and
2813
+ * errors are not chatter and are always written.
2814
+ */
2815
+ connectionDebug(...args) {
2816
+ if (!this.debug && !debugSwitchedOn()) return;
2817
+ console.debug(...args);
2818
+ }
2486
2819
  constructor(config) {
2487
2820
  this.websocketUrl = config.websocketUrl;
2821
+ this.affinity = config.affinity;
2488
2822
  this.getAuthToken = config.getAuthToken;
2489
2823
  this.onUnauthorized = config.onUnauthorized;
2490
2824
  this.impersonate = config.impersonate;
2825
+ this.debug = config.debug === true;
2491
2826
  this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : void 0);
2492
2827
  }
2493
2828
  /**
2829
+ * Name the group this socket belongs to, or clear it with `null`. Read at
2830
+ * each dial, so a socket already open stays where it is until it redials.
2831
+ */
2832
+ setAffinity(key) {
2833
+ this.affinity = key ?? void 0;
2834
+ }
2835
+ /**
2494
2836
  * Open the socket if it is not open (or opening) already.
2495
2837
  *
2496
2838
  * Idempotent, synchronous, and safe to call on every operation that needs a
@@ -2526,7 +2868,7 @@ var RebaseWebSocketClient = class {
2526
2868
  if (this.closedByCaller) return;
2527
2869
  if (this.connectionState !== "reconnecting" && this.connectionState !== "disconnected") return;
2528
2870
  if (this.ws) return;
2529
- connectionDebug(`${reason} — retrying the realtime connection`);
2871
+ this.connectionDebug(`${reason} — retrying the realtime connection`);
2530
2872
  if (this.reconnectTimeout) {
2531
2873
  clearTimeout(this.reconnectTimeout);
2532
2874
  this.reconnectTimeout = null;
@@ -2576,9 +2918,73 @@ var RebaseWebSocketClient = class {
2576
2918
  }
2577
2919
  return true;
2578
2920
  }
2921
+ /** Whether the current run of ceiling refusals has been said in the console. */
2922
+ socketCeilingWarned = false;
2923
+ /**
2924
+ * The server refused this socket for its per-user ceiling. Said once per
2925
+ * run of refusals, as a warning, and reported to every registration at
2926
+ * once as an outage — a refusal is not a blip that the next dial fixes.
2927
+ */
2928
+ noteSocketCeiling(error) {
2929
+ if (!this.socketCeilingWarned) {
2930
+ this.socketCeilingWarned = true;
2931
+ console.warn(`[Rebase] Realtime: the server refused this connection (${error.code}: ${error.message}). Live data is not updating; the client retries, more slowly each time, until another connection closes.`);
2932
+ }
2933
+ this.clearOutageTimer();
2934
+ this.reportConnectionLost(error);
2935
+ }
2579
2936
  /**
2580
2937
  * Authenticate the WebSocket connection
2581
2938
  */
2939
+ /**
2940
+ * {@link authenticate}, asked again a few times when the server could not
2941
+ * answer (its auth store busy, `ROLE_LOOKUP_FAILED`, a timeout) — not when
2942
+ * it refused the session or the socket ceiling, which a retry cannot
2943
+ * change. Stops as soon as `socket` is no longer this client's.
2944
+ */
2945
+ async authenticateRetrying(token, socket) {
2946
+ const delays = [
2947
+ 500,
2948
+ 1500,
2949
+ 3500
2950
+ ];
2951
+ for (let attempt = 0;; attempt++) try {
2952
+ await this.authenticate(token);
2953
+ return;
2954
+ } catch (error) {
2955
+ if (attempt >= delays.length || this.ws !== socket || isSocketCeilingRefusal(error) || isSessionRefusal(error)) throw error;
2956
+ await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
2957
+ if (this.ws !== socket) throw error;
2958
+ }
2959
+ }
2960
+ /** A sign-in again after a channel was refused for not being signed in, in flight. */
2961
+ channelAuthRecovery = null;
2962
+ /**
2963
+ * A channel frame refused `UNAUTHORIZED` while this client holds a way to
2964
+ * get a token: the socket is open but not signed in (an authentication that
2965
+ * failed on a reconnect, a token that expired). Nothing else signs it in —
2966
+ * channel frames expect no answer, so the refusal reaches only the channel —
2967
+ * and every later frame is refused the same way. Sign in again, once for
2968
+ * all the channels that noticed, and have them re-join.
2969
+ */
2970
+ recoverChannelAuth() {
2971
+ if (this.channelAuthRecovery || !this.getAuthToken || this.isAuthenticated) return;
2972
+ const socket = this.ws;
2973
+ this.channelAuthRecovery = (async () => {
2974
+ try {
2975
+ const token = await this.getAuthToken();
2976
+ if (!token || !socket || this.ws !== socket) return;
2977
+ await this.authenticateRetrying(token, socket);
2978
+ if (this.ws === socket) this.emit("reconnect");
2979
+ } catch (error) {
2980
+ this.connectionDebug("Could not sign the socket in again for a channel:", error?.message || error);
2981
+ } finally {
2982
+ setTimeout(() => {
2983
+ this.channelAuthRecovery = null;
2984
+ }, 2e3);
2985
+ }
2986
+ })();
2987
+ }
2582
2988
  async authenticate(token) {
2583
2989
  return new Promise((resolve, reject) => {
2584
2990
  const requestId = `auth_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
@@ -2624,10 +3030,10 @@ var RebaseWebSocketClient = class {
2624
3030
  if (this.isConnected && !this.isAuthenticated && !this.authPromise) this.getAuthToken().then((token) => {
2625
3031
  if (!this.ws) return;
2626
3032
  if (token) this.authenticate(token).catch((e) => {
2627
- if (this.ws) connectionDebug("WebSocket auto-auth skipped:", e?.message || e);
3033
+ if (this.ws) this.connectionDebug("WebSocket auto-auth skipped:", e?.message || e);
2628
3034
  });
2629
3035
  }).catch((e) => {
2630
- if (this.ws) connectionDebug("WebSocket auto-auth skipped:", e?.message || e);
3036
+ if (this.ws) this.connectionDebug("WebSocket auto-auth skipped:", e?.message || e);
2631
3037
  });
2632
3038
  }
2633
3039
  /**
@@ -2675,31 +3081,44 @@ var RebaseWebSocketClient = class {
2675
3081
  this.ws = null;
2676
3082
  }
2677
3083
  try {
2678
- const socket = new this.WebSocketConstructor(withOptIns(this.websocketUrl));
3084
+ const socket = new this.WebSocketConstructor(withOptIns(this.websocketUrl, this.affinity));
2679
3085
  this.ws = socket;
2680
3086
  this.ws.onopen = async () => {
2681
- connectionDebug("Connected to PostgreSQL backend");
3087
+ this.connectionDebug("Connected to PostgreSQL backend");
2682
3088
  const wasReconnect = this.hadConnection;
2683
3089
  this.hadConnection = true;
2684
3090
  this.isConnected = true;
2685
- this.reconnectAttempts = 0;
2686
- this.clearOutageTimer();
2687
- this.outageReported = false;
2688
3091
  this.gaveUp = false;
2689
- this.setState("connected");
3092
+ if (!this.outageReported) this.setState("connected");
2690
3093
  this.refusedSession = null;
2691
3094
  if (this.getAuthToken && !this.isAuthenticated) {
2692
3095
  let token = null;
2693
3096
  try {
2694
3097
  token = await this.getAuthToken();
2695
3098
  if (token) {
2696
- await this.authenticate(token);
2697
- connectionDebug("WebSocket auto-authenticated");
3099
+ await this.authenticateRetrying(token, socket);
3100
+ this.connectionDebug("WebSocket auto-authenticated");
2698
3101
  }
2699
3102
  } catch (error) {
2700
- if (!(token && this.noteSessionRefused(token, error))) connectionDebug("WebSocket connected, not signed in yet:", error?.message || error);
3103
+ if (isSocketCeilingRefusal(error)) {
3104
+ this.noteSocketCeiling(error);
3105
+ return;
3106
+ }
3107
+ if (!(token && this.noteSessionRefused(token, error))) {
3108
+ this.connectionDebug("WebSocket connected, not signed in yet:", error?.message || error);
3109
+ if (token && this.ws === socket && !this.refusedSession) {
3110
+ socket.close(4e3, "Could not authenticate; reconnecting");
3111
+ return;
3112
+ }
3113
+ }
2701
3114
  }
2702
3115
  }
3116
+ if (this.ws !== socket) return;
3117
+ this.reconnectAttempts = 0;
3118
+ this.clearOutageTimer();
3119
+ this.outageReported = false;
3120
+ this.socketCeilingWarned = false;
3121
+ this.setState("connected");
2703
3122
  this.emit(wasReconnect ? "reconnect" : "connect");
2704
3123
  this.processMessageQueue(wasReconnect);
2705
3124
  if (wasReconnect) this.resubscribeAll();
@@ -2715,7 +3134,7 @@ var RebaseWebSocketClient = class {
2715
3134
  }
2716
3135
  };
2717
3136
  const onClosed = () => {
2718
- connectionDebug("Disconnected from PostgreSQL backend");
3137
+ this.connectionDebug("Disconnected from PostgreSQL backend");
2719
3138
  this.stopLivenessWatch();
2720
3139
  this.forgetServerOptIns();
2721
3140
  if (this.ws === socket) this.ws = null;
@@ -2845,7 +3264,7 @@ var RebaseWebSocketClient = class {
2845
3264
  this.reconnectAttempts = Math.min(this.reconnectAttempts + 1, 30);
2846
3265
  const ceiling = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), MAX_RECONNECT_DELAY_MS);
2847
3266
  const delay = MIN_RECONNECT_DELAY_MS + Math.floor(Math.random() * (ceiling - MIN_RECONNECT_DELAY_MS));
2848
- connectionDebug(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
3267
+ this.connectionDebug(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
2849
3268
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
2850
3269
  this.reconnectTimeout = setTimeout(() => {
2851
3270
  this.reconnectTimeout = null;
@@ -2871,11 +3290,11 @@ var RebaseWebSocketClient = class {
2871
3290
  if (this.outageTimer) clearTimeout(this.outageTimer);
2872
3291
  this.outageTimer = null;
2873
3292
  }
2874
- reportConnectionLost() {
3293
+ reportConnectionLost(refusal) {
2875
3294
  if (this.outageReported) return;
2876
3295
  this.outageReported = true;
2877
3296
  this.setState("disconnected");
2878
- const error = realtimeLostError();
3297
+ const error = realtimeLostError(refusal);
2879
3298
  for (const subscription of this.collectionSubscriptions.values()) this.notifyError(subscription.callbacks, error);
2880
3299
  for (const subscription of this.singleSubscriptions.values()) this.notifyError(subscription.callbacks, error);
2881
3300
  for (const handler of [...this.connectionLostHandlers]) try {
@@ -2994,6 +3413,7 @@ var RebaseWebSocketClient = class {
2994
3413
  return;
2995
3414
  }
2996
3415
  if (isChannelMessage(message)) {
3416
+ if (channelErrorCode(message) === "UNAUTHORIZED") this.recoverChannelAuth();
2997
3417
  const handlers = this.channelHandlers.get(message.channel);
2998
3418
  if (handlers) for (const handler of [...handlers]) try {
2999
3419
  handler(message);
@@ -3121,7 +3541,7 @@ var RebaseWebSocketClient = class {
3121
3541
  if (!token) throw new Error("user not logged in");
3122
3542
  if (this.refusedSession?.token === token) throw this.refusedSession.error;
3123
3543
  await this.authenticate(token);
3124
- connectionDebug("WebSocket authenticated on demand");
3544
+ this.connectionDebug("WebSocket authenticated on demand");
3125
3545
  return;
3126
3546
  } catch (error) {
3127
3547
  lastError = error;
@@ -3140,7 +3560,7 @@ var RebaseWebSocketClient = class {
3140
3560
  }
3141
3561
  if (attempt < retryCount - 1) {
3142
3562
  const delay = Math.min(1e3 * (attempt + 1), 3e3);
3143
- connectionDebug(`WebSocket auth attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
3563
+ this.connectionDebug(`WebSocket auth attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
3144
3564
  await new Promise((resolve) => setTimeout(resolve, delay));
3145
3565
  }
3146
3566
  }
@@ -3155,7 +3575,7 @@ var RebaseWebSocketClient = class {
3155
3575
  const token = await this.getAuthToken();
3156
3576
  if (!token) throw new Error("user not logged in");
3157
3577
  await this.authenticate(token);
3158
- connectionDebug("WebSocket reauthenticated successfully");
3578
+ this.connectionDebug("WebSocket reauthenticated successfully");
3159
3579
  } catch (error) {
3160
3580
  console.error("WebSocket reauthentication failed:", error);
3161
3581
  throw error;
@@ -3845,7 +4265,7 @@ var RebaseWebSocketClient = class {
3845
4265
  * we need to re-register everything to resume receiving updates.
3846
4266
  */
3847
4267
  resubscribeAll() {
3848
- connectionDebug(`[WS] Re-subscribing: ${this.collectionSubscriptions.size} collection(s), ${this.singleSubscriptions.size} row(ies)`);
4268
+ this.connectionDebug(`[WS] Re-subscribing: ${this.collectionSubscriptions.size} collection(s), ${this.singleSubscriptions.size} row(ies)`);
3849
4269
  for (const [key, sub] of this.collectionSubscriptions.entries()) {
3850
4270
  if (sub.subscribeInFlight) continue;
3851
4271
  const oldBackendId = sub.backendSubscriptionId;
@@ -4038,6 +4458,28 @@ var RebaseRealtimeChannel = class {
4038
4458
  await this.send("presence_state");
4039
4459
  if (this.wantsHistory) await this.requestHistory();
4040
4460
  }
4461
+ /** Consecutive re-joins asked for by refusals, for the backoff; reset after a quiet minute. */
4462
+ rejoinAttempts = 0;
4463
+ rejoinTimer;
4464
+ lastRejoinAt = 0;
4465
+ /**
4466
+ * Re-join after the server refused this channel for a reason a retry can
4467
+ * change: it could not check permissions at that moment, or it has no record
4468
+ * of the join (a join that was itself refused, so every broadcast after it
4469
+ * came back "not a member"). The join was fire-and-forget and `joined` was
4470
+ * already set, so nothing else would ever send it again. Backs off 1, 2, 4…
4471
+ * up to 30 seconds, one re-join at a time.
4472
+ */
4473
+ scheduleRejoin() {
4474
+ if (this.rejoinTimer || !this.joined) return;
4475
+ if (Date.now() - this.lastRejoinAt > 6e4) this.rejoinAttempts = 0;
4476
+ const delay = Math.min(3e4, 1e3 * 2 ** this.rejoinAttempts++);
4477
+ this.rejoinTimer = setTimeout(() => {
4478
+ this.rejoinTimer = void 0;
4479
+ this.lastRejoinAt = Date.now();
4480
+ if (this.joined) this.rejoin();
4481
+ }, delay);
4482
+ }
4041
4483
  async rejoin() {
4042
4484
  try {
4043
4485
  await this.send("join_channel");
@@ -4135,12 +4577,28 @@ var RebaseRealtimeChannel = class {
4135
4577
  */
4136
4578
  async broadcast(event, payload) {
4137
4579
  await this.join();
4580
+ this.rememberOwnSender(this.transport.socketClientId);
4138
4581
  await this.send("broadcast", {
4139
4582
  event,
4140
4583
  payload
4141
4584
  });
4142
4585
  }
4143
4586
  /**
4587
+ * The socket ids this channel has broadcast from — the current one and the
4588
+ * ones before a reconnect. A message in history from any of them is this
4589
+ * client's own, and a sender is never sent its own messages: replayed after
4590
+ * a reconnect whose `broadcast_ack` was lost, it was applied twice.
4591
+ */
4592
+ ownSenderIds = /* @__PURE__ */ new Set();
4593
+ rememberOwnSender(id) {
4594
+ if (id === void 0 || this.ownSenderIds.has(id)) return;
4595
+ this.ownSenderIds.add(id);
4596
+ if (this.ownSenderIds.size > 16) {
4597
+ const oldest = this.ownSenderIds.values().next().value;
4598
+ if (oldest !== void 0) this.ownSenderIds.delete(oldest);
4599
+ }
4600
+ }
4601
+ /**
4144
4602
  * Observe refusals about this channel.
4145
4603
  *
4146
4604
  * `CHANNEL_FORBIDDEN` when an authorizer refuses a join, a broadcast or a
@@ -4209,6 +4667,10 @@ var RebaseRealtimeChannel = class {
4209
4667
  /** Leave the channel and release every listener and timer. */
4210
4668
  async leave() {
4211
4669
  this.stopHeartbeat();
4670
+ if (this.rejoinTimer) {
4671
+ clearTimeout(this.rejoinTimer);
4672
+ this.rejoinTimer = void 0;
4673
+ }
4212
4674
  this.trackedState = null;
4213
4675
  this.presences = {};
4214
4676
  this.presenceHandlers.clear();
@@ -4313,7 +4775,7 @@ var RebaseRealtimeChannel = class {
4313
4775
  for (const entry of entries) {
4314
4776
  if (entry.seq <= this.lastSeq) continue;
4315
4777
  this.lastSeq = entry.seq;
4316
- if (ownId !== void 0 && entry.senderId === ownId) continue;
4778
+ if (ownId !== void 0 && (entry.senderId === ownId || entry.senderId !== void 0 && this.ownSenderIds.has(entry.senderId))) continue;
4317
4779
  this.deliver({
4318
4780
  event: entry.event,
4319
4781
  payload: entry.payload,
@@ -4352,6 +4814,7 @@ var RebaseRealtimeChannel = class {
4352
4814
  const asObject = typeof raw === "object" ? raw : void 0;
4353
4815
  const text = asObject?.message ?? (typeof raw === "string" ? raw : void 0) ?? message.error ?? "The server refused a channel operation.";
4354
4816
  this.emitError(new RebaseApiError$1(text, { ...asObject?.code ? { code: asObject.code } : {} }));
4817
+ if (this.joined && rejoinsAfter(asObject?.code, text)) this.scheduleRejoin();
4355
4818
  break;
4356
4819
  }
4357
4820
  }
@@ -4426,6 +4889,16 @@ var RebaseRealtimeChannel = class {
4426
4889
  for (const handler of this.presenceHandlers) handler(snapshot, diff);
4427
4890
  }
4428
4891
  };
4892
+ /**
4893
+ * Whether a channel refusal is one a re-join can recover from: the server's
4894
+ * auth store could not answer (`ROLE_LOOKUP_FAILED`, `DATABASE_UNAVAILABLE`), or
4895
+ * it no longer counts this client a member. A channel the client may not use
4896
+ * (any other `CHANNEL_FORBIDDEN`) is not retried.
4897
+ */
4898
+ function rejoinsAfter(code, message) {
4899
+ if (code === "ROLE_LOOKUP_FAILED" || code === "DATABASE_UNAVAILABLE") return true;
4900
+ return code === "CHANNEL_FORBIDDEN" && /not a member/i.test(message);
4901
+ }
4429
4902
  //#endregion
4430
4903
  //#region src/offline-lazy.ts
4431
4904
  /**
@@ -4462,7 +4935,7 @@ var LazyOfflineManager = class {
4462
4935
  keepsLastUser;
4463
4936
  constructor(config, createInner) {
4464
4937
  this.keepsLastUser = config.keepLastUser === true;
4465
- import("./offline-BrqCRgih.js").then(({ OfflineManager: Engine }) => {
4938
+ import("./offline-AvuEcg7u.js").then(({ OfflineManager: Engine }) => {
4466
4939
  const engine = new Engine(config, createInner);
4467
4940
  this.engine = engine;
4468
4941
  const queued = this.queued;
@@ -4537,6 +5010,9 @@ var LazyOfflineManager = class {
4537
5010
  setScope(uid, options) {
4538
5011
  this.run((engine) => engine.setScope(uid, options)).catch(() => void 0);
4539
5012
  }
5013
+ onReachedUnconfirmed(listener) {
5014
+ return this.subscribe((engine) => engine.onReachedUnconfirmed(listener));
5015
+ }
4540
5016
  async resumeLastUser() {
4541
5017
  await await this.run((engine) => engine.resumeLastUser());
4542
5018
  }
@@ -4644,7 +5120,7 @@ function deriveWebSocketUrl(baseUrl) {
4644
5120
  return toWsProtocol(baseUrl);
4645
5121
  }
4646
5122
  function createRebaseClient(options) {
4647
- const transport = createTransport(options, { credentialOutOfBand: options.auth?.authFlowMode === "cookie" });
5123
+ const transport = createTransport(options, { credentialOutOfBand: resolveAuthFlowMode(options.auth) === "cookie" });
4648
5124
  const auth = createAuth(transport, options.auth);
4649
5125
  const admin = createAdmin(transport, options.admin);
4650
5126
  const cron = createCron(transport, options.cron);
@@ -4692,9 +5168,11 @@ function createRebaseClient(options) {
4692
5168
  if (resolvedWsUrl) {
4693
5169
  ws = new RebaseWebSocketClient({
4694
5170
  websocketUrl: resolvedWsUrl,
5171
+ affinity: options.realtime && options.realtime !== true ? options.realtime.affinity : void 0,
4695
5172
  getAuthToken: () => transport.resolveToken(),
4696
5173
  onUnauthorized: () => onUnauthorized(),
4697
- impersonate: options.impersonate
5174
+ impersonate: options.impersonate,
5175
+ debug: options.debug
4698
5176
  });
4699
5177
  let realtimeUid = auth.getSession()?.user?.uid ?? null;
4700
5178
  auth.onAuthStateChange((event, session) => {
@@ -4771,15 +5249,19 @@ function createRebaseClient(options) {
4771
5249
  });
4772
5250
  if (offlineManager.keepsLastUser) {
4773
5251
  let confirming = false;
4774
- offlineManager.api.onStatusChange((status) => {
4775
- if (!status.online || !status.unverifiedUser || confirming || auth.getSession()) return;
5252
+ const confirm = () => {
5253
+ if (confirming || auth.getSession()) return;
4776
5254
  confirming = true;
4777
5255
  auth.refreshSession().catch((error) => {
4778
5256
  if (error instanceof RebaseApiError && error.status !== void 0 && error.status >= 400 && error.status < 500 && !auth.getSession()) offlineManager.setScope(void 0);
4779
5257
  }).finally(() => {
4780
5258
  confirming = false;
4781
5259
  });
5260
+ };
5261
+ offlineManager.api.onStatusChange((status) => {
5262
+ if (status.online && status.unverifiedUser) confirm();
4782
5263
  });
5264
+ offlineManager.onReachedUnconfirmed(confirm);
4783
5265
  }
4784
5266
  }
4785
5267
  /**
@@ -4840,11 +5322,12 @@ function createRebaseClient(options) {
4840
5322
  }
4841
5323
  });
4842
5324
  }
5325
+ const slug = toSnakeCase(prop);
4843
5326
  if (!untypedWarned) {
4844
5327
  untypedWarned = true;
4845
- console.warn(`[Rebase] Untyped data access detected (client.data.${prop}). Collection names are resolved via snake_case conversion, which may cause silent 404s at request time. Pass a \`collections\` dictionary to createRebaseClient() or use the generated SDK for type-safe access.`);
5328
+ console.warn(`[Rebase] Untyped data access detected: client.data.${prop} was sent to /data/${slug}, its name in snake_case, because this client has no \`collections\` dictionary. A collection whose slug is not that (a kebab-case slug, a renamed accessor) answers 404. With generated types, pass \`collections: collectionsDictionary\` (from generated/sdk/database.types) to createRebaseClient(); a typed client needs it. Otherwise use client.data.collection("<slug>").`);
4846
5329
  }
4847
- return collection(toSnakeCase(prop));
5330
+ return collection(slug);
4848
5331
  },
4849
5332
  has(_target, prop) {
4850
5333
  if (prop === "collection") return true;
@@ -4867,24 +5350,26 @@ function createRebaseClient(options) {
4867
5350
  createStorageSource,
4868
5351
  fetchStorageSources,
4869
5352
  ws,
4870
- realtime: {
4871
- /**
4872
- * Join a broadcast/presence channel.
4873
- *
4874
- * Repeated calls with the same name return the same channel, so
4875
- * separate components can attach handlers without each opening its
4876
- * own membership — and `leave()` from one would otherwise silently
4877
- * cut off the others.
4878
- */
4879
- channel: (name, options) => {
4880
- if (!ws) throw new RebaseClientError(realtimeUnreachable ? `Realtime is enabled but ${unreachableReason}` : "Realtime is disabled on this client (realtime: false), so channels are unavailable.", { code: "REALTIME_DISABLED" });
4881
- let existing = realtimeChannels.get(name);
4882
- if (!existing) {
4883
- existing = new RebaseRealtimeChannel(name, ws, options);
4884
- realtimeChannels.set(name, existing);
4885
- } else if (options?.history) existing.enableHistory();
4886
- return existing;
4887
- } },
5353
+ realtime: {
5354
+ /**
5355
+ * Join a broadcast/presence channel.
5356
+ *
5357
+ * Repeated calls with the same name return the same channel, so
5358
+ * separate components can attach handlers without each opening its
5359
+ * own membership — and `leave()` from one would otherwise silently
5360
+ * cut off the others.
5361
+ */
5362
+ channel: (name, options) => {
5363
+ if (!ws) throw new RebaseClientError(realtimeUnreachable ? `Realtime is enabled but ${unreachableReason}` : "Realtime is disabled on this client (realtime: false), so channels are unavailable.", { code: "REALTIME_DISABLED" });
5364
+ let existing = realtimeChannels.get(name);
5365
+ if (!existing) {
5366
+ existing = new RebaseRealtimeChannel(name, ws, options);
5367
+ realtimeChannels.set(name, existing);
5368
+ } else if (options?.history) existing.enableHistory();
5369
+ return existing;
5370
+ },
5371
+ setAffinity: (key) => ws?.setAffinity(key)
5372
+ },
4888
5373
  /**
4889
5374
  * Release every handle that can keep a process alive — see the
4890
5375
  * `close` docblock on the client interface.
@@ -4911,6 +5396,28 @@ channel: (name, options) => {
4911
5396
  onUnauthorized = handler;
4912
5397
  },
4913
5398
  resolveToken: transport.resolveToken,
5399
+ simulate: (simulation) => {
5400
+ const derived = createRebaseClient({
5401
+ baseUrl: options.baseUrl,
5402
+ apiPath: options.apiPath,
5403
+ fetch: options.fetch,
5404
+ collections: options.collections,
5405
+ schemaVersion: options.schemaVersion,
5406
+ headers: {
5407
+ ...options.headers ?? {},
5408
+ ...simulationHeaders(simulation)
5409
+ },
5410
+ realtime: false,
5411
+ auth: {
5412
+ storage: createMemoryStorage(),
5413
+ persistSession: false,
5414
+ autoRefresh: false
5415
+ }
5416
+ });
5417
+ derived.setAuthTokenGetter(() => transport.resolveToken());
5418
+ derived.setOnUnauthorized(() => onUnauthorized());
5419
+ return derived;
5420
+ },
4914
5421
  baseUrl: transport.baseUrl,
4915
5422
  apiPath: transport.apiPath,
4916
5423
  collection,
@@ -4950,6 +5457,6 @@ channel: (name, options) => {
4950
5457
  };
4951
5458
  }
4952
5459
  //#endregion
4953
- export { MemoryOfflineStore, RebaseApiError, RebaseClientError, RebasePaginationError, RebaseRealtimeChannel, RebaseWebSocketClient, STORAGE_REFERENCE_SCHEME, and, cond, createCookieStorage, createMemoryStorage, createRebaseClient, etagOf, isOfflineError, isStorageReference, not, or, parseStorageReference, resolveStorageReferences, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText };
5460
+ export { APPLE_JS_SDK_URL, MemoryOfflineStore, RebaseApiError, RebaseClientError, RebasePaginationError, RebaseRealtimeChannel, RebaseWebSocketClient, STORAGE_REFERENCE_SCHEME, and, cond, createCookieStorage, createMemoryStorage, createRebaseClient, etagOf, isOfflineError, isStorageReference, not, or, parseStorageReference, preloadAppleSignIn, requestAppleAuthorization, resolveStorageReferences, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText };
4954
5461
 
4955
5462
  //# sourceMappingURL=index.es.js.map