@rebasepro/client 0.10.1-canary.31c773c → 0.10.1-canary.3d09338
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 +1 -0
- package/dist/index.es.js +120 -29
- package/dist/index.es.js.map +1 -1
- package/dist/transport.d.ts +16 -0
- package/package.json +5 -4
- package/src/auth.ts +110 -3
- package/src/index.ts +6 -16
- package/src/offline-sync-engine.test.ts +53 -2
- package/src/offline.ts +46 -6
- package/src/storage.ts +11 -3
- package/src/transport.ts +17 -0
package/dist/auth.d.ts
CHANGED
|
@@ -129,6 +129,7 @@ export declare function createAuth(transport: Transport, options?: CreateAuthOpt
|
|
|
129
129
|
}>;
|
|
130
130
|
signOut: () => Promise<void>;
|
|
131
131
|
refreshSession: () => Promise<RebaseSession>;
|
|
132
|
+
handleUnauthorized: () => Promise<boolean>;
|
|
132
133
|
getUser: () => Promise<User>;
|
|
133
134
|
findUserByEmail: (email: string) => Promise<PublicUserProfile | null>;
|
|
134
135
|
updateUser: (updates: {
|
package/dist/index.es.js
CHANGED
|
@@ -170,6 +170,9 @@ function createTransport(config) {
|
|
|
170
170
|
get apiPath() {
|
|
171
171
|
return apiPath;
|
|
172
172
|
},
|
|
173
|
+
get storageUrlOrigin() {
|
|
174
|
+
return config.storageUrlOrigin?.replace(/\/$/, "") || void 0;
|
|
175
|
+
},
|
|
173
176
|
get fetchFn() {
|
|
174
177
|
return fetchFn;
|
|
175
178
|
},
|
|
@@ -295,19 +298,67 @@ function createAuth(transport, options) {
|
|
|
295
298
|
*/
|
|
296
299
|
function isFatalRefreshError(err) {
|
|
297
300
|
if (!(err instanceof RebaseApiError)) return false;
|
|
301
|
+
if (err.code === "TOKEN_ALREADY_USED") return false;
|
|
298
302
|
if (err.code === "INVALID_TOKEN" || err.code === "TOKEN_EXPIRED") return true;
|
|
299
303
|
return err.status === 401 || err.status === 403;
|
|
300
304
|
}
|
|
305
|
+
/**
|
|
306
|
+
* Drop this client's session without telling the server.
|
|
307
|
+
*
|
|
308
|
+
* `signOut()` is a user action: it POSTs /logout, which revokes the whole
|
|
309
|
+
* sign-in. That is the wrong hammer for a refresh that failed. Our token
|
|
310
|
+
* may be stale precisely because a sibling tab holds a live one, and
|
|
311
|
+
* logging out on its behalf would turn one tab's bad luck into everybody
|
|
312
|
+
* being signed out — the exact failure this work exists to remove.
|
|
313
|
+
*/
|
|
314
|
+
function abandonSessionLocally() {
|
|
315
|
+
currentSession = null;
|
|
316
|
+
clearStoredSession();
|
|
317
|
+
if (refreshTimeout) {
|
|
318
|
+
clearTimeout(refreshTimeout);
|
|
319
|
+
refreshTimeout = null;
|
|
320
|
+
}
|
|
321
|
+
transport.setToken(null);
|
|
322
|
+
emit("SIGNED_OUT", null);
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Recover from a 401 on an ordinary API request.
|
|
326
|
+
*
|
|
327
|
+
* Returns `true` when the caller should retry — we minted a fresh access
|
|
328
|
+
* token. When the refresh is rejected *fatally* (the refresh token itself
|
|
329
|
+
* is invalid, expired or revoked) this client can no longer act as the
|
|
330
|
+
* user at all, so we drop the session and emit `SIGNED_OUT`. UIs gate on
|
|
331
|
+
* that event, so they show their login screen instead of leaving the user
|
|
332
|
+
* staring at "Invalid or expired token" on every view.
|
|
333
|
+
*
|
|
334
|
+
* Transient failures (offline, 5xx, backend restarting) keep the session:
|
|
335
|
+
* the scheduled refresh backs off and retries, and the token is very
|
|
336
|
+
* likely still good once the backend answers again.
|
|
337
|
+
*/
|
|
338
|
+
async function handleUnauthorized() {
|
|
339
|
+
if (!currentSession) return false;
|
|
340
|
+
if (authFlowMode !== "cookie" && !currentSession.refreshToken) {
|
|
341
|
+
abandonSessionLocally();
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
try {
|
|
345
|
+
await refreshSession();
|
|
346
|
+
return true;
|
|
347
|
+
} catch (err) {
|
|
348
|
+
if (isFatalRefreshError(err)) abandonSessionLocally();
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
301
352
|
async function attemptScheduledRefresh(attempt) {
|
|
302
353
|
try {
|
|
303
354
|
await refreshSession();
|
|
304
355
|
} catch (err) {
|
|
305
356
|
if (isFatalRefreshError(err)) {
|
|
306
|
-
|
|
357
|
+
abandonSessionLocally();
|
|
307
358
|
return;
|
|
308
359
|
}
|
|
309
360
|
if (attempt >= MAX_REFRESH_RETRIES) {
|
|
310
|
-
|
|
361
|
+
abandonSessionLocally();
|
|
311
362
|
return;
|
|
312
363
|
}
|
|
313
364
|
const backoff = Math.min(REFRESH_RETRY_BASE_MS * 2 ** attempt, REFRESH_RETRY_MAX_MS);
|
|
@@ -528,9 +579,42 @@ function createAuth(transport, options) {
|
|
|
528
579
|
transport.setToken(null);
|
|
529
580
|
emit("SIGNED_OUT", null);
|
|
530
581
|
}
|
|
582
|
+
/**
|
|
583
|
+
* Serialise refreshes across TABS, not just within one.
|
|
584
|
+
*
|
|
585
|
+
* The in-flight promise below covers callers inside a single JavaScript
|
|
586
|
+
* context. It does nothing about the far more common case: two tabs of the
|
|
587
|
+
* same app booting together, each firing its own /refresh with the same
|
|
588
|
+
* cookie. The server tolerates that now (superseded tokens stay usable for
|
|
589
|
+
* a grace window), but tolerating a stampede is not the same as avoiding
|
|
590
|
+
* one, and every extra rotation is another chance to end up holding a
|
|
591
|
+
* token whose response never arrived.
|
|
592
|
+
*
|
|
593
|
+
* Web Locks are best-effort on purpose. supabase-js shipped this and then
|
|
594
|
+
* spent a year fielding deadlock reports — a lock held by a crashed or
|
|
595
|
+
* frozen tab must never be able to wedge sign-in — so a lock we cannot
|
|
596
|
+
* take within the timeout is simply not taken, and the refresh proceeds
|
|
597
|
+
* unserialised, exactly as it did before.
|
|
598
|
+
*/
|
|
599
|
+
const REFRESH_LOCK_NAME = "rebase-auth-refresh";
|
|
600
|
+
const REFRESH_LOCK_TIMEOUT_MS = 5e3;
|
|
601
|
+
async function withRefreshLock(fn) {
|
|
602
|
+
const locks = globalThis.navigator?.locks;
|
|
603
|
+
if (!locks?.request) return fn();
|
|
604
|
+
const controller = new AbortController();
|
|
605
|
+
const giveUp = setTimeout(() => controller.abort(), REFRESH_LOCK_TIMEOUT_MS);
|
|
606
|
+
try {
|
|
607
|
+
return await locks.request(REFRESH_LOCK_NAME, { signal: controller.signal }, async () => fn());
|
|
608
|
+
} catch (e) {
|
|
609
|
+
if (e?.name !== "AbortError") throw e;
|
|
610
|
+
return fn();
|
|
611
|
+
} finally {
|
|
612
|
+
clearTimeout(giveUp);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
531
615
|
function refreshSession() {
|
|
532
616
|
if (inFlightRefresh) return inFlightRefresh;
|
|
533
|
-
inFlightRefresh = doRefreshSession().finally(() => {
|
|
617
|
+
inFlightRefresh = withRefreshLock(() => doRefreshSession()).finally(() => {
|
|
534
618
|
inFlightRefresh = null;
|
|
535
619
|
});
|
|
536
620
|
return inFlightRefresh;
|
|
@@ -766,6 +850,7 @@ function createAuth(transport, options) {
|
|
|
766
850
|
signInWithSpotify,
|
|
767
851
|
signOut,
|
|
768
852
|
refreshSession,
|
|
853
|
+
handleUnauthorized,
|
|
769
854
|
getUser,
|
|
770
855
|
findUserByEmail,
|
|
771
856
|
updateUser,
|
|
@@ -1307,6 +1392,12 @@ function createFunctionsClient(transport) {
|
|
|
1307
1392
|
*/
|
|
1308
1393
|
function createStorage(transport, storageId) {
|
|
1309
1394
|
const urlsCache = /* @__PURE__ */ new Map();
|
|
1395
|
+
/**
|
|
1396
|
+
* Base for URLs the *browser* will fetch on its own (file downloads,
|
|
1397
|
+
* previews). API requests keep going to `baseUrl`; see
|
|
1398
|
+
* {@link RebaseClientConfig.storageUrlOrigin} for why these can differ.
|
|
1399
|
+
*/
|
|
1400
|
+
const fileUrlBase = () => `${transport.storageUrlOrigin ?? transport.baseUrl}${transport.apiPath}`;
|
|
1310
1401
|
/** Append ?storageId=... to a path when multi-backend routing is active. */
|
|
1311
1402
|
const withStorageId = (path) => {
|
|
1312
1403
|
if (!storageId) return path;
|
|
@@ -1344,7 +1435,7 @@ function createStorage(transport, storageId) {
|
|
|
1344
1435
|
fileNotFound: true
|
|
1345
1436
|
};
|
|
1346
1437
|
if (isPublicStoragePath(filePath)) {
|
|
1347
|
-
const publicConfig = { url: withStorageId(`${
|
|
1438
|
+
const publicConfig = { url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}`) };
|
|
1348
1439
|
urlsCache.set(cacheKey, { config: publicConfig });
|
|
1349
1440
|
return publicConfig;
|
|
1350
1441
|
}
|
|
@@ -1352,7 +1443,7 @@ function createStorage(transport, storageId) {
|
|
|
1352
1443
|
const result = await transport.request(withStorageId(`/storage/metadata/${filePath}`));
|
|
1353
1444
|
if (result.data.public) {
|
|
1354
1445
|
const publicConfig = {
|
|
1355
|
-
url: withStorageId(`${
|
|
1446
|
+
url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}`),
|
|
1356
1447
|
metadata: result.data
|
|
1357
1448
|
};
|
|
1358
1449
|
urlsCache.set(cacheKey, { config: publicConfig });
|
|
@@ -1361,7 +1452,7 @@ function createStorage(transport, storageId) {
|
|
|
1361
1452
|
const scopedToken = result.data.token;
|
|
1362
1453
|
const tokenQuery = scopedToken ? `?token=${scopedToken}` : "";
|
|
1363
1454
|
const downloadConfig = {
|
|
1364
|
-
url: withStorageId(`${
|
|
1455
|
+
url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}${tokenQuery}`),
|
|
1365
1456
|
metadata: result.data
|
|
1366
1457
|
};
|
|
1367
1458
|
const expiresAt = result.data.tokenExpiresIn ? Date.now() + (result.data.tokenExpiresIn - 10) * 1e3 : void 0;
|
|
@@ -3829,6 +3920,8 @@ var OfflineManager = class {
|
|
|
3829
3920
|
for (const slug of slugs) this.collections.set(slug, {
|
|
3830
3921
|
rows: /* @__PURE__ */ new Map(),
|
|
3831
3922
|
snapshots: /* @__PURE__ */ new Map(),
|
|
3923
|
+
fresh: /* @__PURE__ */ new Set(),
|
|
3924
|
+
freshRows: /* @__PURE__ */ new Set(),
|
|
3832
3925
|
absent: /* @__PURE__ */ new Set(),
|
|
3833
3926
|
ready: true
|
|
3834
3927
|
});
|
|
@@ -3874,6 +3967,7 @@ var OfflineManager = class {
|
|
|
3874
3967
|
this.connectivity.markFailure();
|
|
3875
3968
|
}
|
|
3876
3969
|
const answer = this.localFind(slug, params);
|
|
3970
|
+
this.notifyCollection(slug, false);
|
|
3877
3971
|
return {
|
|
3878
3972
|
data: answer.data,
|
|
3879
3973
|
meta: answer.meta
|
|
@@ -4065,7 +4159,7 @@ var OfflineManager = class {
|
|
|
4065
4159
|
emit: () => {
|
|
4066
4160
|
if (closed || !this.collections.get(slug)?.ready) return;
|
|
4067
4161
|
const result = this.answer(slug, params, this.snapshotFor(slug, params));
|
|
4068
|
-
const signature = this.signature(slug, result.data, result.meta.total);
|
|
4162
|
+
const signature = `${result.fromCache ? "c" : "s"}${result.hasPendingWrites ? "p" : "-"}` + this.signature(slug, result.data, result.meta.total);
|
|
4069
4163
|
if (observer.settled && signature === observer.signature) return;
|
|
4070
4164
|
observer.signature = signature;
|
|
4071
4165
|
observer.settled = true;
|
|
@@ -4117,13 +4211,15 @@ var OfflineManager = class {
|
|
|
4117
4211
|
if (closed || !this.collections.get(slug)?.ready) return;
|
|
4118
4212
|
const row = this.localRow(slug, id);
|
|
4119
4213
|
const entry = this.collections.get(slug)?.rows.get(String(id));
|
|
4120
|
-
const
|
|
4214
|
+
const fromCache = !this.collections.get(slug)?.freshRows.has(String(id));
|
|
4215
|
+
const hasPendingWrites = this.hasPending(slug, id);
|
|
4216
|
+
const signature = `${fromCache ? "c" : "s"}${hasPendingWrites ? "p" : "-"}|` + (row === void 0 ? MISSING : `${String(id)}:${entry?.rev ?? 0}`);
|
|
4121
4217
|
if (observer.settled && signature === observer.signature) return;
|
|
4122
4218
|
observer.signature = signature;
|
|
4123
4219
|
observer.settled = true;
|
|
4124
4220
|
onResult(row, {
|
|
4125
|
-
fromCache
|
|
4126
|
-
hasPendingWrites
|
|
4221
|
+
fromCache,
|
|
4222
|
+
hasPendingWrites
|
|
4127
4223
|
});
|
|
4128
4224
|
}
|
|
4129
4225
|
};
|
|
@@ -4194,6 +4290,8 @@ var OfflineManager = class {
|
|
|
4194
4290
|
state = {
|
|
4195
4291
|
rows: /* @__PURE__ */ new Map(),
|
|
4196
4292
|
snapshots: /* @__PURE__ */ new Map(),
|
|
4293
|
+
fresh: /* @__PURE__ */ new Set(),
|
|
4294
|
+
freshRows: /* @__PURE__ */ new Set(),
|
|
4197
4295
|
absent: /* @__PURE__ */ new Set(),
|
|
4198
4296
|
ready: false
|
|
4199
4297
|
};
|
|
@@ -4253,6 +4351,7 @@ var OfflineManager = class {
|
|
|
4253
4351
|
answer(slug, params, snapshot) {
|
|
4254
4352
|
const state = this.collections.get(slug);
|
|
4255
4353
|
const exact = isExactlyEvaluable(params);
|
|
4354
|
+
const fromCache = !state?.fresh.has(buildQueryString(params));
|
|
4256
4355
|
if (!state) return {
|
|
4257
4356
|
data: [],
|
|
4258
4357
|
meta: {
|
|
@@ -4269,7 +4368,7 @@ var OfflineManager = class {
|
|
|
4269
4368
|
const local = runLocalQuery([...state.rows.values()].map((e) => e.row), params);
|
|
4270
4369
|
return {
|
|
4271
4370
|
...local,
|
|
4272
|
-
fromCache
|
|
4371
|
+
fromCache,
|
|
4273
4372
|
hasPendingWrites: local.data.some((row) => this.hasPending(slug, row.id)),
|
|
4274
4373
|
partial: true
|
|
4275
4374
|
};
|
|
@@ -4312,7 +4411,7 @@ var OfflineManager = class {
|
|
|
4312
4411
|
offset,
|
|
4313
4412
|
hasMore: snapshot.hasMore
|
|
4314
4413
|
},
|
|
4315
|
-
fromCache
|
|
4414
|
+
fromCache,
|
|
4316
4415
|
hasPendingWrites: rows.some((row) => this.hasPending(slug, row.id)),
|
|
4317
4416
|
partial: !exact
|
|
4318
4417
|
};
|
|
@@ -4320,6 +4419,7 @@ var OfflineManager = class {
|
|
|
4320
4419
|
localFind(slug, params) {
|
|
4321
4420
|
const state = this.collections.get(slug);
|
|
4322
4421
|
const snapshot = this.snapshotFor(slug, params);
|
|
4422
|
+
state?.fresh.delete(buildQueryString(params));
|
|
4323
4423
|
if (!snapshot && (!state || state.rows.size === 0)) throw offlineError(`Offline: no cached data for "${slug}".`);
|
|
4324
4424
|
const answer = this.answer(slug, params, snapshot);
|
|
4325
4425
|
return snapshot ? answer : {
|
|
@@ -4343,6 +4443,7 @@ var OfflineManager = class {
|
|
|
4343
4443
|
cachedAt,
|
|
4344
4444
|
rev: ++this.revCounter
|
|
4345
4445
|
});
|
|
4446
|
+
state.freshRows.delete(key);
|
|
4346
4447
|
this.forgetTombstone(slug, key);
|
|
4347
4448
|
this.writeCache(this.rowKey(slug, key), dehydrateRow(row), cachedAt);
|
|
4348
4449
|
this.evictRows(slug);
|
|
@@ -4359,8 +4460,9 @@ var OfflineManager = class {
|
|
|
4359
4460
|
const existed = state.rows.delete(key);
|
|
4360
4461
|
if (known) {
|
|
4361
4462
|
state.absent.add(key);
|
|
4463
|
+
state.freshRows.add(key);
|
|
4362
4464
|
this.writeCache(this.absentKey(slug, key), true);
|
|
4363
|
-
}
|
|
4465
|
+
} else state.freshRows.delete(key);
|
|
4364
4466
|
if (existed) this.deleteCache([this.rowKey(slug, key)]);
|
|
4365
4467
|
}
|
|
4366
4468
|
forgetTombstone(slug, key) {
|
|
@@ -4392,6 +4494,7 @@ var OfflineManager = class {
|
|
|
4392
4494
|
continue;
|
|
4393
4495
|
}
|
|
4394
4496
|
this.forgetTombstone(slug, key);
|
|
4497
|
+
state.freshRows.add(key);
|
|
4395
4498
|
const existing = state.rows.get(key);
|
|
4396
4499
|
if (existing && JSON.stringify(existing.row) === JSON.stringify(merged)) {
|
|
4397
4500
|
existing.cachedAt = cachedAt;
|
|
@@ -4462,6 +4565,7 @@ var OfflineManager = class {
|
|
|
4462
4565
|
const state = this.collectionState(slug);
|
|
4463
4566
|
const key = buildQueryString(params);
|
|
4464
4567
|
state.snapshots.set(key, snapshot);
|
|
4568
|
+
state.fresh.add(key);
|
|
4465
4569
|
this.writeCache(`${this.scope}|q|${slug}|${key}`, snapshot);
|
|
4466
4570
|
this.evictSnapshots(slug);
|
|
4467
4571
|
return snapshot;
|
|
@@ -4725,6 +4829,7 @@ var OfflineManager = class {
|
|
|
4725
4829
|
cachedAt,
|
|
4726
4830
|
rev: ++this.revCounter
|
|
4727
4831
|
});
|
|
4832
|
+
if (this.applyPendingToRow(slug, key, void 0, op.mutationId) === void 0) state.freshRows.add(key);
|
|
4728
4833
|
this.writeCache(this.rowKey(slug, key), dehydrateRow(merged), cachedAt);
|
|
4729
4834
|
}
|
|
4730
4835
|
/**
|
|
@@ -4964,14 +5069,7 @@ function createRebaseClient(options) {
|
|
|
4964
5069
|
} catch (e) {}
|
|
4965
5070
|
return session?.accessToken || options.token || "";
|
|
4966
5071
|
},
|
|
4967
|
-
onUnauthorized: options.onUnauthorized || (
|
|
4968
|
-
try {
|
|
4969
|
-
await auth.refreshSession();
|
|
4970
|
-
return true;
|
|
4971
|
-
} catch (e) {
|
|
4972
|
-
return false;
|
|
4973
|
-
}
|
|
4974
|
-
})
|
|
5072
|
+
onUnauthorized: options.onUnauthorized || (() => auth.handleUnauthorized())
|
|
4975
5073
|
});
|
|
4976
5074
|
auth.onAuthStateChange((event, session) => {
|
|
4977
5075
|
if (!ws) return;
|
|
@@ -4981,14 +5079,7 @@ function createRebaseClient(options) {
|
|
|
4981
5079
|
}
|
|
4982
5080
|
});
|
|
4983
5081
|
}
|
|
4984
|
-
if (!options.onUnauthorized) transport.setOnUnauthorized(
|
|
4985
|
-
try {
|
|
4986
|
-
await auth.refreshSession();
|
|
4987
|
-
return true;
|
|
4988
|
-
} catch (e) {
|
|
4989
|
-
return false;
|
|
4990
|
-
}
|
|
4991
|
-
});
|
|
5082
|
+
if (!options.onUnauthorized) transport.setOnUnauthorized(() => auth.handleUnauthorized());
|
|
4992
5083
|
/**
|
|
4993
5084
|
* Suggest the closest known collection key for a mistyped accessor.
|
|
4994
5085
|
* Uses edit-distance-1 and prefix matching — no external dependency.
|