@biltme/backend 0.11.0 → 0.12.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/README.md CHANGED
@@ -39,10 +39,17 @@ the first attempt, then gives up and keeps the session. Requests waiting on the
39
39
  refresh wait that long. Set `auth.refreshRetryWindowMs` to change it; `0` tries
40
40
  once. supabase-js on its own retries for 30 seconds.
41
41
 
42
+ While a signed-in user's expired session can't be refreshed, data, storage and
43
+ function requests fail as if the network were down, with `status: 0` and the
44
+ message `SessionUnavailableError: …`. supabase-js on its own sends them with
45
+ the anon key instead, so reads come back empty and writes fail row-level
46
+ security with `42501`. An app that queues writes offline should retry these,
47
+ like any network error.
48
+
42
49
  On iOS and Android with `expo-network` installed, auto-refresh stops while the
43
50
  device is offline and starts again when it comes back, refreshing at once if
44
- the token is due. Without `expo-network`, or with `autoRefreshToken: false`,
45
- nothing changes.
51
+ the token is due, even if a refresh failed in the last minute. Without
52
+ `expo-network`, or with `autoRefreshToken: false`, nothing changes.
46
53
 
47
54
  Every supabase-js method works:
48
55
 
package/dist/index.d.ts CHANGED
@@ -92,8 +92,11 @@ export type TablesUpdate<Name extends keyof PublicTables> = PublicTables[Name] e
92
92
  * realtime channel throws because Bilt Cloud has no realtime (see {@link blockRealtime}),
93
93
  * the client has `notifications` (see {@link Notifications}), a session refresh
94
94
  * that fails on the network stops retrying after `auth.refreshRetryWindowMs`
95
- * (see {@link BiltAuthOptions}), and on React Native with `expo-network`
96
- * installed, auto-refresh pauses while the device is offline (see {@link pauseRefreshWhileOffline}).
95
+ * (see {@link BiltAuthOptions}), a request that would fall back to the anon key
96
+ * while the user's session cannot be refreshed fails like a network error
97
+ * instead (see {@link holdRequestsWithoutSession}), and on React Native with
98
+ * `expo-network` installed, auto-refresh pauses while the device is offline and
99
+ * retries at once when it comes back (see {@link pauseRefreshWhileOffline}).
97
100
  *
98
101
  * The second member of the intersection is supabase-js's own signature. An
99
102
  * intersection of function types is an overload set, so a bare call takes the
@@ -115,6 +118,7 @@ export type BiltClientOptions = NonNullable<Parameters<BareCall>[2]> & {
115
118
  };
116
119
  type BareCreateClient = (url: Parameters<BareCall>[0], key: Parameters<BareCall>[1], options?: BiltClientOptions) => BiltClient;
117
120
  export { REALTIME_NOT_SUPPORTED } from './realtime';
121
+ export { SessionUnavailableError } from './session';
118
122
  export type { BiltAuthOptions } from './refresh';
119
123
  export { NotificationsError } from './notifications';
120
124
  export type { Notifications, NotificationMessage, NotificationOutcome, NotificationSendResult, NotificationCounts, NotificationSendAllResult, } from './notifications';
package/dist/index.js CHANGED
@@ -11856,6 +11856,9 @@ async function loadNetwork() {
11856
11856
  return;
11857
11857
  }
11858
11858
  }
11859
+ function forgetRefreshFailure(auth) {
11860
+ Object.assign(auth, { lastRefreshFailure: null });
11861
+ }
11859
11862
  async function pauseRefreshWhileOffline(auth, options, load = loadNetwork) {
11860
11863
  if (!isReactNative() || options?.autoRefreshToken === false || options?.skipAutoInitialize)
11861
11864
  return;
@@ -11870,7 +11873,12 @@ async function pauseRefreshWhileOffline(auth, options, load = loadNetwork) {
11870
11873
  if (now === offline)
11871
11874
  return;
11872
11875
  offline = now;
11873
- now ? auth.stopAutoRefresh() : auth.startAutoRefresh();
11876
+ if (now) {
11877
+ auth.stopAutoRefresh();
11878
+ return;
11879
+ }
11880
+ forgetRefreshFailure(auth);
11881
+ auth.startAutoRefresh();
11874
11882
  };
11875
11883
  network.addNetworkStateListener((state) => {
11876
11884
  heard = true;
@@ -11881,6 +11889,47 @@ async function pauseRefreshWhileOffline(auth, options, load = loadNetwork) {
11881
11889
  apply(initial);
11882
11890
  }
11883
11891
 
11892
+ // src/session.ts
11893
+ class SessionUnavailableError extends TypeError {
11894
+ constructor() {
11895
+ super("The session has expired and could not be refreshed yet, so the request was not sent without it.");
11896
+ this.name = "SessionUnavailableError";
11897
+ }
11898
+ }
11899
+ function href(input) {
11900
+ if (typeof input === "string")
11901
+ return input;
11902
+ if (input instanceof URL)
11903
+ return input.href;
11904
+ return input.url;
11905
+ }
11906
+ function bearer(input, init) {
11907
+ const headers = new Headers(init?.headers ?? (typeof input === "object" && "headers" in input ? input.headers : undefined));
11908
+ return headers.get("Authorization")?.replace(/^Bearer /i, "") ?? null;
11909
+ }
11910
+ async function hasStoredSession(auth) {
11911
+ const { storage, storageKey } = auth;
11912
+ const raw = await storage.getItem(storageKey);
11913
+ if (!raw)
11914
+ return false;
11915
+ try {
11916
+ const session = JSON.parse(raw);
11917
+ return typeof session.refresh_token === "string" && session.refresh_token !== "";
11918
+ } catch {
11919
+ return false;
11920
+ }
11921
+ }
11922
+ function holdRequestsWithoutSession(url, key, auth, base) {
11923
+ const authUrl = `${url.trim().replace(/\/+$/, "")}/auth/v1/`;
11924
+ const held = async (input, init) => {
11925
+ if (!href(input).startsWith(authUrl) && bearer(input, init) === key && await hasStoredSession(auth())) {
11926
+ throw new SessionUnavailableError;
11927
+ }
11928
+ return (base ?? fetch)(input, init);
11929
+ };
11930
+ return Object.assign(held, { preconnect: (base ?? fetch).preconnect });
11931
+ }
11932
+
11884
11933
  // src/uploads.ts
11885
11934
  function readBytes(blob) {
11886
11935
  if (typeof FileReader === "undefined")
@@ -11997,7 +12046,8 @@ var createClient2 = (url, key, options) => {
11997
12046
  assertCredentials(url, key);
11998
12047
  const auth = options?.auth;
11999
12048
  const windowMs = refreshRetryWindow(auth);
12000
- const client = createClient(url, key, options);
12049
+ const fetch2 = holdRequestsWithoutSession(url, key, () => client.auth, options?.global?.fetch);
12050
+ const client = createClient(url, key, { ...options, global: { ...options?.global, fetch: fetch2 } });
12001
12051
  setRefreshRetryWindow(client.auth, windowMs);
12002
12052
  pauseRefreshWhileOffline(client.auth, auth).catch(() => {
12003
12053
  return;
@@ -12018,6 +12068,7 @@ export {
12018
12068
  export_FunctionsRelayError as FunctionsRelayError,
12019
12069
  NotificationsError,
12020
12070
  REALTIME_NOT_SUPPORTED,
12071
+ SessionUnavailableError,
12021
12072
  StorageApiError,
12022
12073
  asyncStorage,
12023
12074
  createClient2 as createClient,
package/dist/refresh.d.ts CHANGED
@@ -31,8 +31,8 @@ type PauseOptions = {
31
31
  };
32
32
  /**
33
33
  * On React Native with `expo-network` installed, stops the auto-refresh ticker
34
- * while the device is offline and starts it again, refreshing at once if due,
35
- * when it comes back.
34
+ * while the device is offline and starts it again when it comes back,
35
+ * refreshing at once if due, even within auth-js's cooldown after a failed refresh.
36
36
  */
37
37
  export declare function pauseRefreshWhileOffline(auth: Auth, options: PauseOptions | undefined, load?: () => Promise<Network | undefined>): Promise<void>;
38
38
  export {};
@@ -0,0 +1,24 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ type Auth = SupabaseClient<any, any, any>['auth'];
3
+ /**
4
+ * Thrown in place of a request that would have gone out with the anon key
5
+ * while a signed-in session is stored but could not be refreshed, usually
6
+ * because the network is down. Callers see it as a failed fetch: postgrest-js
7
+ * reports `status: 0` and the message `SessionUnavailableError: …`.
8
+ */
9
+ export declare class SessionUnavailableError extends TypeError {
10
+ constructor();
11
+ }
12
+ /**
13
+ * Wraps the client's fetch so a data, storage or function request that carries
14
+ * the anon key while a session is stored fails like a network error instead.
15
+ *
16
+ * supabase-js sends the anon key whenever `getSession()` returns no session,
17
+ * and it returns none while a due refresh is failing or cooling down after a
18
+ * failure. auth-js removes the stored session when a refresh fails for good,
19
+ * so a stored one means the user is still signed in. Sent anyway, the request
20
+ * runs as `anon`: reads come back empty and writes fail RLS with `42501`,
21
+ * which an offline queue takes as permanent and drops.
22
+ */
23
+ export declare function holdRequestsWithoutSession(url: string, key: string, auth: () => Auth, base?: typeof fetch): typeof fetch;
24
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@biltme/backend",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Bilt backend SDK — thin shim over @supabase/supabase-js for bilt-cloud projects",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",