@rebasepro/client 0.27.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Transport } from "./transport.js";
2
- import type { AuthConfigDocument, AuthChangeEvent, RebaseSession, DeviceSession, User } from "@rebasepro/types";
2
+ import type { AuthConfigDocument, AuthChangeEvent, RebaseSession, AuthTokens, DeviceSession, User } from "@rebasepro/types";
3
3
  export type { RebaseSession, AuthTokens, AuthChangeEvent, DeviceSession } from "@rebasepro/types";
4
4
  /** Minimal, non-sensitive user profile returned by {@link findUserByEmail}. */
5
5
  export interface PublicUserProfile {
@@ -315,6 +315,8 @@ export declare function createAuth(transport: Transport, options?: CreateAuthOpt
315
315
  * URL with an expiry, so copy the bytes rather than storing this.
316
316
  */
317
317
  photoURL?: string | null;
318
+ tokens?: AuthTokens;
319
+ user?: Record<string, unknown>;
318
320
  }>;
319
321
  sendVerificationEmail: () => Promise<{
320
322
  success: boolean;
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
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";
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-Cxhh99Q-.js";
2
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";
@@ -440,13 +440,14 @@ function createAuth(transport, options) {
440
440
  * round trip of latency each.
441
441
  *
442
442
  * The refresh is {@link refreshSession}, so a burst of requests shares one
443
- * (the one started at load included). A refresh that fails hands back the
444
- * token the request would have carried anyway: the 401 path then does
445
- * exactly what it always did. One whose session ended while it ran hands
446
- * back nothing, so the transport sends what it holds now — no token after
447
- * a sign-out, the new account's after a sign-in — and never the token of
448
- * the account that has gone. The realtime socket authenticates through
449
- * this same path.
443
+ * (the one started at load included). A refresh that fails without the
444
+ * refresh token being refused hands back the token the request would have
445
+ * carried anyway: the 401 path then does exactly what it always did. One
446
+ * refused, or one whose session ended while it ran, hands back nothing, so
447
+ * the transport sends what it holds now — no token after a sign-out or a
448
+ * refused restore, the new account's after a sign-in — and never the
449
+ * token of the account that has gone. The realtime socket authenticates
450
+ * through this same path.
450
451
  */
451
452
  function tokenForRequest() {
452
453
  if (refreshOwnRequests > 0) return void 0;
@@ -454,7 +455,7 @@ function createAuth(transport, options) {
454
455
  if (!session) return cookieRestore?.then(() => void 0);
455
456
  if (!needsFreshToken(session)) return void 0;
456
457
  const epoch = sessionEpoch;
457
- return refreshSession().then((fresh) => epoch === sessionEpoch ? fresh.accessToken : void 0, () => epoch === sessionEpoch ? session.accessToken : void 0);
458
+ return refreshSession().then((fresh) => epoch === sessionEpoch ? fresh.accessToken : void 0, (err) => epoch === sessionEpoch && !isFatalRefreshError(err) ? session.accessToken : void 0);
458
459
  }
459
460
  transport.setTokenRefresher?.(tokenForRequest);
460
461
  async function attemptScheduledRefresh(attempt) {
@@ -1021,12 +1022,21 @@ function createAuth(transport, options) {
1021
1022
  * Throws `IDENTITY_ALREADY_LINKED` (409) if that provider identity is
1022
1023
  * attached to a different user. Succeeds idempotently (`alreadyLinked:
1023
1024
  * true`) if it is already attached to the current one.
1025
+ *
1026
+ * From an anonymous session the link makes the guest an account: the
1027
+ * account's session replaces the guest's and `USER_UPDATED` is emitted.
1024
1028
  */
1025
1029
  async function linkProvider(providerId, payload) {
1026
- return transport.request(authPath + "/link/" + providerId, {
1030
+ const result = await transport.request(authPath + "/link/" + providerId, {
1027
1031
  method: "POST",
1028
- body: JSON.stringify(payload)
1032
+ body: JSON.stringify(payload),
1033
+ credentials: authFlowMode === "cookie" ? "include" : void 0
1029
1034
  });
1035
+ if (result.tokens && result.user) handleAuthResponse({
1036
+ tokens: result.tokens,
1037
+ user: result.user
1038
+ }, "USER_UPDATED");
1039
+ return result;
1030
1040
  }
1031
1041
  async function sendVerificationEmail() {
1032
1042
  return transport.request(authPath + "/send-verification", { method: "POST" });
@@ -1251,7 +1261,8 @@ function createAuth(transport, options) {
1251
1261
  body: JSON.stringify({
1252
1262
  email,
1253
1263
  password
1254
- })
1264
+ }),
1265
+ credentials: authFlowMode === "cookie" ? "include" : void 0
1255
1266
  }), "USER_UPDATED");
1256
1267
  return {
1257
1268
  user: session.user,
@@ -1353,7 +1364,8 @@ function createAuth(transport, options) {
1353
1364
  });
1354
1365
  const session = handleAuthResponse(options?.mfaToken ? await withPendingToken("/mfa/challenge/verify", payload, options.mfaToken) : await transport.request(authPath + "/mfa/challenge/verify", {
1355
1366
  method: "POST",
1356
- body: payload
1367
+ body: payload,
1368
+ credentials: authFlowMode === "cookie" ? "include" : void 0
1357
1369
  }), "SIGNED_IN");
1358
1370
  return {
1359
1371
  user: session.user,
@@ -1537,7 +1549,7 @@ function createAuth(transport, options) {
1537
1549
  getSession,
1538
1550
  getAccessToken,
1539
1551
  onAuthStateChange,
1540
- canRestoreSession: () => persistSession || authFlowMode === "cookie",
1552
+ canRestoreSession: () => persistSession,
1541
1553
  isInitialized: () => isInitialized,
1542
1554
  /**
1543
1555
  * How restoring the session on load ended — see
@@ -1962,8 +1974,8 @@ function createFunctionsClient(transport) {
1962
1974
  code: "INVALID_FUNCTION_NAME",
1963
1975
  details: { name }
1964
1976
  });
1965
- const pathPart = (options?.path ?? "").split(/[?#]/)[0];
1966
- if (isDotSegment(name) || pathPart.split("/").some(isDotSegment)) throw new RebaseClientError$1(`Invalid function route "${name}${options?.path ? ` + ${options.path}` : ""}": a \`.\` or \`..\` segment would leave /functions/` + name + ".", {
1977
+ const pathPart = (options?.path ?? "").replace(/[\t\n\r]/g, "").split(/[?#]/)[0];
1978
+ if (isDotSegment(name) || pathPart.split(/[/\\]/).some(isDotSegment)) throw new RebaseClientError$1(`Invalid function route "${name}${options?.path ? ` + ${options.path}` : ""}": a \`.\` or \`..\` segment would leave /functions/` + name + ".", {
1967
1979
  code: "INVALID_FUNCTION_PATH",
1968
1980
  details: {
1969
1981
  name,
@@ -2018,9 +2030,16 @@ function createFunctionsClient(transport) {
2018
2030
  * other character is encoded, including a literal `%`. Verified to round-trip
2019
2031
  * through the server's decode for all of the above, plus `+`, accented
2020
2032
  * characters and a trailing `%`.
2033
+ *
2034
+ * Throws `INVALID_STORAGE_KEY` for a key with a `..` segment.
2021
2035
  */
2022
2036
  function encodeStorageKey(key) {
2023
- return key.split("/").map(encodeURIComponent).join("/");
2037
+ const segments = key.split("/");
2038
+ if (segments.includes("..")) throw new RebaseClientError$1(`Storage key ${JSON.stringify(key)} contains a '..' path segment. Keys must name an object directly.`, {
2039
+ code: "INVALID_STORAGE_KEY",
2040
+ details: { key }
2041
+ });
2042
+ return segments.map(encodeURIComponent).join("/");
2024
2043
  }
2025
2044
  /**
2026
2045
  * The fields of an upload's form, as the resumable endpoint's
@@ -3491,10 +3510,7 @@ var RebaseWebSocketClient = class {
3491
3510
  if (collectionSub.subscribeTimeout) clearTimeout(collectionSub.subscribeTimeout);
3492
3511
  collectionSub.subscribeTimeout = void 0;
3493
3512
  collectionSub.subscribeInFlight = false;
3494
- const error = frameError(message);
3495
- collectionSub.callbacks.forEach((callback) => {
3496
- if (callback.onError) callback.onError(error);
3497
- });
3513
+ this.notifyError(collectionSub.callbacks, frameError(message));
3498
3514
  return;
3499
3515
  }
3500
3516
  }
@@ -3509,10 +3525,7 @@ var RebaseWebSocketClient = class {
3509
3525
  if (entitySub.subscribeTimeout) clearTimeout(entitySub.subscribeTimeout);
3510
3526
  entitySub.subscribeTimeout = void 0;
3511
3527
  entitySub.subscribeInFlight = false;
3512
- const error = frameError(message);
3513
- entitySub.callbacks.forEach((callback) => {
3514
- if (callback.onError) callback.onError(error);
3515
- });
3528
+ this.notifyError(entitySub.callbacks, frameError(message));
3516
3529
  return;
3517
3530
  }
3518
3531
  }
@@ -4455,7 +4468,9 @@ var RebaseRealtimeChannel = class {
4455
4468
  const onConnectionLost = this.transport.onConnectionLost?.((error) => this.emitError(error));
4456
4469
  if (onConnectionLost) this.unsubscribers.push(onConnectionLost);
4457
4470
  await this.send("join_channel");
4471
+ if (!this.joined) return;
4458
4472
  await this.send("presence_state");
4473
+ if (!this.joined) return;
4459
4474
  if (this.wantsHistory) await this.requestHistory();
4460
4475
  }
4461
4476
  /** Consecutive re-joins asked for by refusals, for the backoff; reset after a quiet minute. */
@@ -4539,8 +4554,10 @@ var RebaseRealtimeChannel = class {
4539
4554
  */
4540
4555
  async track(state) {
4541
4556
  await this.join();
4557
+ if (!this.joined) return;
4542
4558
  this.trackedState = state;
4543
4559
  await this.send("presence_track", { state });
4560
+ if (!this.joined || this.trackedState !== state) return;
4544
4561
  if (!this.heartbeat) {
4545
4562
  this.heartbeat = setInterval(() => {
4546
4563
  if (!this.trackedState) return;
@@ -4881,12 +4898,27 @@ var RebaseRealtimeChannel = class {
4881
4898
  this.deliver(event);
4882
4899
  }
4883
4900
  }
4901
+ /**
4902
+ * Hand an event to every broadcast handler, each isolated from the
4903
+ * others. A throw is reported and goes no further: this runs in the middle
4904
+ * of a replay or a flush, and one escaping it would end that pass with the
4905
+ * catch-up still marked in flight and its timeout already cleared, so every
4906
+ * later message on the channel would be held back for good.
4907
+ */
4884
4908
  deliver(event) {
4885
- for (const handler of [...this.broadcastHandlers]) handler(event);
4909
+ for (const handler of [...this.broadcastHandlers]) try {
4910
+ handler(event);
4911
+ } catch (e) {
4912
+ console.error("Error in channel broadcast handler:", e);
4913
+ }
4886
4914
  }
4887
4915
  emitPresence(diff) {
4888
4916
  const snapshot = { ...this.presences };
4889
- for (const handler of this.presenceHandlers) handler(snapshot, diff);
4917
+ for (const handler of [...this.presenceHandlers]) try {
4918
+ handler(snapshot, diff);
4919
+ } catch (e) {
4920
+ console.error("Error in channel presence handler:", e);
4921
+ }
4890
4922
  }
4891
4923
  };
4892
4924
  /**
@@ -4935,7 +4967,7 @@ var LazyOfflineManager = class {
4935
4967
  keepsLastUser;
4936
4968
  constructor(config, createInner) {
4937
4969
  this.keepsLastUser = config.keepLastUser === true;
4938
- import("./offline-AvuEcg7u.js").then(({ OfflineManager: Engine }) => {
4970
+ import("./offline-BjJdcVBb.js").then(({ OfflineManager: Engine }) => {
4939
4971
  const engine = new Engine(config, createInner);
4940
4972
  this.engine = engine;
4941
4973
  const queued = this.queued;
@@ -5180,7 +5212,7 @@ function createRebaseClient(options) {
5180
5212
  if (event === "SIGNED_OUT") {
5181
5213
  realtimeUid = null;
5182
5214
  ws.disconnect();
5183
- } else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
5215
+ } else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED" || event === "USER_UPDATED") {
5184
5216
  const uid = session?.user?.uid ?? null;
5185
5217
  if (uid !== realtimeUid) {
5186
5218
  realtimeUid = uid;