mnfst 0.5.305 → 0.5.307
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/lib/manifest.appwrite.auth.js +21 -0
- package/lib/manifest.appwrite.data.js +1 -1
- package/lib/manifest.appwrite.presences.js +629 -88
- package/lib/manifest.data.js +1 -1
- package/lib/manifest.integrity.json +6 -6
- package/lib/manifest.sw.js +1 -1
- package/lib/manifest.utilities.js +12 -1
- package/lib/manifest.utilities.node.mjs +12 -1
- package/package.json +3 -1
|
@@ -541,6 +541,16 @@ function initializeAuthStore() {
|
|
|
541
541
|
window.addEventListener('online', recheck);
|
|
542
542
|
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') recheck(); });
|
|
543
543
|
|
|
544
|
+
// Plugins hand session-bound work to waitUntil(promise); bounded so logout never hangs
|
|
545
|
+
async function beforeLogout() {
|
|
546
|
+
const pending = [];
|
|
547
|
+
try {
|
|
548
|
+
window.dispatchEvent(new CustomEvent('manifest:auth:before-logout', { detail: { waitUntil: p => pending.push(Promise.resolve(p)) } }));
|
|
549
|
+
} catch (e) { }
|
|
550
|
+
if (!pending.length) return;
|
|
551
|
+
await Promise.race([Promise.allSettled(pending), new Promise(r => setTimeout(r, 3000))]);
|
|
552
|
+
}
|
|
553
|
+
|
|
544
554
|
function markVerified(store) {
|
|
545
555
|
store._sessionUnverified = false;
|
|
546
556
|
store._recheckAttempt = 0;
|
|
@@ -652,6 +662,8 @@ function initializeAuthStore() {
|
|
|
652
662
|
}
|
|
653
663
|
|
|
654
664
|
const authStore = {
|
|
665
|
+
// Awaited before any deleteSession: session-bound cleanup (presence) still authenticates
|
|
666
|
+
_beforeSessionEnd: beforeLogout,
|
|
655
667
|
user: null,
|
|
656
668
|
session: null,
|
|
657
669
|
isAuthenticated: false,
|
|
@@ -1022,6 +1034,7 @@ function initializeAuthStore() {
|
|
|
1022
1034
|
// If guest is disabled but we have anonymous session, clear it
|
|
1023
1035
|
if (this.isAnonymous && !this._guestAuto && !this._guestManual) {
|
|
1024
1036
|
try {
|
|
1037
|
+
await beforeLogout();
|
|
1025
1038
|
await appwrite.account.deleteSession(this.session.$id);
|
|
1026
1039
|
this.isAuthenticated = false;
|
|
1027
1040
|
this.isAnonymous = false;
|
|
@@ -1285,6 +1298,9 @@ function initializeAuthStore() {
|
|
|
1285
1298
|
this.inProgress = true;
|
|
1286
1299
|
|
|
1287
1300
|
try {
|
|
1301
|
+
// Session-bound cleanup (presence delete) runs while the session is valid
|
|
1302
|
+
await beforeLogout();
|
|
1303
|
+
|
|
1288
1304
|
// Delete current session (works for guest, magic link, and OAuth sessions)
|
|
1289
1305
|
if (this.session) {
|
|
1290
1306
|
await this._appwrite.account.deleteSession(this.session.$id);
|
|
@@ -1368,6 +1384,7 @@ function initializeAuthStore() {
|
|
|
1368
1384
|
|
|
1369
1385
|
try {
|
|
1370
1386
|
if (this.session) {
|
|
1387
|
+
await beforeLogout();
|
|
1371
1388
|
await this._appwrite.account.deleteSession(this.session.$id);
|
|
1372
1389
|
}
|
|
1373
1390
|
|
|
@@ -6410,6 +6427,7 @@ function initializeMagicLinks() {
|
|
|
6410
6427
|
// and force a brand-new user.
|
|
6411
6428
|
if (this.session && this.isAnonymous && !upgradingGuest) {
|
|
6412
6429
|
try {
|
|
6430
|
+
await this._beforeSessionEnd?.();
|
|
6413
6431
|
await this._appwrite.account.deleteSession(this.session.$id);
|
|
6414
6432
|
} catch (deleteError) {
|
|
6415
6433
|
// Could not delete anonymous session
|
|
@@ -6846,6 +6864,7 @@ function initializeEmailOTP() {
|
|
|
6846
6864
|
// checks the code, so the guest session must go first.
|
|
6847
6865
|
if (this.session && this.isAnonymous) {
|
|
6848
6866
|
try {
|
|
6867
|
+
await this._beforeSessionEnd?.();
|
|
6849
6868
|
await this._appwrite.account.deleteSession(this.session.$id);
|
|
6850
6869
|
guestEnded = true;
|
|
6851
6870
|
} catch (deleteError) {
|
|
@@ -7218,6 +7237,7 @@ function initializeOAuth() {
|
|
|
7218
7237
|
// session stays so Appwrite links the OAuth identity to it (preserving teams)
|
|
7219
7238
|
if (this.isAnonymous && this.session && !appwriteConfig?.guestUpgrade) {
|
|
7220
7239
|
try {
|
|
7240
|
+
await this._beforeSessionEnd?.();
|
|
7221
7241
|
await this._appwrite.account.deleteSession(this.session.$id);
|
|
7222
7242
|
this.session = null;
|
|
7223
7243
|
this.user = null;
|
|
@@ -7369,6 +7389,7 @@ function handleOAuthCallbacks() {
|
|
|
7369
7389
|
// account and the "prohibited" branch below reuses the upgraded session.
|
|
7370
7390
|
if (store.session && store.isAnonymous && !upgradingGuest) {
|
|
7371
7391
|
try {
|
|
7392
|
+
await store._beforeSessionEnd?.();
|
|
7372
7393
|
await store._appwrite.account.deleteSession(store.session.$id);
|
|
7373
7394
|
} catch (deleteError) {
|
|
7374
7395
|
// Could not delete anonymous session
|
|
@@ -289,20 +289,51 @@ if (!window.ManifestRealtimeHub) {
|
|
|
289
289
|
|
|
290
290
|
/* State */
|
|
291
291
|
|
|
292
|
+
// Appwrite's default presence TTL when upsert omits expiresAt: 15 minutes
|
|
293
|
+
const SERVER_TTL_MS = 15 * 60 * 1000;
|
|
294
|
+
// Keep-alive ceiling leaves room for background-timer throttling (≤1 min)
|
|
295
|
+
const KEEPALIVE_MAX_MS = SERVER_TTL_MS - 5 * 60 * 1000;
|
|
296
|
+
const KEEPALIVE_MIN_MS = 1000;
|
|
297
|
+
const ACK_MS = 2000;
|
|
298
|
+
const WATCH_GRACE_MS = 90 * 1000;
|
|
299
|
+
|
|
292
300
|
const ctx = {
|
|
293
301
|
client: null,
|
|
294
302
|
presences: null,
|
|
295
303
|
sub: null,
|
|
296
|
-
heartbeat: null,
|
|
297
304
|
started: false,
|
|
298
|
-
status: 'online',
|
|
305
|
+
status: 'online', // base status (set() / start option)
|
|
299
306
|
metadata: null,
|
|
307
|
+
team: undefined, // write scope of the most recent change, browser-wide
|
|
308
|
+
cleared: false,
|
|
309
|
+
stamp: 0, // shared-state version, last writer wins
|
|
300
310
|
scope: 'auto', // 'auto'/'team' = current team, 'global', or an explicit team id
|
|
301
311
|
teamsEnabled: false, // manifest.appwrite.auth.teams (read in ensureServices)
|
|
302
|
-
auto: true, //
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
312
|
+
auto: true, // away when none of the user's tabs is visible
|
|
313
|
+
keepAliveMs: 5 * 60 * 1000,
|
|
314
|
+
settleMs: 1000, // activity-drop debounce (absorbs tab switches)
|
|
315
|
+
flushMs: 100, // incoming-event coalescing window
|
|
316
|
+
tabId: Math.random().toString(36).slice(2) + Date.now().toString(36),
|
|
317
|
+
role: null, // 'leader' | 'follower' | 'solo' | null
|
|
318
|
+
bc: null,
|
|
319
|
+
release: null, // releases the held Web Lock
|
|
320
|
+
abort: null, // cancels a queued lock request
|
|
321
|
+
tabs: new Map(), // leader: tabId → activity rank
|
|
322
|
+
rank: 0, // this tab: 2 focused, 1 visible, 0 hidden
|
|
323
|
+
sent: null, // last published { status, metadata, team }
|
|
324
|
+
sentAt: 0,
|
|
325
|
+
mine: null, // own record (published or optimistic)
|
|
326
|
+
roster: {}, // others, unfiltered: userId → { rec, perms }
|
|
327
|
+
timers: { keep: null, publish: null, flush: null, wait: null, expire: null, watch: null, ack: null },
|
|
328
|
+
leaderKeep: 0, // leader's keep-alive, for the follower watchdog
|
|
329
|
+
touched: null, // ids seen live while a list is in flight
|
|
330
|
+
userId: null, // user tracking started for
|
|
331
|
+
offset: 0, // server clock − client clock (from upsert responses)
|
|
332
|
+
promotion: null, // pending promotion wait { timer, resolve }
|
|
333
|
+
chain: Promise.resolve(),
|
|
334
|
+
onState: null,
|
|
335
|
+
suspended: false,
|
|
336
|
+
listening: false
|
|
306
337
|
};
|
|
307
338
|
|
|
308
339
|
/* Config */
|
|
@@ -417,35 +448,92 @@ if (!window.ManifestRealtimeHub) {
|
|
|
417
448
|
};
|
|
418
449
|
}
|
|
419
450
|
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
451
|
+
function permsOf(raw) {
|
|
452
|
+
return Array.isArray(raw?.$permissions) ? raw.$permissions.slice() : [];
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// name/color in metadata for rosters (name null when unknown — display label is the author's)
|
|
456
|
+
function ownMeta(metadata) {
|
|
457
|
+
const user = authUser();
|
|
458
|
+
return Object.assign({ name: user?.name || null, color: userColor(user?.$id) }, metadata || {});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// One store assignment per call, skipped when nothing changed
|
|
462
|
+
let lastJson = '';
|
|
463
|
+
let lastRecords = null;
|
|
464
|
+
function render() {
|
|
465
|
+
const s = store(); if (!s) return;
|
|
466
|
+
const now = Date.now() + ctx.offset;
|
|
467
|
+
let soonest = Infinity;
|
|
468
|
+
const next = {};
|
|
469
|
+
for (const id in ctx.roster) {
|
|
470
|
+
const e = ctx.roster[id];
|
|
471
|
+
if (!e) continue;
|
|
472
|
+
// Expired peers drop locally, without waiting for Appwrite's delete event
|
|
473
|
+
const exp = e.rec?.expiresAt ? Date.parse(e.rec.expiresAt) : NaN;
|
|
474
|
+
if (exp <= now) continue;
|
|
475
|
+
if (exp < soonest) soonest = exp;
|
|
476
|
+
if (inScope({ $permissions: e.perms }, id)) next[id] = e.rec;
|
|
477
|
+
}
|
|
478
|
+
clearTimeout(ctx.timers.expire);
|
|
479
|
+
ctx.timers.expire = null;
|
|
480
|
+
if (ctx.started && soonest !== Infinity) ctx.timers.expire = setTimeout(render, Math.min(soonest - now + 50, 2147483647));
|
|
481
|
+
const user = authUser();
|
|
482
|
+
if (user && ctx.mine) {
|
|
483
|
+
next[user.$id] = normalize({ userId: user.$id, status: ctx.mine.status, metadata: ownMeta(ctx.mine.metadata), $updatedAt: ctx.mine.at });
|
|
484
|
+
}
|
|
485
|
+
const json = JSON.stringify(next);
|
|
486
|
+
if (json === lastJson && s.records === lastRecords) return;
|
|
487
|
+
lastJson = json;
|
|
488
|
+
s.records = next;
|
|
489
|
+
lastRecords = s.records;
|
|
424
490
|
}
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
const
|
|
491
|
+
|
|
492
|
+
function setMine(d) {
|
|
493
|
+
ctx.mine = d ? { status: d.status, metadata: d.metadata, at: new Date().toISOString() } : null;
|
|
494
|
+
const s = store(); if (s) s.me = d ? d.status : null;
|
|
495
|
+
render();
|
|
429
496
|
}
|
|
430
497
|
|
|
498
|
+
// Coalesce incoming events: at most one store flush (and one roster
|
|
499
|
+
// broadcast) per flushMs window
|
|
500
|
+
function scheduleFlush() {
|
|
501
|
+
if (ctx.timers.flush) return;
|
|
502
|
+
ctx.timers.flush = setTimeout(flushNow, ctx.flushMs);
|
|
503
|
+
}
|
|
504
|
+
function flushNow() {
|
|
505
|
+
clearTimeout(ctx.timers.flush);
|
|
506
|
+
ctx.timers.flush = null;
|
|
507
|
+
render();
|
|
508
|
+
if (ctx.role === 'leader') post({ t: 'roster', roster: ctx.roster });
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// Runs after subscribe(): live events seen while listing are newer than the list
|
|
431
512
|
async function hydrate() {
|
|
432
|
-
const
|
|
513
|
+
const touched = ctx.touched = new Set();
|
|
433
514
|
try {
|
|
434
515
|
const res = await ctx.presences.list();
|
|
435
516
|
const rows = res?.presences || res?.rows || res?.documents || [];
|
|
436
|
-
const
|
|
437
|
-
|
|
438
|
-
if (
|
|
517
|
+
const meId = authUser()?.$id;
|
|
518
|
+
const next = {};
|
|
519
|
+
rows.forEach(r => { const n = normalize(r); if (n && n.userId !== meId && !touched.has(n.userId)) next[n.userId] = { rec: n, perms: permsOf(r) }; });
|
|
520
|
+
touched.forEach(id => { if (ctx.roster[id]) next[id] = ctx.roster[id]; });
|
|
521
|
+
ctx.roster = next;
|
|
522
|
+
flushNow();
|
|
439
523
|
} catch (e) {
|
|
440
|
-
if (s) s.error = e?.message || String(e);
|
|
524
|
+
const s = store(); if (s) s.error = e?.message || String(e);
|
|
525
|
+
} finally {
|
|
526
|
+
if (ctx.touched === touched) ctx.touched = null;
|
|
441
527
|
}
|
|
442
528
|
}
|
|
443
529
|
|
|
530
|
+
// Writers only: followers get the roster from the leader
|
|
444
531
|
function subscribe() {
|
|
445
532
|
const A = window.Appwrite;
|
|
446
533
|
const hub = window.ManifestRealtimeHub;
|
|
447
534
|
const channel = (A.Channel && typeof A.Channel.presences === 'function') ? A.Channel.presences() : 'presences';
|
|
448
|
-
hub.
|
|
535
|
+
ctx.sub = () => hub.unsubscribe('presence:roster');
|
|
536
|
+
return hub.subscribe({
|
|
449
537
|
name: 'presence:roster',
|
|
450
538
|
channel,
|
|
451
539
|
getRealtime: async () => hub.acquire(ctx.client),
|
|
@@ -456,53 +544,92 @@ if (!window.ManifestRealtimeHub) {
|
|
|
456
544
|
// Ignore echoes of our own presence (tracked locally; delayed echoes would clobber newer status)
|
|
457
545
|
const meId = authUser()?.$id;
|
|
458
546
|
if (meId && rec.userId === meId) return;
|
|
459
|
-
|
|
460
|
-
if (
|
|
461
|
-
|
|
462
|
-
|
|
547
|
+
if (ctx.touched) ctx.touched.add(rec.userId);
|
|
548
|
+
if (action === 'delete') delete ctx.roster[rec.userId];
|
|
549
|
+
else ctx.roster[rec.userId] = { rec, perms: permsOf(payload) };
|
|
550
|
+
scheduleFlush();
|
|
463
551
|
}
|
|
464
552
|
}).catch(e => {
|
|
465
553
|
const s = store(); if (s) s.error = e?.message || String(e);
|
|
466
554
|
});
|
|
467
|
-
ctx.sub = () => hub.unsubscribe('presence:roster');
|
|
468
555
|
}
|
|
469
556
|
|
|
470
|
-
/*
|
|
557
|
+
/* Activity */
|
|
471
558
|
|
|
472
|
-
|
|
559
|
+
function computeRank() {
|
|
560
|
+
if (typeof document === 'undefined') return 2;
|
|
561
|
+
if (document.visibilityState === 'hidden') return 0;
|
|
562
|
+
try { if (typeof document.hasFocus === 'function' && document.hasFocus()) return 2; } catch (e) { }
|
|
563
|
+
return 1;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function maxRank() {
|
|
567
|
+
if (ctx.role !== 'leader') return ctx.rank;
|
|
568
|
+
let r = 0;
|
|
569
|
+
ctx.tabs.forEach(v => { if (v > r) r = v; });
|
|
570
|
+
return r;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function onActivity() {
|
|
574
|
+
const r = computeRank();
|
|
575
|
+
if (r === ctx.rank) return;
|
|
576
|
+
const up = r > ctx.rank;
|
|
577
|
+
ctx.rank = r;
|
|
578
|
+
if (isWriter()) {
|
|
579
|
+
ctx.tabs.set(ctx.tabId, r);
|
|
580
|
+
schedulePublish(up ? 50 : ctx.settleMs);
|
|
581
|
+
} else if (ctx.role === 'follower') {
|
|
582
|
+
post({ t: 'hello', from: ctx.tabId, rank: r });
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/* Publishing */
|
|
587
|
+
|
|
588
|
+
function isWriter() {
|
|
589
|
+
return ctx.role === 'leader' || ctx.role === 'solo';
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// What this browser should publish: base status, or away when no tab is visible
|
|
593
|
+
function desired() {
|
|
594
|
+
if (ctx.cleared) return null;
|
|
595
|
+
const away = ctx.auto && ctx.started && !!ctx.role && maxRank() === 0;
|
|
596
|
+
return { status: away ? 'away' : ctx.status, metadata: ctx.metadata, team: ctx.team === undefined ? scopeTeamId() : ctx.team };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function same(a, b) {
|
|
600
|
+
return !!(a && b) && a.status === b.status && a.team === b.team && JSON.stringify(a.metadata) === JSON.stringify(b.metadata);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// Writes run one at a time, in order
|
|
604
|
+
function enqueue(fn) {
|
|
605
|
+
const p = ctx.chain.then(fn, fn);
|
|
606
|
+
ctx.chain = p.catch(() => { });
|
|
607
|
+
return p;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
async function write(d) {
|
|
473
611
|
const A = window.Appwrite;
|
|
474
612
|
const user = authUser();
|
|
475
613
|
const s = store();
|
|
476
|
-
if (!user) { if (s) s.error = 'sign in required'; return false; }
|
|
477
|
-
if (!(await ensureServices())) { if (s) s.error = 'Appwrite Presences unavailable'; return false; }
|
|
478
|
-
ctx.status = status != null ? status : ctx.status;
|
|
479
|
-
ctx.metadata = metadata !== undefined ? metadata : ctx.metadata;
|
|
480
|
-
|
|
481
614
|
// Read-scope + owner write (owner update/delete required, else updates 401).
|
|
482
615
|
// Scoped (teams enabled, scope not global): team grant when resolved,
|
|
483
616
|
// self-only until then — however long teams take — never the users()
|
|
484
617
|
// broadcast. users() is only for global scope or teams-disabled projects.
|
|
485
|
-
// The team-switch effect rescopes reactively when a team resolves/changes.
|
|
486
|
-
const teamId = scopeTeamId();
|
|
487
618
|
const scoped = ctx.teamsEnabled && ctx.scope !== 'global' && ctx.scope !== false && ctx.scope != null;
|
|
488
|
-
const readRole =
|
|
619
|
+
const readRole = d.team ? A.Role.team(d.team) : (scoped ? A.Role.user(user.$id) : A.Role.users());
|
|
489
620
|
const permissions = [
|
|
490
621
|
A.Permission.read(readRole),
|
|
491
622
|
A.Permission.update(A.Role.user(user.$id)),
|
|
492
623
|
A.Permission.delete(A.Role.user(user.$id))
|
|
493
624
|
];
|
|
494
|
-
|
|
495
|
-
// name/color in metadata for rosters (name null when unknown — display label is the author's)
|
|
496
|
-
const meta = Object.assign(
|
|
497
|
-
{ name: user.name || null, color: userColor(user.$id) },
|
|
498
|
-
ctx.metadata || {}
|
|
499
|
-
);
|
|
500
|
-
|
|
501
|
-
// Optimistic local update
|
|
502
|
-
putRecord(normalize({ userId: user.$id, status: ctx.status, metadata: meta, $updatedAt: new Date().toISOString() }));
|
|
503
|
-
if (s) s.me = ctx.status;
|
|
504
625
|
try {
|
|
505
|
-
await ctx.presences.upsert({ presenceId: user.$id, status:
|
|
626
|
+
const res = await ctx.presences.upsert({ presenceId: user.$id, status: d.status, metadata: ownMeta(d.metadata), permissions });
|
|
627
|
+
const server = Date.parse(res?.$updatedAt);
|
|
628
|
+
if (Number.isFinite(server)) {
|
|
629
|
+
const prev = ctx.offset;
|
|
630
|
+
ctx.offset = server - Date.now();
|
|
631
|
+
if (Math.abs(ctx.offset - prev) > 1000) render();
|
|
632
|
+
}
|
|
506
633
|
if (s) s.error = null;
|
|
507
634
|
return true;
|
|
508
635
|
} catch (e) {
|
|
@@ -511,21 +638,415 @@ if (!window.ManifestRealtimeHub) {
|
|
|
511
638
|
}
|
|
512
639
|
}
|
|
513
640
|
|
|
514
|
-
//
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
641
|
+
// Send on change; force re-sends unchanged state (keep-alive)
|
|
642
|
+
function publish(force) {
|
|
643
|
+
return enqueue(async () => {
|
|
644
|
+
const user = authUser();
|
|
645
|
+
if (!user || !ctx.presences) return false;
|
|
646
|
+
// Lost the lock while queued: the new leader owns the record
|
|
647
|
+
if (ctx.started && ctx.role && !isWriter()) return false;
|
|
648
|
+
const d = desired();
|
|
649
|
+
if (!d) {
|
|
650
|
+
clearTimeout(ctx.timers.keep);
|
|
651
|
+
if (ctx.sent || force) {
|
|
652
|
+
ctx.sent = null;
|
|
653
|
+
try { await ctx.presences.delete({ presenceId: user.$id }); } catch (e) { }
|
|
654
|
+
}
|
|
655
|
+
setMine(null);
|
|
656
|
+
announceState();
|
|
657
|
+
return true;
|
|
658
|
+
}
|
|
659
|
+
if (!force && same(d, ctx.sent)) return true;
|
|
660
|
+
// Scope change: old-scope rosters never receive a perms rewrite
|
|
661
|
+
// (delivery follows the OLD read grant), so delete first — the
|
|
662
|
+
// delete event still carries it — then re-upsert under the new scope
|
|
663
|
+
if (ctx.sent && ctx.sent.team !== d.team) {
|
|
664
|
+
try { await ctx.presences.delete({ presenceId: user.$id }); } catch (e) { }
|
|
665
|
+
}
|
|
666
|
+
setMine(d);
|
|
667
|
+
if (ctx.started && ctx.role && !isWriter()) return false;
|
|
668
|
+
const ok = await write(d);
|
|
669
|
+
// Cleared (here or in another tab) while the write was in flight: undo it
|
|
670
|
+
if (ctx.cleared) {
|
|
671
|
+
ctx.sent = null;
|
|
672
|
+
try { await ctx.presences.delete({ presenceId: user.$id }); } catch (e) { }
|
|
673
|
+
setMine(null);
|
|
674
|
+
announceState();
|
|
675
|
+
return ok;
|
|
676
|
+
}
|
|
677
|
+
ctx.sent = ok ? d : null;
|
|
678
|
+
ctx.sentAt = Date.now();
|
|
679
|
+
armKeepAlive();
|
|
680
|
+
announceState();
|
|
681
|
+
return ok;
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function schedulePublish(delay) {
|
|
686
|
+
if (!isWriter()) return;
|
|
687
|
+
clearTimeout(ctx.timers.publish);
|
|
688
|
+
ctx.timers.publish = setTimeout(() => { ctx.timers.publish = null; publish(false); }, delay);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
function armKeepAlive(ms) {
|
|
692
|
+
clearTimeout(ctx.timers.keep);
|
|
693
|
+
ctx.timers.keep = null;
|
|
694
|
+
if (!isWriter() || ctx.cleared) return;
|
|
695
|
+
ctx.timers.keep = setTimeout(keepAlive, ms != null ? Math.max(0, ms) : ctx.keepAliveMs);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
async function keepAlive() {
|
|
699
|
+
ctx.timers.keep = null;
|
|
700
|
+
if (!isWriter()) return;
|
|
701
|
+
// Roll call first: prunes tabs that died without a goodbye
|
|
702
|
+
if (ctx.role === 'leader' && ctx.bc) {
|
|
703
|
+
ctx.tabs = new Map([[ctx.tabId, ctx.rank]]);
|
|
704
|
+
post({ t: 'roll' });
|
|
705
|
+
await new Promise(r => { ctx.timers.wait = setTimeout(r, 300); });
|
|
706
|
+
if (ctx.role !== 'leader') return;
|
|
707
|
+
}
|
|
708
|
+
publish(true);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/* Tabs */
|
|
712
|
+
|
|
713
|
+
// Shared state change from this tab, mirrored to the others
|
|
714
|
+
function differs(patch) {
|
|
715
|
+
return Object.keys(patch).some(k => k === 'metadata'
|
|
716
|
+
? JSON.stringify(ctx.metadata) !== JSON.stringify(patch.metadata)
|
|
717
|
+
: ctx[k] !== patch[k]);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function change(patch, extra) {
|
|
721
|
+
Object.assign(ctx, patch);
|
|
722
|
+
ctx.stamp = Math.max(Date.now(), ctx.stamp + 1);
|
|
723
|
+
post(Object.assign({ t: 'set', from: ctx.tabId, stamp: ctx.stamp, status: ctx.status, metadata: ctx.metadata, team: ctx.team, cleared: ctx.cleared }, extra));
|
|
724
|
+
if (ctx.role === 'follower' && !ctx.cleared) {
|
|
725
|
+
// Unacknowledged by a leader in time: it's stuck, take over
|
|
726
|
+
clearTimeout(ctx.timers.ack);
|
|
727
|
+
ctx.timers.ack = setTimeout(takeOver, ACK_MS);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function adopt(m) {
|
|
732
|
+
if (!m || typeof m.stamp !== 'number' || m.stamp < ctx.stamp) return false;
|
|
733
|
+
ctx.stamp = m.stamp;
|
|
734
|
+
ctx.status = m.status;
|
|
735
|
+
ctx.metadata = m.metadata;
|
|
736
|
+
ctx.team = m.team;
|
|
737
|
+
ctx.cleared = !!m.cleared;
|
|
738
|
+
if (m.deleted) ctx.sent = null;
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
function announceState() {
|
|
743
|
+
if (ctx.role !== 'leader') return;
|
|
744
|
+
post({
|
|
745
|
+
t: 'state', from: ctx.tabId, stamp: ctx.stamp, status: ctx.status, metadata: ctx.metadata, team: ctx.team,
|
|
746
|
+
cleared: ctx.cleared, sent: ctx.sent, sentAt: ctx.sentAt, keepAliveMs: ctx.keepAliveMs, offset: ctx.offset, error: store()?.error || null
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
function post(m) {
|
|
751
|
+
if (!ctx.bc) return;
|
|
752
|
+
try { ctx.bc.postMessage(m); } catch (e) { }
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function onMessage(m) {
|
|
756
|
+
if (!m || m.from === ctx.tabId) return;
|
|
757
|
+
const leader = ctx.role === 'leader';
|
|
758
|
+
switch (m.t) {
|
|
759
|
+
case 'hello':
|
|
760
|
+
if (!leader) return;
|
|
761
|
+
{
|
|
762
|
+
const prev = ctx.tabs.get(m.from);
|
|
763
|
+
ctx.tabs.set(m.from, m.rank);
|
|
764
|
+
if (m.join) { post({ t: 'roster', roster: ctx.roster }); announceState(); }
|
|
765
|
+
if (prev !== m.rank) schedulePublish(m.rank > (prev ?? -1) ? 50 : ctx.settleMs);
|
|
766
|
+
}
|
|
767
|
+
return;
|
|
768
|
+
case 'bye':
|
|
769
|
+
if (!leader) return;
|
|
770
|
+
if (ctx.tabs.delete(m.from)) schedulePublish(ctx.settleMs);
|
|
771
|
+
return;
|
|
772
|
+
case 'set':
|
|
773
|
+
// Ack every set, changed or not: an unacked follower takes over
|
|
774
|
+
if (leader) post({ t: 'ack', from: ctx.tabId, stamp: m.stamp });
|
|
775
|
+
if (adopt(m) && leader) schedulePublish(0);
|
|
776
|
+
return;
|
|
777
|
+
case 'ack':
|
|
778
|
+
if (ctx.role === 'follower' && m.stamp >= ctx.stamp) { clearTimeout(ctx.timers.ack); ctx.timers.ack = null; armWatch(); }
|
|
779
|
+
return;
|
|
780
|
+
case 'lead':
|
|
781
|
+
case 'roll':
|
|
782
|
+
if (ctx.role === 'follower') { post({ t: 'hello', from: ctx.tabId, rank: ctx.rank }); armWatch(); }
|
|
783
|
+
return;
|
|
784
|
+
case 'roster':
|
|
785
|
+
if (ctx.role !== 'follower') return;
|
|
786
|
+
ctx.roster = m.roster || {};
|
|
787
|
+
render();
|
|
788
|
+
armWatch();
|
|
789
|
+
return;
|
|
790
|
+
case 'state':
|
|
791
|
+
if (ctx.role !== 'follower') return;
|
|
792
|
+
adopt(m);
|
|
793
|
+
ctx.sent = m.sent || null;
|
|
794
|
+
ctx.sentAt = m.sentAt || 0;
|
|
795
|
+
ctx.leaderKeep = m.keepAliveMs || 0;
|
|
796
|
+
if (typeof m.offset === 'number' && m.offset !== ctx.offset) { ctx.offset = m.offset; render(); }
|
|
797
|
+
if (m.stamp >= ctx.stamp) { clearTimeout(ctx.timers.ack); ctx.timers.ack = null; }
|
|
798
|
+
armWatch();
|
|
799
|
+
setMine(m.sent || null);
|
|
800
|
+
{ const s = store(); if (s) s.error = m.error || null; }
|
|
801
|
+
if (ctx.onState) { const fn = ctx.onState; ctx.onState = null; fn(); }
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/* Election */
|
|
807
|
+
|
|
808
|
+
// One writer per browser per user: Web Locks elect, BroadcastChannel fans out
|
|
809
|
+
function groupName() {
|
|
810
|
+
const cfg = ctx.client?.config || {};
|
|
811
|
+
return `manifest-presence:${cfg.endpoint || ''}:${cfg.project || ''}:${authUser()?.$id || ''}`;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
function lockApi() {
|
|
815
|
+
const locks = window.navigator?.locks;
|
|
816
|
+
return locks && typeof locks.request === 'function' ? locks : null;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// A held lock's request rejects when another tab steals it
|
|
820
|
+
function hold(request, onError) {
|
|
821
|
+
request.catch(() => {
|
|
822
|
+
if (onError) onError();
|
|
823
|
+
if (ctx.role === 'leader') demote();
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
async function join() {
|
|
828
|
+
ctx.rank = computeRank();
|
|
829
|
+
const locks = lockApi();
|
|
830
|
+
const BC = window.BroadcastChannel;
|
|
831
|
+
if (!locks || typeof BC !== 'function') return becomeSolo();
|
|
832
|
+
const name = groupName();
|
|
833
|
+
try {
|
|
834
|
+
ctx.bc = new BC(name);
|
|
835
|
+
ctx.bc.onmessage = e => onMessage(e.data);
|
|
836
|
+
} catch (e) {
|
|
837
|
+
ctx.bc = null;
|
|
838
|
+
return becomeSolo();
|
|
839
|
+
}
|
|
840
|
+
// Free lock → lead now; held → follow and queue for it
|
|
841
|
+
const got = await new Promise(resolve => {
|
|
842
|
+
hold(locks.request(name, { ifAvailable: true }, lock => {
|
|
843
|
+
if (!lock) { resolve(false); return null; }
|
|
844
|
+
resolve(true);
|
|
845
|
+
return new Promise(r => { ctx.release = r; });
|
|
846
|
+
}), () => resolve(false));
|
|
847
|
+
});
|
|
848
|
+
if (!ctx.started) { if (ctx.release) { ctx.release(); ctx.release = null; } return; }
|
|
849
|
+
if (got) return becomeLeader(false);
|
|
850
|
+
ctx.role = 'follower';
|
|
851
|
+
queue();
|
|
852
|
+
post({ t: 'hello', from: ctx.tabId, rank: ctx.rank, join: true });
|
|
853
|
+
armWatch();
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
function queue() {
|
|
857
|
+
const locks = lockApi();
|
|
858
|
+
if (!locks) return;
|
|
859
|
+
const AC = window.AbortController;
|
|
860
|
+
const abort = typeof AC === 'function' ? new AC() : null;
|
|
861
|
+
ctx.abort = abort;
|
|
862
|
+
hold(locks.request(groupName(), abort ? { signal: abort.signal } : {}, () => {
|
|
863
|
+
if (!ctx.started || ctx.abort !== abort) return null;
|
|
864
|
+
ctx.abort = null;
|
|
865
|
+
return new Promise(r => { ctx.release = r; becomeLeader(true); });
|
|
866
|
+
}));
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// Follower watchdog: no word from the leader within keep-alive + grace
|
|
870
|
+
// means it's suspended (Safari has no freeze event) — take the lock
|
|
871
|
+
function armWatch() {
|
|
872
|
+
clearTimeout(ctx.timers.watch);
|
|
873
|
+
ctx.timers.watch = null;
|
|
874
|
+
if (ctx.role !== 'follower') return;
|
|
875
|
+
const keep = Math.max(ctx.keepAliveMs, ctx.leaderKeep || 0);
|
|
876
|
+
// Jitter so two followers rarely steal at once
|
|
877
|
+
ctx.timers.watch = setTimeout(takeOver, keep + Math.min(WATCH_GRACE_MS, keep / 2) + Math.random() * Math.min(1000, keep / 4));
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
function takeOver() {
|
|
881
|
+
if (ctx.role !== 'follower' || !ctx.started) return;
|
|
882
|
+
const locks = lockApi();
|
|
883
|
+
if (!locks) return;
|
|
884
|
+
if (ctx.abort) { try { ctx.abort.abort(); } catch (e) { } ctx.abort = null; }
|
|
885
|
+
clearTimeout(ctx.timers.watch);
|
|
886
|
+
clearTimeout(ctx.timers.ack);
|
|
887
|
+
hold(locks.request(groupName(), { steal: true }, () => new Promise(r => { ctx.release = r; becomeLeader(true); })));
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// Lost the lock to a steal: back to follower, queue again
|
|
891
|
+
function demote() {
|
|
892
|
+
if (ctx.role !== 'leader') return;
|
|
893
|
+
cancelPromotion();
|
|
894
|
+
if (ctx.release) { try { ctx.release(); } catch (e) { } }
|
|
895
|
+
['keep', 'publish', 'wait'].forEach(k => { clearTimeout(ctx.timers[k]); ctx.timers[k] = null; });
|
|
896
|
+
ctx.release = null;
|
|
897
|
+
if (typeof ctx.sub === 'function') { try { ctx.sub(); } catch (e) { } }
|
|
898
|
+
ctx.sub = null;
|
|
899
|
+
ctx.role = 'follower';
|
|
900
|
+
if (!ctx.started) return;
|
|
901
|
+
queue();
|
|
902
|
+
post({ t: 'hello', from: ctx.tabId, rank: ctx.rank, join: true });
|
|
903
|
+
armWatch();
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
async function becomeLeader(promoted) {
|
|
907
|
+
ctx.role = 'leader';
|
|
908
|
+
ctx.tabs = new Map([[ctx.tabId, ctx.rank]]);
|
|
909
|
+
['watch', 'ack'].forEach(k => { clearTimeout(ctx.timers[k]); ctx.timers[k] = null; });
|
|
910
|
+
post({ t: 'lead', from: ctx.tabId });
|
|
911
|
+
await subscribe();
|
|
912
|
+
if (ctx.role !== 'leader') return;
|
|
913
|
+
await hydrate();
|
|
914
|
+
if (ctx.role !== 'leader') return;
|
|
915
|
+
// The row may be gone (a predecessor that thought it was alone deleted
|
|
916
|
+
// it): always rewrite, after other tabs report their activity
|
|
917
|
+
if (promoted) {
|
|
918
|
+
await new Promise(resolve => {
|
|
919
|
+
ctx.promotion = { resolve, timer: setTimeout(resolve, 300) };
|
|
920
|
+
});
|
|
921
|
+
ctx.promotion = null;
|
|
922
|
+
}
|
|
923
|
+
if (ctx.role !== 'leader') return;
|
|
924
|
+
await publish(true);
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
async function becomeSolo() {
|
|
928
|
+
ctx.role = 'solo';
|
|
929
|
+
ctx.tabs = new Map([[ctx.tabId, ctx.rank]]);
|
|
930
|
+
await subscribe();
|
|
931
|
+
if (ctx.role !== 'solo') return;
|
|
932
|
+
await hydrate();
|
|
933
|
+
if (ctx.role !== 'solo') return;
|
|
934
|
+
await publish(true);
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function cancelPromotion() {
|
|
938
|
+
if (!ctx.promotion) return;
|
|
939
|
+
clearTimeout(ctx.promotion.timer);
|
|
940
|
+
const { resolve } = ctx.promotion;
|
|
941
|
+
ctx.promotion = null;
|
|
942
|
+
resolve();
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
function resign() {
|
|
946
|
+
ctx.role = null;
|
|
947
|
+
cancelPromotion();
|
|
948
|
+
Object.keys(ctx.timers).forEach(k => { clearTimeout(ctx.timers[k]); ctx.timers[k] = null; });
|
|
949
|
+
if (ctx.abort) { try { ctx.abort.abort(); } catch (e) { } ctx.abort = null; }
|
|
950
|
+
if (ctx.release) { ctx.release(); ctx.release = null; }
|
|
951
|
+
if (typeof ctx.sub === 'function') { try { ctx.sub(); } catch (e) { } }
|
|
952
|
+
ctx.sub = null;
|
|
953
|
+
if (ctx.bc) {
|
|
954
|
+
post({ t: 'bye', from: ctx.tabId });
|
|
955
|
+
try { ctx.bc.close(); } catch (e) { }
|
|
956
|
+
ctx.bc = null;
|
|
957
|
+
}
|
|
958
|
+
if (ctx.onState) { const fn = ctx.onState; ctx.onState = null; fn(); }
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
function waitForLeader(ms) {
|
|
962
|
+
return new Promise(resolve => {
|
|
963
|
+
const t = setTimeout(() => { ctx.onState = null; resolve(); }, ms);
|
|
964
|
+
ctx.onState = () => { clearTimeout(t); resolve(); };
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/* Lifecycle */
|
|
969
|
+
|
|
970
|
+
// Last tab out deletes the record; others hand over (bfcache + freeze rejoin on return)
|
|
971
|
+
function onPageHide() {
|
|
972
|
+
if (!ctx.started || !ctx.role) return;
|
|
973
|
+
const alone = ctx.role !== 'follower' && ![...ctx.tabs.keys()].some(id => id !== ctx.tabId);
|
|
974
|
+
const user = authUser();
|
|
975
|
+
if (alone && user && ctx.presences) {
|
|
976
|
+
ctx.sent = null;
|
|
977
|
+
// Tabs we didn't know about must not inherit a stale "sent"
|
|
978
|
+
announceState();
|
|
979
|
+
try { ctx.presences.delete({ presenceId: user.$id }).catch(() => { }); } catch (e) { }
|
|
980
|
+
}
|
|
981
|
+
resign();
|
|
982
|
+
ctx.suspended = true;
|
|
983
|
+
}
|
|
984
|
+
function onFreeze() {
|
|
985
|
+
if (!ctx.started || !ctx.role) return;
|
|
986
|
+
resign();
|
|
987
|
+
ctx.suspended = true;
|
|
988
|
+
}
|
|
989
|
+
function onReturn(e) {
|
|
990
|
+
if (e && e.type === 'pageshow' && !e.persisted) return;
|
|
991
|
+
if (!ctx.suspended || !ctx.started) return;
|
|
992
|
+
ctx.suspended = false;
|
|
993
|
+
join();
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
const LISTENERS = [
|
|
997
|
+
[() => document, 'visibilitychange', onActivity],
|
|
998
|
+
[() => window, 'focus', onActivity],
|
|
999
|
+
[() => window, 'blur', onActivity],
|
|
1000
|
+
[() => window, 'pagehide', onPageHide],
|
|
1001
|
+
[() => window, 'pageshow', onReturn],
|
|
1002
|
+
[() => document, 'freeze', onFreeze],
|
|
1003
|
+
[() => document, 'resume', onReturn]
|
|
1004
|
+
];
|
|
1005
|
+
function listen(on) {
|
|
1006
|
+
if (ctx.listening === on) return;
|
|
1007
|
+
ctx.listening = on;
|
|
1008
|
+
LISTENERS.forEach(([target, type, fn]) => {
|
|
1009
|
+
const t = target();
|
|
1010
|
+
if (!t) return;
|
|
1011
|
+
if (on) t.addEventListener(type, fn);
|
|
1012
|
+
else t.removeEventListener(type, fn);
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/* Operations */
|
|
1017
|
+
|
|
1018
|
+
async function set(status, metadata) {
|
|
518
1019
|
const user = authUser();
|
|
519
|
-
|
|
520
|
-
|
|
1020
|
+
const s = store();
|
|
1021
|
+
if (!user) { if (s) s.error = 'sign in required'; return false; }
|
|
1022
|
+
if (!(await ensureServices())) { if (s) s.error = 'Appwrite Presences unavailable'; return false; }
|
|
1023
|
+
const patch = { cleared: false, team: scopeTeamId() };
|
|
1024
|
+
if (status != null) patch.status = status;
|
|
1025
|
+
if (metadata !== undefined) patch.metadata = metadata;
|
|
1026
|
+
if (!differs(patch)) return ctx.role === 'follower' ? true : publish(false);
|
|
1027
|
+
change(patch);
|
|
1028
|
+
if (ctx.role === 'follower') {
|
|
1029
|
+
setMine({ status: ctx.status, metadata: ctx.metadata });
|
|
1030
|
+
return true;
|
|
1031
|
+
}
|
|
1032
|
+
return publish(false);
|
|
521
1033
|
}
|
|
522
1034
|
|
|
1035
|
+
// Resolves once the record is deleted, from this tab, while its session is valid
|
|
523
1036
|
async function clear() {
|
|
524
1037
|
const user = authUser();
|
|
525
|
-
if (!user
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
1038
|
+
if (!user) return;
|
|
1039
|
+
if (ctx.role === 'follower') {
|
|
1040
|
+
// Peers adopt cleared + no record, so the leader never rewrites it
|
|
1041
|
+
change({ cleared: true }, { deleted: true });
|
|
1042
|
+
ctx.sent = null;
|
|
1043
|
+
setMine(null);
|
|
1044
|
+
if (await ensureServices()) { try { await ctx.presences.delete({ presenceId: user.$id }); } catch (e) { } }
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
change({ cleared: true });
|
|
1048
|
+
if (await ensureServices()) await publish(true);
|
|
1049
|
+
setMine(null);
|
|
529
1050
|
}
|
|
530
1051
|
|
|
531
1052
|
function of(userId) {
|
|
@@ -541,8 +1062,9 @@ if (!window.ManifestRealtimeHub) {
|
|
|
541
1062
|
async function start(options) {
|
|
542
1063
|
const opts = options || {};
|
|
543
1064
|
if (typeof opts.auto === 'boolean') ctx.auto = opts.auto;
|
|
544
|
-
|
|
545
|
-
|
|
1065
|
+
// heartbeatMs: pre-0.5.301 name, now an alias of keepAliveMs
|
|
1066
|
+
const keep = typeof opts.keepAliveMs === 'number' ? opts.keepAliveMs : opts.heartbeatMs;
|
|
1067
|
+
if (typeof keep === 'number' && keep > 0) ctx.keepAliveMs = Math.min(KEEPALIVE_MAX_MS, Math.max(KEEPALIVE_MIN_MS, keep));
|
|
546
1068
|
|
|
547
1069
|
// Scope: start() option > manifest appwrite.presences.scope > 'auto'
|
|
548
1070
|
const cfg = await getPresencesConfig();
|
|
@@ -555,20 +1077,19 @@ if (!window.ManifestRealtimeHub) {
|
|
|
555
1077
|
if (ctx.started) return true;
|
|
556
1078
|
|
|
557
1079
|
ctx.started = true;
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
window.addEventListener('focus', ctx.onFocus);
|
|
1080
|
+
ctx.userId = authUser().$id;
|
|
1081
|
+
ctx.cleared = false;
|
|
1082
|
+
if (typeof opts.status === 'string') ctx.status = opts.status;
|
|
1083
|
+
ctx.team = scopeTeamId();
|
|
1084
|
+
listen(true);
|
|
1085
|
+
|
|
1086
|
+
await join();
|
|
1087
|
+
if (ctx.role === 'follower') {
|
|
1088
|
+
await waitForLeader(1000);
|
|
1089
|
+
// Only real differences go to the leader (a no-op would still be acked, but costs a message)
|
|
1090
|
+
const patch = { cleared: false, team: scopeTeamId() };
|
|
1091
|
+
if (typeof opts.status === 'string') patch.status = opts.status;
|
|
1092
|
+
if (differs(patch)) change(patch);
|
|
572
1093
|
}
|
|
573
1094
|
|
|
574
1095
|
if (s) { s.ready = true; s.error = null; }
|
|
@@ -576,13 +1097,22 @@ if (!window.ManifestRealtimeHub) {
|
|
|
576
1097
|
}
|
|
577
1098
|
|
|
578
1099
|
function stop() {
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
if (typeof ctx.sub === 'function') { try { ctx.sub(); } catch (e) { } }
|
|
583
|
-
ctx.sub = null;
|
|
1100
|
+
listen(false);
|
|
1101
|
+
resign();
|
|
1102
|
+
ctx.suspended = false;
|
|
584
1103
|
ctx.started = false;
|
|
585
|
-
|
|
1104
|
+
ctx.userId = null;
|
|
1105
|
+
ctx.roster = {};
|
|
1106
|
+
ctx.mine = null;
|
|
1107
|
+
// The next user in this tab starts clean
|
|
1108
|
+
ctx.status = 'online';
|
|
1109
|
+
ctx.metadata = null;
|
|
1110
|
+
ctx.team = undefined;
|
|
1111
|
+
ctx.cleared = false;
|
|
1112
|
+
ctx.stamp = 0;
|
|
1113
|
+
ctx.sent = null;
|
|
1114
|
+
ctx.sentAt = 0;
|
|
1115
|
+
const s = store(); if (s) { s.ready = false; s.records = {}; s.me = null; }
|
|
586
1116
|
}
|
|
587
1117
|
|
|
588
1118
|
/* Registration */
|
|
@@ -593,13 +1123,16 @@ if (!window.ManifestRealtimeHub) {
|
|
|
593
1123
|
// Clear on sign-out
|
|
594
1124
|
try {
|
|
595
1125
|
Alpine.effect(() => {
|
|
596
|
-
|
|
1126
|
+
const user = authUser();
|
|
1127
|
+
if (!ctx.started) return;
|
|
1128
|
+
// Signed out, or a different user (guest restored after logout): the
|
|
1129
|
+
// record was removed by before-logout while the session was valid
|
|
1130
|
+
if (!user || user.$id !== ctx.userId) stop();
|
|
597
1131
|
});
|
|
598
1132
|
} catch (e) { }
|
|
599
1133
|
|
|
600
|
-
// Re-scope on team switch: refilter the roster
|
|
601
|
-
//
|
|
602
|
-
// delivered to them once the read grant moves)
|
|
1134
|
+
// Re-scope on team switch: refilter the roster locally; the writer
|
|
1135
|
+
// deletes + rewrites own presence under the new grant
|
|
603
1136
|
let lastTeam;
|
|
604
1137
|
try {
|
|
605
1138
|
Alpine.effect(() => {
|
|
@@ -607,8 +1140,11 @@ if (!window.ManifestRealtimeHub) {
|
|
|
607
1140
|
if (team === lastTeam) return;
|
|
608
1141
|
lastTeam = team;
|
|
609
1142
|
if (!ctx.started) return;
|
|
610
|
-
|
|
611
|
-
|
|
1143
|
+
render();
|
|
1144
|
+
const next = scopeTeamId();
|
|
1145
|
+
if (next === ctx.team) return;
|
|
1146
|
+
change({ team: next });
|
|
1147
|
+
schedulePublish(0);
|
|
612
1148
|
});
|
|
613
1149
|
} catch (e) { }
|
|
614
1150
|
|
|
@@ -618,14 +1154,19 @@ if (!window.ManifestRealtimeHub) {
|
|
|
618
1154
|
get list() { return all(); },
|
|
619
1155
|
get ready() { return !!store()?.ready; },
|
|
620
1156
|
get error() { return store()?.error || null; },
|
|
621
|
-
get me() { return store()?.me || null; }
|
|
1157
|
+
get me() { return store()?.me || null; },
|
|
1158
|
+
get leader() { return isWriter(); }
|
|
622
1159
|
};
|
|
623
1160
|
Alpine.magic('presence', () => api);
|
|
624
1161
|
});
|
|
625
1162
|
|
|
626
|
-
//
|
|
627
|
-
window.addEventListener('
|
|
1163
|
+
// auth logout(): delete our record before the session is deleted (after, it 401s)
|
|
1164
|
+
window.addEventListener('manifest:auth:before-logout', e => {
|
|
1165
|
+
if (!ctx.started && !ctx.sent) return;
|
|
1166
|
+
const pending = clear();
|
|
1167
|
+
if (e?.detail && typeof e.detail.waitUntil === 'function') e.detail.waitUntil(pending);
|
|
1168
|
+
});
|
|
628
1169
|
|
|
629
1170
|
// Non-Alpine handle
|
|
630
|
-
window.ManifestPresence = { start, stop, set, clear, of, all };
|
|
1171
|
+
window.ManifestPresence = { start, stop, set, clear, of, all, get leader() { return isWriter(); } };
|
|
631
1172
|
})();
|
package/lib/manifest.data.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"manifest.appwrite.auth.js": "sha384-
|
|
3
|
-
"manifest.appwrite.data.js": "sha384-
|
|
4
|
-
"manifest.appwrite.presences.js": "sha384-
|
|
2
|
+
"manifest.appwrite.auth.js": "sha384-n+Fohtui5o2h3HpM7ifnop9YsAdlTj0uHYfzljQMghLJeDkODC6OXop6ds6OTZha",
|
|
3
|
+
"manifest.appwrite.data.js": "sha384-shHW4TELqrKNvs4SPLSZXalrfvjGOb07bIgQDQmJzYh9C3tevkFZ21Gj1DJXPY9X",
|
|
4
|
+
"manifest.appwrite.presences.js": "sha384-O3EedwV2QTzd4YotjvGPsDHbxaGbtRaZuNopC7/Cfoo5uYPo8ZHYkCPCWurXpA2/",
|
|
5
5
|
"manifest.bindings.js": "sha384-lPtMf8Ykaic9gNVZKq8Scia1881ZeMAyxer3WCIkUNwwrgzGBWto1OXADUwjvORF",
|
|
6
6
|
"manifest.charts.js": "sha384-BnTxO3ncLxg82aV+64tQMS3ssN+RKZ69Dic6Oruz0pw+/UIK2MAZicg8+ooHF2ZA",
|
|
7
7
|
"manifest.chat.js": "sha384-8kxS2HImRVeRiarqaGiNFlCTqB7inp/y7Hn0kIPNzADl130s4JgnmJ7uCmW0Mmvt",
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"manifest.combobox.js": "sha384-/lJo6vaxKjgnBSRs/dzkhK1dzGk3GBw8FISoNJZB70mwAVwu1k5veZyBXjOb4keS",
|
|
12
12
|
"manifest.components.js": "sha384-t2qgBbcGPMoTYpMffOHW2dM07UWIq3pU3PYqLGrS6QP2hzCer4ofgaIKA+7hW558",
|
|
13
13
|
"manifest.computed.js": "sha384-GYML/e81gQfN+iDbqhPUgny8bINCyL+SrbTofoGk4hlCnLLjv51mCv42JMqq+ku5",
|
|
14
|
-
"manifest.data.js": "sha384-
|
|
14
|
+
"manifest.data.js": "sha384-XAjBF3BiFfuCw1Sljw5xWz9b893wMtJ67+smTu3nT/vJzybHtm9T9yUuNIZxttT8",
|
|
15
15
|
"manifest.datepicker.js": "sha384-pZUQhUK6u5cl6g0myBXND/Wtrs1RTovYmy/ETQLUV0JujvTvUdRNc/XjPpVhtK16",
|
|
16
16
|
"manifest.defer.js": "sha384-PRp7+dCZHnnl55rX2xrHutLrQnszHo7o5o9Tq28M/yjLZPuXDzcwQNxCdvbtCYSz",
|
|
17
17
|
"manifest.device.js": "sha384-YeQaS56L8IILqrQNBSeAOLwIh5DuAOrE60cYLK1+46qJtUrXlAvqGe2j5mbV4Vq7",
|
|
@@ -29,13 +29,13 @@
|
|
|
29
29
|
"manifest.status.js": "sha384-ofu7nBnVIGZ1U1o2R9d2H3V8aEMPUCVbl5FO3gIToXqi0oa36fTviEdh5UU7Kitw",
|
|
30
30
|
"manifest.submissions.js": "sha384-v9eS47ytAfTGIKAyVnbd0QWegucVS7yduvigqfsxxoqXmbaEoy0M2y+BiI4xeZBd",
|
|
31
31
|
"manifest.svg.js": "sha384-qr/8H9+2cIhSXNbRWRtIdrDlTOxKlNJqwEefHvCYoiBNW/kKhPTFa109Orv/EBnb",
|
|
32
|
-
"manifest.sw.js": "sha384-
|
|
32
|
+
"manifest.sw.js": "sha384-TSRtiRTLIduflsBdi2ojvyNrO5su/eUrfrRyatBvAT7d6PWCXckMY3Bq+9RDTWZt",
|
|
33
33
|
"manifest.tabs.js": "sha384-otU09H7jnawVKQdLAYpMCd3jx00tgyPVr42D2hLIBzN5dG4se505YesavdnMqEi1",
|
|
34
34
|
"manifest.tailwind.js": "sha384-yuP3LEvWU+QVjxjkZ0YhErtC9RrGmhOmHjjFjhS9obqZbp5/KTIEnSR0CXDvHE0B",
|
|
35
35
|
"manifest.toasts.js": "sha384-UpOz9fAdGeGUhL0NamBg5iPepEfIy73p9HYdcxfOQC5b7CVsl7Our0skdZzaLNcC",
|
|
36
36
|
"manifest.tooltips.js": "sha384-hXGp5j0s6p2kGZY/hqLPEbaUv68ca63kFCjYiZqK3DcC12mpHTBy1vz3kuApyf4p",
|
|
37
37
|
"manifest.url.parameters.js": "sha384-J2aSVBOPsoqsbafHndrWLHEDpKb4AKJAoQnVmKA4gZh5P/8HHjFWHO/lkusmG84l",
|
|
38
|
-
"manifest.utilities.js": "sha384-
|
|
38
|
+
"manifest.utilities.js": "sha384-UYU0eluyEtLq0sKoeeogRNbHa3cqkrWedtSlXYMBAIaDLF4Z4g5RIVYnCuVWQ19N",
|
|
39
39
|
"manifest.virtual.js": "sha384-PtIDx042i29mkxEYZH+y3whBzKgBgV01CU1XzzeEl/8TBPl9qvny4ppyXgYI5DsM",
|
|
40
40
|
"manifest.js": "sha384-vaJVFuwnaYalVw8vjut1si3Kqwk5+sDHiC3iScfS417NSWqfhNZNBdvcF2lUbuz+"
|
|
41
41
|
}
|
package/lib/manifest.sw.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
// Build stamps the published version here; unstamped (dev) falls back to the
|
|
18
18
|
// registration URL's `v`, then 'dev'.
|
|
19
|
-
const BUILD_VERSION = '0.5.
|
|
19
|
+
const BUILD_VERSION = '0.5.307';
|
|
20
20
|
const CACHE_PREFIX = 'mnfst-sw:';
|
|
21
21
|
const META_CACHE = CACHE_PREFIX + 'meta';
|
|
22
22
|
// Sized to hold a full precache.json warm-up (PRECACHE_MAX_ENTRIES server-side)
|
|
@@ -1343,6 +1343,12 @@ TailwindCompiler.prototype.scheduleEnsureUtilityStylesLast = function () {
|
|
|
1343
1343
|
});
|
|
1344
1344
|
};
|
|
1345
1345
|
|
|
1346
|
+
// Tailwind browser runtime output and baked prerender utilities: not theme sources
|
|
1347
|
+
function isGeneratedUtilitiesStyle(style) {
|
|
1348
|
+
return style.hasAttribute('data-mnfst-utilities') ||
|
|
1349
|
+
(!style.id && (style.textContent || '').trimStart().startsWith('/*! tailwindcss'));
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1346
1352
|
// Discover CSS files from stylesheets and imports
|
|
1347
1353
|
TailwindCompiler.prototype.discoverCssFiles = function () {
|
|
1348
1354
|
try {
|
|
@@ -1382,8 +1388,12 @@ TailwindCompiler.prototype.discoverCssFiles = function () {
|
|
|
1382
1388
|
// Add any inline styles (exclude generated styles)
|
|
1383
1389
|
const styleElements = document.querySelectorAll('style:not(#manifest-styles)');
|
|
1384
1390
|
for (const style of styleElements) {
|
|
1391
|
+
if (isGeneratedUtilitiesStyle(style)) continue;
|
|
1385
1392
|
if (style.textContent && style.textContent.trim()) {
|
|
1386
1393
|
const id = style.id || `inline-style-${Array.from(styleElements).indexOf(style)}`;
|
|
1394
|
+
// Synthetic ids aren't on the element: keep it for fetchThemeContent
|
|
1395
|
+
if (!this.inlineStyleSources) this.inlineStyleSources = new Map();
|
|
1396
|
+
this.inlineStyleSources.set(id, style);
|
|
1387
1397
|
this.cssFiles.add('inline:' + id);
|
|
1388
1398
|
}
|
|
1389
1399
|
}
|
|
@@ -1654,7 +1664,8 @@ TailwindCompiler.prototype.fetchThemeContent = async function () {
|
|
|
1654
1664
|
|
|
1655
1665
|
if (source.startsWith('inline:')) {
|
|
1656
1666
|
const styleId = source.replace('inline:', '');
|
|
1657
|
-
const
|
|
1667
|
+
const kept = this.inlineStyleSources && this.inlineStyleSources.get(styleId);
|
|
1668
|
+
const styleElement = (kept && kept.isConnected) ? kept : styleId ?
|
|
1658
1669
|
document.getElementById(styleId) :
|
|
1659
1670
|
document.querySelector('style');
|
|
1660
1671
|
if (styleElement) {
|
|
@@ -774,6 +774,12 @@ TailwindCompiler.prototype.scheduleEnsureUtilityStylesLast = function () {
|
|
|
774
774
|
});
|
|
775
775
|
};
|
|
776
776
|
|
|
777
|
+
// Tailwind browser runtime output and baked prerender utilities: not theme sources
|
|
778
|
+
function isGeneratedUtilitiesStyle(style) {
|
|
779
|
+
return style.hasAttribute('data-mnfst-utilities') ||
|
|
780
|
+
(!style.id && (style.textContent || '').trimStart().startsWith('/*! tailwindcss'));
|
|
781
|
+
}
|
|
782
|
+
|
|
777
783
|
// Discover CSS files from stylesheets and imports
|
|
778
784
|
TailwindCompiler.prototype.discoverCssFiles = function () {
|
|
779
785
|
try {
|
|
@@ -813,8 +819,12 @@ TailwindCompiler.prototype.discoverCssFiles = function () {
|
|
|
813
819
|
// Add any inline styles (exclude generated styles)
|
|
814
820
|
const styleElements = document.querySelectorAll('style:not(#manifest-styles)');
|
|
815
821
|
for (const style of styleElements) {
|
|
822
|
+
if (isGeneratedUtilitiesStyle(style)) continue;
|
|
816
823
|
if (style.textContent && style.textContent.trim()) {
|
|
817
824
|
const id = style.id || `inline-style-${Array.from(styleElements).indexOf(style)}`;
|
|
825
|
+
// Synthetic ids aren't on the element: keep it for fetchThemeContent
|
|
826
|
+
if (!this.inlineStyleSources) this.inlineStyleSources = new Map();
|
|
827
|
+
this.inlineStyleSources.set(id, style);
|
|
818
828
|
this.cssFiles.add('inline:' + id);
|
|
819
829
|
}
|
|
820
830
|
}
|
|
@@ -1085,7 +1095,8 @@ TailwindCompiler.prototype.fetchThemeContent = async function () {
|
|
|
1085
1095
|
|
|
1086
1096
|
if (source.startsWith('inline:')) {
|
|
1087
1097
|
const styleId = source.replace('inline:', '');
|
|
1088
|
-
const
|
|
1098
|
+
const kept = this.inlineStyleSources && this.inlineStyleSources.get(styleId);
|
|
1099
|
+
const styleElement = (kept && kept.isConnected) ? kept : styleId ?
|
|
1089
1100
|
document.getElementById(styleId) :
|
|
1090
1101
|
document.querySelector('style');
|
|
1091
1102
|
if (styleElement) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mnfst",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.307",
|
|
4
4
|
"private": false,
|
|
5
5
|
"workspaces": [
|
|
6
6
|
"templates/starter",
|
|
@@ -62,6 +62,8 @@
|
|
|
62
62
|
"test:e2e:prerender-patch": "node tests/e2e/utilities-prerender-patch.e2e.mjs",
|
|
63
63
|
"test:e2e:hidden-responsive": "node tests/e2e/utilities-hidden-responsive.e2e.mjs",
|
|
64
64
|
"test:e2e:tailwind-dark": "node tests/e2e/tailwind-dark-variant.e2e.mjs",
|
|
65
|
+
"test:e2e:inline-style-variants": "node tests/e2e/utilities-inline-style-variants.e2e.mjs",
|
|
66
|
+
"test:e2e:presence-tabs": "node tests/e2e/presence-tabs.e2e.mjs",
|
|
65
67
|
"lint": "echo 'No linting configured'",
|
|
66
68
|
"release:docs": "npm test && node scripts/release-bump.mjs packages/docs && cd packages/docs && npm publish --auth-type=web",
|
|
67
69
|
"release:check": "node scripts/release-check.mjs"
|