mnfst 0.5.329 → 0.5.331

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  (function () {
4
4
 
5
- const MANIFEST_BUILD_VERSION = '0.5.329';
5
+ const MANIFEST_BUILD_VERSION = '0.5.331';
6
6
 
7
7
  /* Manifest Data Sources - Configuration */
8
8
 
@@ -568,6 +568,52 @@ function sourceGeneration(dataSourceName) {
568
568
  return sourceGen.get(dataSourceName) || 0;
569
569
  }
570
570
 
571
+ // Team of the rows each source shows: written only when a read's rows land (scopeTeam landing option)
572
+ const loadTeams = new Map();
573
+ // Rows from reads built for different teams (a page appended across a switch): never current
574
+ const MIXED_TEAMS = Symbol('mixed');
575
+ // Reads in flight per source: { team } — undefined until the scope build, SKIPPED when nothing was sent
576
+ const teamReads = new Map();
577
+ const SKIPPED = Symbol('skipped');
578
+ function teamNow() {
579
+ const team = typeof Alpine !== 'undefined' ? Alpine.store('auth')?.currentTeam : null;
580
+ return team?.$id || team?.id || null;
581
+ }
582
+ // Rows emptied without a read (unresolved scope, failed first load): no team to compare
583
+ function clearLoadTeam(dataSourceName) { loadTeams.delete(dataSourceName); }
584
+ function loadTeamOf(dataSourceName) {
585
+ const team = loadTeams.get(dataSourceName);
586
+ return team === MIXED_TEAMS ? undefined : team;
587
+ }
588
+ // A read's handle: building() while it builds again, built(team) after its scope build, end() when it settles
589
+ function beginTeamRead(dataSourceName) {
590
+ const read = { team: undefined };
591
+ let reads = teamReads.get(dataSourceName);
592
+ if (!reads) teamReads.set(dataSourceName, reads = new Set());
593
+ reads.add(read);
594
+ return {
595
+ building() { read.team = undefined; },
596
+ built(team) { read.team = team === undefined ? SKIPPED : team; },
597
+ end() {
598
+ reads.delete(read);
599
+ if (!reads.size && teamReads.get(dataSourceName) === reads) teamReads.delete(dataSourceName);
600
+ }
601
+ };
602
+ }
603
+ // A read still building, or built for this team, will land (or settle) first
604
+ function teamReadHolds(dataSourceName, team) {
605
+ const reads = teamReads.get(dataSourceName);
606
+ if (!reads) return false;
607
+ for (const read of reads) if (read.team === undefined || read.team === team) return true;
608
+ return false;
609
+ }
610
+ // Applied landing: a replace sets the team; an append built for another team mixes it
611
+ function recordLandedTeam(source, options) {
612
+ if (!options) return;
613
+ if ('scopeTeam' in options) loadTeams.set(source, options.scopeTeam);
614
+ else if ('appendTeam' in options && loadTeams.has(source) && loadTeams.get(source) !== options.appendTeam) loadTeams.set(source, MIXED_TEAMS);
615
+ }
616
+
571
617
  // Drop a source from memory (rows, caches, in-flight keys, freshness): the
572
618
  // next read hydrates/fetches for the new scope; older loads are discarded
573
619
  function resetSource(dataSourceName) {
@@ -581,6 +627,7 @@ function resetSource(dataSourceName) {
581
627
  for (const key of [...loadingPromises.keys()]) if (key.startsWith(prefix)) loadingPromises.delete(key);
582
628
  for (const key of [...loadReadTokens.keys()]) if (key.startsWith(prefix)) loadReadTokens.delete(key);
583
629
  freshness.delete(dataSourceName);
630
+ loadTeams.delete(dataSourceName);
584
631
  pendingLocal.delete(dataSourceName);
585
632
  for (let i = pendingLandings.length - 1; i >= 0; i--) {
586
633
  if (pendingLandings[i].source !== dataSourceName) continue;
@@ -1088,6 +1135,7 @@ function flushLandings() {
1088
1135
  if (typeof op.options?.readToken === 'number' && !isLatestRead(op.source, op.options.readToken)) { skipped.add(op); continue; }
1089
1136
  const state = writeSource(op.source, group.rows, op.options);
1090
1137
  if (!state) continue;
1138
+ recordLandedTeam(op.source, op.options);
1091
1139
  touched.add(op.source);
1092
1140
  if (!op.options.persistHydration && op.rows !== null && op.rows !== undefined) landed.add(op.source);
1093
1141
  // Only load completions (explicit loading state) feed render-ready; realtime upserts never do
@@ -1443,109 +1491,77 @@ function initializeStore() {
1443
1491
  Alpine.store('data', initialStore);
1444
1492
  }
1445
1493
 
1446
- // Listen for team changes to reload team-scoped data sources
1494
+ // Team-scoped sources (team, teams, or either in a dual scope)
1495
+ function isTeamScope(scope) {
1496
+ return scope === 'team' || scope === 'teams' || (Array.isArray(scope) && (scope.includes('team') || scope.includes('teams')));
1497
+ }
1498
+
1499
+ // Each poll reloads sources read under another team than the current one
1447
1500
  function setupTeamChangeListener() {
1448
1501
  if (typeof Alpine === 'undefined') return;
1449
1502
 
1450
- let lastTeamId = null;
1451
1503
  let checking = false;
1504
+ let scoped = [];
1505
+ let scopedFor = null;
1506
+ // Sources with no recorded read (skipped, hydrated) reloaded once per team
1507
+ const kicked = new Map();
1452
1508
 
1453
1509
  const checkTeamChange = async () => {
1454
1510
  if (checking) return;
1455
1511
  checking = true;
1456
1512
 
1457
1513
  try {
1458
- const authStore = Alpine.store('auth');
1459
- if (!authStore) {
1460
- checking = false;
1461
- return;
1462
- }
1463
-
1464
- const currentTeamId = authStore.currentTeam?.$id || null;
1465
-
1466
- if (currentTeamId !== lastTeamId) {
1467
- lastTeamId = currentTeamId;
1468
-
1469
- // Get manifest to identify team-scoped data sources
1470
- const manifest = await window.ManifestDataConfig.ensureManifest();
1471
- if (!manifest?.data) {
1472
- checking = false;
1473
- return;
1474
- }
1475
-
1476
- // Find team-scoped data sources (both "team" and "teams" scopes, including dual scope)
1477
- const teamScopedDataSources = Object.getOwnPropertyNames(manifest.data).map(name => [name, manifest.data[name]])
1478
- .filter(([name, config]) => {
1479
- if (typeof config === 'object' && config.scope) {
1480
- const scope = config.scope;
1481
- // Check for "team", "teams", or array containing team/teams
1482
- if (scope === 'team' || scope === 'teams') {
1483
- return true;
1484
- }
1485
- if (Array.isArray(scope) && (scope.includes('team') || scope.includes('teams'))) {
1486
- return true;
1487
- }
1488
- }
1489
- return false;
1490
- })
1491
- .map(([name]) => name);
1492
-
1493
- if (teamScopedDataSources.length === 0) {
1494
- checking = false;
1495
- return;
1514
+ if (!Alpine.store('auth')) return;
1515
+ const manifest = await window.ManifestDataConfig.ensureManifest();
1516
+ if (!manifest?.data) return;
1517
+ if (scopedFor !== manifest.data) {
1518
+ scopedFor = manifest.data;
1519
+ scoped = Object.getOwnPropertyNames(manifest.data)
1520
+ .filter(name => { const config = manifest.data[name]; return !!config && typeof config === 'object' && isTeamScope(config.scope); });
1521
+ }
1522
+
1523
+ const team = teamNow();
1524
+ const raw = rawOf(Alpine.store('data')) || {};
1525
+ let stale = null;
1526
+ for (const name of scoped) {
1527
+ // A read still building, or built for this team, lands first
1528
+ if (teamReadHolds(name, team)) continue;
1529
+ if (loadTeams.has(name)) {
1530
+ if (loadTeams.get(name) === team) continue;
1531
+ } else {
1532
+ // Never read: stays lazy; its first read builds for the current team
1533
+ if (raw[`_${name}_state`] === undefined && raw[name] == null) continue;
1534
+ if (team === null || kicked.get(name) === team) continue;
1535
+ kicked.set(name, team);
1496
1536
  }
1537
+ (stale || (stale = [])).push(name);
1538
+ }
1539
+ if (!stale) return;
1497
1540
 
1498
- // Clear cache for team-scoped data sources (similar to locale change)
1499
- teamScopedDataSources.forEach(dataSourceName => {
1500
- // Clear all locale variants of this data source
1501
- const keysToDelete = [];
1502
- for (const key of dataSourceCache.keys()) {
1503
- if (key.startsWith(`${dataSourceName}:`)) {
1504
- keysToDelete.push(key);
1505
- }
1506
- }
1507
- keysToDelete.forEach(key => dataSourceCache.delete(key));
1541
+ const prefixes = stale.map(name => `${name}:`);
1542
+ const owned = key => prefixes.some(prefix => key.startsWith(prefix));
1543
+ for (const key of [...dataSourceCache.keys()]) if (owned(key)) dataSourceCache.delete(key);
1544
+ for (const key of [...loadingPromises.keys()]) if (owned(key)) loadingPromises.delete(key);
1508
1545
 
1509
- // Clear loading promises for this data source
1510
- const promisesToDelete = [];
1511
- for (const key of loadingPromises.keys()) {
1512
- if (key.startsWith(`${dataSourceName}:`)) {
1513
- promisesToDelete.push(key);
1514
- }
1515
- }
1516
- promisesToDelete.forEach(key => loadingPromises.delete(key));
1517
- });
1546
+ const store = Alpine.store('data');
1547
+ if (store) {
1548
+ stale.forEach(name => { delete store[name]; });
1549
+ touchSources(store, stale);
1550
+ }
1551
+ stale.forEach(name => {
1552
+ loadTeams.delete(name);
1553
+ window.ManifestDataProxies?.clearAccessCache?.(name);
1554
+ });
1518
1555
 
1519
- // Remove team-scoped data from store
1520
- const store = Alpine.store('data');
1521
- if (store) {
1522
- teamScopedDataSources.forEach(dataSourceName => {
1523
- delete store[dataSourceName];
1556
+ // Reload for the current team; outranks a $query built for the old one
1557
+ const loadDataSource = window.ManifestDataMain?.loadDataSource;
1558
+ if (loadDataSource) {
1559
+ stale.forEach(name => {
1560
+ window.ManifestDataMain?.cancelAuthRetry?.(name);
1561
+ Promise.resolve(loadDataSource(name, undefined, { reload: true })).catch(error => {
1562
+ console.error('[Manifest Data] Failed to reload data source after team change:', name, error);
1524
1563
  });
1525
- touchSources(store, teamScopedDataSources);
1526
- }
1527
-
1528
- // Clear proxy cache for these data sources
1529
- teamScopedDataSources.forEach(dataSourceName => {
1530
- if (window.ManifestDataProxies && window.ManifestDataProxies.clearAccessCache) {
1531
- window.ManifestDataProxies.clearAccessCache(dataSourceName);
1532
- }
1533
1564
  });
1534
-
1535
- // Reload (not just cache-clear) so data is fresh for the new team
1536
- const loadDataSource = window.ManifestDataMain?.loadDataSource;
1537
- if (loadDataSource) {
1538
- // Reload all team-scoped data sources with new team context
1539
- Promise.all(teamScopedDataSources.map(async (dataSourceName) => {
1540
- try {
1541
- // Reload with new team context
1542
- await loadDataSource(dataSourceName);
1543
- } catch (error) {
1544
- console.error('[Manifest Data] Failed to reload data source after team change:', dataSourceName, error);
1545
- }
1546
- })).then(() => {
1547
- });
1548
- }
1549
1565
  }
1550
1566
  } catch (error) {
1551
1567
  console.error('[Manifest Data] Error handling team change:', error);
@@ -1557,9 +1573,7 @@ function setupTeamChangeListener() {
1557
1573
  // Wait for Alpine and auth store to be ready, then start polling
1558
1574
  let teamCheckIntervalId = null;
1559
1575
  const startPolling = () => {
1560
- const authStore = Alpine.store('auth');
1561
- if (authStore) {
1562
- lastTeamId = authStore.currentTeam?.$id || null;
1576
+ if (Alpine.store('auth')) {
1563
1577
  if (!teamCheckIntervalId) {
1564
1578
  // Poll every 2s to limit CPU wakeups; team changes are rare
1565
1579
  teamCheckIntervalId = setInterval(window.ManifestPending?.background?.(checkTeamChange) ?? checkTeamChange, 2000);
@@ -1570,11 +1584,6 @@ function setupTeamChangeListener() {
1570
1584
  }
1571
1585
  };
1572
1586
 
1573
- // Logout already reset scoped sources (data main); don't reload them again as a team change
1574
- const syncTeam = () => { lastTeamId = Alpine.store('auth')?.currentTeam?.$id || null; };
1575
- window.addEventListener('manifest:auth:logout', syncTeam);
1576
- window.addEventListener('manifest:auth:session-cleared', syncTeam);
1577
-
1578
1587
  if (document.readyState === 'loading') {
1579
1588
  document.addEventListener('DOMContentLoaded', startPolling);
1580
1589
  } else {
@@ -1984,6 +1993,9 @@ window.ManifestDataStore = {
1984
1993
  sourceFreshness,
1985
1994
  // Persistence (§12.2)
1986
1995
  sourceGeneration,
1996
+ clearLoadTeam,
1997
+ loadTeamOf,
1998
+ beginTeamRead,
1987
1999
  isStaleWrite,
1988
2000
  resetSource,
1989
2001
  touchSource,
@@ -2058,6 +2070,7 @@ window.ManifestDataStore = {
2058
2070
  landedIdentity: new Map(), // source -> identity its pending rows were read under
2059
2071
  writeTimer: null,
2060
2072
  hydrated: new Set(), // sources hydrated (or attempted) this generation
2073
+ teamRejected: new Map(), // source -> team its snapshot was refused under (retried under another team)
2061
2074
  hydratedIdentity: null, // identity auth-dependent hydration last ran under
2062
2075
  fetchKicked: new Set(),
2063
2076
  watching: false,
@@ -2079,6 +2092,16 @@ window.ManifestDataStore = {
2079
2092
  try { return JSON.stringify(source.queries || '').includes('$auth.'); } catch { return false; }
2080
2093
  }
2081
2094
 
2095
+ // Team-scoped sources stamp the team their rows were read for; once a team is known, another team's snapshot is skipped
2096
+ function isTeamScoped(source) {
2097
+ const scope = source && typeof source === 'object' ? source.scope : null;
2098
+ return scope === 'team' || scope === 'teams' || (Array.isArray(scope) && (scope.includes('team') || scope.includes('teams')));
2099
+ }
2100
+ function currentTeamId() {
2101
+ const team = (typeof Alpine !== 'undefined' && Alpine.store) ? Alpine.store('auth')?.currentTeam : null;
2102
+ return team?.$id || team?.id || null;
2103
+ }
2104
+
2082
2105
  // Current identity: '' signed out (or no auth plugin), null while auth is still booting
2083
2106
  function authIdentity() {
2084
2107
  const auth = (typeof Alpine !== 'undefined' && Alpine.store) ? Alpine.store('auth') : null;
@@ -2173,7 +2196,7 @@ window.ManifestDataStore = {
2173
2196
  for (const [name, source] of Object.entries(manifest?.data || {})) {
2174
2197
  if (!source || typeof source !== 'object') continue;
2175
2198
  const cfg = normalizeConfig(source.persist);
2176
- if (cfg) { cfg.authDependent = isAuthDependent(source); state.sources.set(name, cfg); }
2199
+ if (cfg) { cfg.authDependent = isAuthDependent(source); cfg.teamScoped = isTeamScoped(source); state.sources.set(name, cfg); }
2177
2200
  }
2178
2201
  state.scopeExpr = typeof manifest?.persistence?.scope === 'string' && manifest.persistence.scope.trim()
2179
2202
  ? manifest.persistence.scope.trim() : null;
@@ -2212,6 +2235,7 @@ window.ManifestDataStore = {
2212
2235
  const cfg = normalizeConfig(config === undefined ? true : config);
2213
2236
  if (!cfg) { state.sources.delete(source); return false; }
2214
2237
  cfg.authDependent = isAuthDependent(state.manifest?.data?.[source] || state.manifest?.appwrite?.[source]);
2238
+ cfg.teamScoped = isTeamScoped(state.manifest?.data?.[source] || state.manifest?.appwrite?.[source]);
2215
2239
  state.sources.set(source, cfg);
2216
2240
  state.hydrated.delete(source);
2217
2241
  state.fetchKicked.delete(source);
@@ -2337,6 +2361,7 @@ window.ManifestDataStore = {
2337
2361
  state.generation++;
2338
2362
  cancelWrites();
2339
2363
  state.hydrated.clear();
2364
+ state.teamRejected.clear();
2340
2365
  state.fetchKicked.clear();
2341
2366
  // pending → resolved is boot, not a switch: rows loaded meanwhile stay (hydrate skips fresh sources), nothing is wiped
2342
2367
  if (!wasPending) {
@@ -2497,6 +2522,8 @@ window.ManifestDataStore = {
2497
2522
  identity = authUnverified() ? null : authIdentity();
2498
2523
  if (identity === null || landed === null || (landed !== undefined && landed !== identity)) return null;
2499
2524
  }
2525
+ // The team of the landed rows (the store records it per landing); unknown → unstamped
2526
+ const team = cfg.teamScoped ? ds.loadTeamOf?.(source) : undefined;
2500
2527
  try {
2501
2528
  const snapshot = snapshotOf(source, raw, cfg);
2502
2529
  if (snapshot === null) return null;
@@ -2509,7 +2536,8 @@ window.ManifestDataStore = {
2509
2536
  frameworkVersion: state.frameworkVersion,
2510
2537
  deployment: state.deployment,
2511
2538
  locale: liveLocale(),
2512
- ...(cfg.authDependent ? { identity } : {})
2539
+ ...(cfg.authDependent ? { identity } : {}),
2540
+ ...(team !== undefined ? { team } : {})
2513
2541
  };
2514
2542
  } catch (error) {
2515
2543
  warnOnce(`snapshot:${source}`, `persistence skipped "${source}" (rows are not serialisable)`, error);
@@ -2590,6 +2618,11 @@ window.ManifestDataStore = {
2590
2618
  const identity = hydrationIdentity();
2591
2619
  if (identity === null || record.identity !== identity) return unconfirmed() ? { ok: false } : { ok: false, drop: true };
2592
2620
  }
2621
+ // Another team's (or, with a team to compare, an unstamped) snapshot: kept for when that team is current again
2622
+ if (cfg.teamScoped) {
2623
+ const team = currentTeamId();
2624
+ if (team !== null && (!('team' in record) || record.team !== team)) return { ok: false, retry: true };
2625
+ }
2593
2626
  return { ok: true };
2594
2627
  }
2595
2628
 
@@ -2602,10 +2635,12 @@ window.ManifestDataStore = {
2602
2635
  const known = identity !== null;
2603
2636
  if (known && identity !== state.hydratedIdentity) {
2604
2637
  for (const [source, cfg] of state.sources) if (cfg.authDependent) state.hydrated.delete(source);
2638
+ state.teamRejected.clear();
2605
2639
  state.hydratedIdentity = identity;
2606
2640
  }
2607
2641
  const pending = sources.filter(source => state.sources.has(source) && !state.hydrated.has(source)
2608
- && (known || !state.sources.get(source).authDependent));
2642
+ && (known || !state.sources.get(source).authDependent)
2643
+ && !(state.teamRejected.has(source) && state.teamRejected.get(source) === currentTeamId()));
2609
2644
  if (!ds || !pending.length || !state.enabled || state.disabled || state.scopePending) return;
2610
2645
  for (const source of pending) state.hydrated.add(source);
2611
2646
  const generation = state.generation;
@@ -2619,11 +2654,17 @@ window.ManifestDataStore = {
2619
2654
  const record = records[i];
2620
2655
  if (!cfg || !record) return;
2621
2656
  const check = validRecord(record, cfg);
2622
- if (!check.ok) { if (check.drop) drop.push(record.key); return; }
2657
+ if (!check.ok) {
2658
+ if (check.drop) drop.push(record.key);
2659
+ if (check.retry) { state.hydrated.delete(source); state.teamRejected.set(source, currentTeamId()); }
2660
+ return;
2661
+ }
2662
+ state.teamRejected.delete(source);
2623
2663
  if (ds.sourceFreshness(source).done) return; // fresh landing already applied
2624
2664
  cfg.rows = Array.isArray(record.rows) ? record.rows.length : 1;
2625
2665
  cfg.savedAt = record.savedAt;
2626
- landings.push(ds.landRows(source, record.rows, { mode: 'replace', ready: true, fresh: false, persistHydration: true, allowDuringInit: true }));
2666
+ const team = cfg.teamScoped && 'team' in record ? { scopeTeam: record.team } : {};
2667
+ landings.push(ds.landRows(source, record.rows, { mode: 'replace', ready: true, fresh: false, persistHydration: true, allowDuringInit: true, ...team }));
2627
2668
  });
2628
2669
  if (drop.length) deleteKeys(drop).catch(() => { /* disabled */ });
2629
2670
  await Promise.all(landings);
@@ -8823,64 +8864,76 @@ function createAppwriteMethodsHandler(dataSourceName, reloadDataSource) {
8823
8864
  queries = named;
8824
8865
  }
8825
8866
  window.ManifestDataStore?.setSourceState?.(dataSourceName, { loading: true });
8826
- // A $auth. value or scope not resolved yet: wait for auth once, then run
8827
- const build = () => window.ManifestDataQueries.buildAppwriteQueries(queries || [], scope, scopeColumns);
8828
- let appwriteQueries = await build();
8829
- if (appwriteQueries === null) {
8830
- const waiting = window.ManifestDataMain?.awaitingQueries;
8831
- waiting?.add(dataSourceName);
8832
- try {
8833
- await window.ManifestDataMain?.waitForAuthChange?.();
8834
- // Let any reload of this source already running finish, then run as the newest read
8835
- window.ManifestDataStore?.endRead?.(dataSourceName, readToken);
8836
- await window.ManifestDataMain?.settledReads?.(dataSourceName);
8837
- } finally {
8838
- waiting?.delete(dataSourceName);
8867
+ // Team listener waits while this $query builds; its landing records the team the build used
8868
+ const teamRead = window.ManifestDataStore?.beginTeamRead?.(dataSourceName) || { building() {}, built() {}, end() {} };
8869
+ let builtTeam;
8870
+ const noteTeam = (team) => { builtTeam = team; teamRead.built(team); };
8871
+ try {
8872
+ // A $auth. value or scope not resolved yet: wait for auth once, then run
8873
+ const build = () => window.ManifestDataQueries.buildAppwriteQueries(queries || [], scope, scopeColumns);
8874
+ let appwriteQueries = await build();
8875
+ if (appwriteQueries === null) {
8876
+ noteTeam(undefined);
8877
+ const waiting = window.ManifestDataMain?.awaitingQueries;
8878
+ waiting?.add(dataSourceName);
8879
+ try {
8880
+ await window.ManifestDataMain?.waitForAuthChange?.();
8881
+ // Let any reload of this source already running finish, then run as the newest read
8882
+ window.ManifestDataStore?.endRead?.(dataSourceName, readToken);
8883
+ await window.ManifestDataMain?.settledReads?.(dataSourceName);
8884
+ } finally {
8885
+ waiting?.delete(dataSourceName);
8886
+ }
8887
+ readToken = window.ManifestDataStore?.beginRead?.(dataSourceName);
8888
+ window.ManifestDataStore?.setSourceState?.(dataSourceName, { loading: true });
8889
+ teamRead.building();
8890
+ appwriteQueries = await build();
8839
8891
  }
8840
- readToken = window.ManifestDataStore?.beginRead?.(dataSourceName);
8841
- window.ManifestDataStore?.setSourceState?.(dataSourceName, { loading: true });
8842
- appwriteQueries = await build();
8843
- }
8844
- if (appwriteQueries === null) {
8845
- throw new Error(`[Manifest Data] "${dataSourceName}" $query: auth not ready — sign in, or check the $auth. values in its queries`);
8846
- }
8847
- // Dedupe key: source + serialized queries (never across different queries)
8848
- const key = `${dataSourceName}:$query:${JSON.stringify(appwriteQueries.map(q => String(q)))}`;
8849
- const { runDeduped, landRows, sourceGeneration, isLatestRead } = window.ManifestDataStore || {};
8850
- const generation = sourceGeneration?.(dataSourceName);
8851
- const requireAuth = window.ManifestDataMain?.requiresIdentity?.({ ...dataSource, queries: [dataSource.queries, queries] }) ?? true;
8852
- // Paged sources: the new filter set starts again at its first window (or walks all)
8853
- const main = window.ManifestDataMain;
8854
- const spec = main?.pagingSpec?.(dataSource);
8855
- const want = spec ? main.pagedWant(dataSourceName, spec) : 0;
8856
- let paged = null;
8857
- const run = spec
8858
- ? async () => {
8859
- const fetchPaged = () => main.fetchPagedRows(dataSourceName, queries || [], {
8860
- want,
8861
- isCurrent: () => !isLatestRead || isLatestRead(dataSourceName, readToken)
8862
- });
8863
- paged = await fetchPaged();
8864
- if (paged === null) { await main.waitForAuthChange(); paged = await fetchPaged(); }
8865
- if (paged === null) throw new Error(`[Manifest Data] "${dataSourceName}" $query: auth not ready yet — retry after auth settles`);
8866
- return paged.rows;
8892
+ if (appwriteQueries === null) {
8893
+ throw new Error(`[Manifest Data] "${dataSourceName}" $query: auth not ready — sign in, or check the $auth. values in its queries`);
8867
8894
  }
8868
- : () => (main?.withRetry || ((_, fn) => fn()))(dataSource, () => window.ManifestDataAppwrite.loadTableRows(
8869
- appwriteConfig.databaseId,
8870
- tableId,
8871
- appwriteQueries,
8872
- { requireAuth }
8873
- ), () => sourceGeneration?.(dataSourceName) === generation); // shared by identical calls: stop only on a reset
8874
- const result = (runDeduped && !spec) ? await runDeduped(key, run) : await run();
8875
- // Network landing: query result replaces the source (coalesced, identity-preserving);
8876
- // only the last-issued read of this source lands
8877
- const latest = !isLatestRead || isLatestRead(dataSourceName, readToken);
8878
- if (result !== undefined && landRows && latest && sourceGeneration?.(dataSourceName) === generation) {
8879
- window.ManifestDataMain?.setActiveQuery?.(dataSourceName, queries || [], Array.isArray(result) ? result.length : 0);
8880
- if (paged) main.setPagingState(dataSourceName, { ...paged, spec }, { filters: queries || [] });
8881
- await landRows(dataSourceName, result, { mode: 'replace', fresh: true, generation, readToken });
8895
+ if (!window.ManifestDataMain?.pagingSpec?.(dataSource)) noteTeam(appwriteQueries.scopeTeam);
8896
+ // Dedupe key: source + serialized queries (never across different queries)
8897
+ const key = `${dataSourceName}:$query:${JSON.stringify(appwriteQueries.map(q => String(q)))}`;
8898
+ const { runDeduped, landRows, sourceGeneration, isLatestRead } = window.ManifestDataStore || {};
8899
+ const generation = sourceGeneration?.(dataSourceName);
8900
+ const requireAuth = window.ManifestDataMain?.requiresIdentity?.({ ...dataSource, queries: [dataSource.queries, queries] }) ?? true;
8901
+ // Paged sources: the new filter set starts again at its first window (or walks all)
8902
+ const main = window.ManifestDataMain;
8903
+ const spec = main?.pagingSpec?.(dataSource);
8904
+ const want = spec ? main.pagedWant(dataSourceName, spec) : 0;
8905
+ let paged = null;
8906
+ const run = spec
8907
+ ? async () => {
8908
+ const fetchPaged = () => main.fetchPagedRows(dataSourceName, queries || [], {
8909
+ want,
8910
+ isCurrent: () => !isLatestRead || isLatestRead(dataSourceName, readToken),
8911
+ onTeam: noteTeam
8912
+ });
8913
+ paged = await fetchPaged();
8914
+ if (paged === null) { noteTeam(undefined); await main.waitForAuthChange(); teamRead.building(); paged = await fetchPaged(); }
8915
+ if (paged === null) throw new Error(`[Manifest Data] "${dataSourceName}" $query: auth not ready yet — retry after auth settles`);
8916
+ return paged.rows;
8917
+ }
8918
+ : () => (main?.withRetry || ((_, fn) => fn()))(dataSource, () => window.ManifestDataAppwrite.loadTableRows(
8919
+ appwriteConfig.databaseId,
8920
+ tableId,
8921
+ appwriteQueries,
8922
+ { requireAuth }
8923
+ ), () => sourceGeneration?.(dataSourceName) === generation); // shared by identical calls: stop only on a reset
8924
+ const result = (runDeduped && !spec) ? await runDeduped(key, run) : await run();
8925
+ // Network landing: query result replaces the source (coalesced, identity-preserving);
8926
+ // only the last-issued read of this source lands
8927
+ const latest = !isLatestRead || isLatestRead(dataSourceName, readToken);
8928
+ if (result !== undefined && landRows && latest && sourceGeneration?.(dataSourceName) === generation) {
8929
+ window.ManifestDataMain?.setActiveQuery?.(dataSourceName, queries || [], Array.isArray(result) ? result.length : 0);
8930
+ if (paged) main.setPagingState(dataSourceName, { ...paged, spec }, { filters: queries || [] });
8931
+ await landRows(dataSourceName, result, { mode: 'replace', fresh: true, generation, readToken, ...(builtTeam === undefined ? {} : { scopeTeam: builtTeam }) });
8932
+ }
8933
+ return result;
8934
+ } finally {
8935
+ teamRead.end();
8882
8936
  }
8883
- return result;
8884
8937
  }
8885
8938
  }
8886
8939
 
@@ -11268,21 +11321,29 @@ window.ManifestDataProxies.clearNestedProxyCacheForDataSource = clearNestedProxy
11268
11321
  // manifest.data.queries.js) skips the network read and waits here instead of
11269
11322
  // sending a broken/empty-equal query. Retries once when auth settles further;
11270
11323
  // dedup by key so a source pending across repeated loads doesn't stack listeners.
11271
- const pendingAuthRetries = new Set();
11324
+ const pendingAuthRetries = new Map();
11272
11325
  const AUTH_RETRY_EVENTS = ['manifest:auth:initialized', 'manifest:auth:teams-loaded', 'manifest:auth:login', 'manifest:auth:anonymous'];
11273
11326
  function scheduleAuthRetry(dataSourceName, locale) {
11274
11327
  if (typeof window === 'undefined') return;
11275
11328
  const key = `${dataSourceName}:${locale}`;
11276
11329
  if (pendingAuthRetries.has(key)) return;
11277
- pendingAuthRetries.add(key);
11278
- const retry = () => {
11330
+ const disarm = () => {
11279
11331
  pendingAuthRetries.delete(key);
11280
11332
  AUTH_RETRY_EVENTS.forEach(type => window.removeEventListener(type, retry));
11333
+ };
11334
+ const retry = () => {
11335
+ disarm();
11281
11336
  loadDataSource(dataSourceName, locale, { reload: true });
11282
11337
  };
11338
+ pendingAuthRetries.set(key, disarm);
11283
11339
  AUTH_RETRY_EVENTS.forEach(type => window.addEventListener(type, retry));
11284
11340
  }
11285
11341
 
11342
+ // Another path reloads the source (team listener): drop its waiting retries
11343
+ function cancelAuthRetry(dataSourceName) {
11344
+ for (const [key, disarm] of [...pendingAuthRetries]) if (key.startsWith(`${dataSourceName}:`)) disarm();
11345
+ }
11346
+
11286
11347
  // Teams known for this identity: login/anonymous dispatch after teams load, teams-loaded after the background load.
11287
11348
  // A cross-tab login arrives before this tab's team load; its teams-loaded follows.
11288
11349
  let teamsSettledFor = null;
@@ -11446,19 +11507,13 @@ function setupAuthResetListener() {
11446
11507
 
11447
11508
  // Client-side scope filter: Appwrite returns all accessible files, so narrow to
11448
11509
  // the current team to match database team-scope behavior.
11510
+ // The result carries the team it filtered by (scopeTeam), read once with the filter.
11449
11511
  async function filterFilesByScope(files, scope) {
11450
- if (!files || !Array.isArray(files) || files.length === 0) {
11451
- return files;
11452
- }
11453
-
11454
- // Get auth store
11455
11512
  const authStore = typeof Alpine !== 'undefined' ? Alpine.store('auth') : null;
11456
- if (!authStore) {
11457
- return files;
11458
- }
11513
+ const hasFiles = Array.isArray(files) && files.length > 0;
11459
11514
 
11460
11515
  // Wait for auth store initialization
11461
- if (!authStore._initialized || authStore.isAuthenticated === undefined) {
11516
+ if (hasFiles && authStore && (!authStore._initialized || authStore.isAuthenticated === undefined)) {
11462
11517
  let attempts = 0;
11463
11518
  const maxAttempts = 10;
11464
11519
  while (attempts < maxAttempts && (!authStore._initialized || authStore.isAuthenticated === undefined)) {
@@ -11467,6 +11522,16 @@ async function filterFilesByScope(files, scope) {
11467
11522
  }
11468
11523
  }
11469
11524
 
11525
+ // No await below: one snapshot of the team
11526
+ const currentTeam = authStore?.currentTeam;
11527
+ const team = currentTeam?.$id || currentTeam?.id || null;
11528
+ const tag = (out) => Array.isArray(out) && window.ManifestDataQueries?.tagTeam ? window.ManifestDataQueries.tagTeam(out, team) : out;
11529
+ return tag(filterFilesSnapshot(files, scope, authStore, team, hasFiles));
11530
+ }
11531
+
11532
+ function filterFilesSnapshot(files, scope, authStore, team, hasFiles) {
11533
+ if (!hasFiles || !authStore) return files;
11534
+
11470
11535
  const isAuthenticated = authStore.isAuthenticated === true;
11471
11536
  if (!isAuthenticated) {
11472
11537
  return [];
@@ -11498,10 +11563,8 @@ async function filterFilesByScope(files, scope) {
11498
11563
  }
11499
11564
 
11500
11565
  if (hasTeamScope) {
11501
- const currentTeam = authStore.currentTeam;
11502
- const teamId = currentTeam?.$id || currentTeam?.id;
11503
- if (teamId) {
11504
- expectedPermissions.push(Permission.read(Role.team(teamId)));
11566
+ if (team) {
11567
+ expectedPermissions.push(Permission.read(Role.team(team)));
11505
11568
  } else {
11506
11569
  // No current team - return empty array (matches database behavior)
11507
11570
  return [];
@@ -11839,7 +11902,7 @@ function pagedFilters(dataSourceName, dataSource) {
11839
11902
  // Fetch pages of a table: `want` rows from `after` (a row $id), `size` per request, each
11840
11903
  // asking for one extra row so "more" is exact. isCurrent() false stops the walk.
11841
11904
  // Returns { rows, total, hasMore } or null when queries can't resolve yet (auth)
11842
- async function fetchPagedRows(dataSourceName, filters, { want, after = null, isCurrent = () => true } = {}) {
11905
+ async function fetchPagedRows(dataSourceName, filters, { want, after = null, isCurrent = () => true, onTeam } = {}) {
11843
11906
  const manifest = await window.ManifestDataConfig.ensureManifest();
11844
11907
  const dataSource = manifest?.data?.[dataSourceName];
11845
11908
  const spec = pagingSpec(dataSource);
@@ -11850,6 +11913,8 @@ async function fetchPagedRows(dataSourceName, filters, { want, after = null, isC
11850
11913
  const scopeColumns = window.ManifestDataConfig.getScopeColumns(dataSource);
11851
11914
  const base = await window.ManifestDataQueries.buildAppwriteQueries(stripPageWindow(filters), scope, scopeColumns);
11852
11915
  if (base === null) return null;
11916
+ const team = base.scopeTeam;
11917
+ onTeam?.(team);
11853
11918
  const Query = window.Appwrite.Query;
11854
11919
  const requireAuth = requiresIdentity(dataSource);
11855
11920
  const limit = Math.max(1, want || spec.size);
@@ -11870,7 +11935,7 @@ async function fetchPagedRows(dataSourceName, filters, { want, after = null, isC
11870
11935
  if (!hasMore || !got.length || !isCurrent()) break;
11871
11936
  cursor = got[got.length - 1].$id;
11872
11937
  }
11873
- return { rows, total, hasMore };
11938
+ return { rows, total, hasMore, team };
11874
11939
  }
11875
11940
 
11876
11941
  // A page landed: move the cursor to its last server row and publish $hasMore / $total.
@@ -11951,7 +12016,7 @@ async function loadMoreOnce(dataSourceName) {
11951
12016
  // Overtaken by a load or $query: its window replaces the rows, then this runs again
11952
12017
  if (!page || !isCurrent()) { if (page) requeueMore(dataSourceName); return 0; }
11953
12018
  // Skipped (a newer read began): the cursor stays; this runs again after that read
11954
- if (await landRows(dataSourceName, page.rows, { mode: 'append', generation, readToken: read, order: state.order || undefined }) === false) {
12019
+ if (await landRows(dataSourceName, page.rows, { mode: 'append', generation, readToken: read, order: state.order || undefined, ...(page.team !== undefined && { appendTeam: page.team }) }) === false) {
11955
12020
  if (sourceGeneration(dataSourceName) === generation) requeueMore(dataSourceName);
11956
12021
  return 0;
11957
12022
  }
@@ -12357,7 +12422,8 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12357
12422
  const staleLocaleHit = locale !== live && !!(cachedData && cachedData._locale);
12358
12423
  if (!isInitializing && !staleLocaleHit) {
12359
12424
  // Landing (coalesced): resolves once the cached rows are visible
12360
- await landRows(dataSourceName, cachedData, { mode: 'replace', loading: false, error: null, ready: true, fresh: true });
12425
+ const cachedTeam = cachedData && typeof cachedData === 'object' && 'scopeTeam' in cachedData ? { scopeTeam: cachedData.scopeTeam } : {};
12426
+ await landRows(dataSourceName, cachedData, { mode: 'replace', loading: false, error: null, ready: true, fresh: true, ...cachedTeam });
12361
12427
  }
12362
12428
  return cachedData;
12363
12429
  }
@@ -12413,6 +12479,12 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12413
12479
  const generation = sourceGeneration ? sourceGeneration(dataSourceName) : 0;
12414
12480
  const load = { identity: confirmedIdentity(), bound: undefined, abandoned: false, replacement: null };
12415
12481
  loadIdentities.set(cacheKey, load);
12482
+ // Team listener waits while this read builds; its landing records the team the build used
12483
+ const teamRead = window.ManifestDataStore.beginTeamRead?.(dataSourceName) || { building() {}, built() {}, end() {} };
12484
+ let builtTeam;
12485
+ // team: what the scope build used (undefined: nothing sent)
12486
+ const noteTeam = (team) => { builtTeam = team; teamRead.built(team); };
12487
+ const teamLanding = () => (builtTeam === undefined ? {} : { scopeTeam: builtTeam });
12416
12488
  const superseded = () => load.abandoned || (sourceGeneration && sourceGeneration(dataSourceName) !== generation);
12417
12489
 
12418
12490
  // Unresolvable scope (signed out, or teamless): settle empty, not $loading forever; auth events reload.
@@ -12425,6 +12497,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12425
12497
  const state = Alpine.store('data')?.[`_${dataSourceName}_state`];
12426
12498
  if (state?.ready || superseded() || !authSettledSignedOut()) return;
12427
12499
  updateStore(dataSourceName, [], { loading: false, error: null, ready: true });
12500
+ window.ManifestDataStore.clearLoadTeam?.(dataSourceName);
12428
12501
  }, wait + 10);
12429
12502
  return false;
12430
12503
  }
@@ -12435,6 +12508,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12435
12508
  return true;
12436
12509
  }
12437
12510
  updateStore(dataSourceName, [], { loading: false, error: null, ready: true });
12511
+ window.ManifestDataStore.clearLoadTeam?.(dataSourceName);
12438
12512
  return true;
12439
12513
  };
12440
12514
 
@@ -12517,13 +12591,16 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12517
12591
  const defaults = queriesConfig ? (queriesConfig.default || queriesConfig) : [];
12518
12592
  const paged = spec ? await fetchPagedRows(dataSourceName, defaults, {
12519
12593
  want: pagedWant(dataSourceName, spec),
12520
- isCurrent: () => !superseded() && window.ManifestDataStore.isLatestRead(dataSourceName, readToken)
12594
+ isCurrent: () => !superseded() && window.ManifestDataStore.isLatestRead(dataSourceName, readToken),
12595
+ onTeam: noteTeam
12521
12596
  }) : undefined;
12522
12597
  if (paged) pagedResult = { ...paged, spec, filters: defaults };
12523
12598
  const queries = spec
12524
12599
  ? (paged ? [] : null)
12525
12600
  : await window.ManifestDataQueries.buildAppwriteQueries(defaults, scope, scopeColumns);
12526
12601
 
12602
+ // Paged: onTeam already noted the build (or nothing was sent)
12603
+ if (!spec) noteTeam(queries?.scopeTeam); else if (!paged) noteTeam(undefined);
12527
12604
  // Not ready (auth/scope unresolved): skip this read, retry on an auth event
12528
12605
  if (queries === null) {
12529
12606
  scheduleAuthRetry(dataSourceName, locale);
@@ -12584,6 +12661,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12584
12661
 
12585
12662
  // Not ready (a $auth. arg in queriesConfig unresolved): skip, retry on an auth event
12586
12663
  if (queries === null) {
12664
+ noteTeam();
12587
12665
  scheduleAuthRetry(dataSourceName, locale);
12588
12666
  if (settleUnresolved(manifest)) landed = true;
12589
12667
  return null;
@@ -12599,10 +12677,10 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12599
12677
 
12600
12678
  // Filter files by scope if scope is defined (client-side filtering)
12601
12679
  // This matches the database team scope behavior
12602
- if (scope && files && Array.isArray(files) && files.length > 0) {
12603
- const originalCount = files.length;
12680
+ if (scope) {
12604
12681
  files = await filterFilesByScope(files, scope);
12605
- }
12682
+ noteTeam(files.scopeTeam);
12683
+ } else noteTeam();
12606
12684
 
12607
12685
  data = files;
12608
12686
 
@@ -12753,7 +12831,8 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12753
12831
  return enhancedData;
12754
12832
  }
12755
12833
 
12756
- // Cache is always safe — the key carries this load's locale.
12834
+ // Cache is always safe — the key carries this load's locale (and the team it was built for)
12835
+ if (builtTeam !== undefined && enhancedData && typeof enhancedData === 'object') window.ManifestDataQueries?.tagTeam?.(enhancedData, builtTeam);
12757
12836
  dataSourceCache.set(cacheKey, enhancedData);
12758
12837
 
12759
12838
  // Stale-locale guard: if the locale changed mid-load, a localized
@@ -12771,7 +12850,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12771
12850
  landed = true;
12772
12851
  clearActiveQuery(dataSourceName, Array.isArray(enhancedData) ? enhancedData.length : 0);
12773
12852
  if (pagedResult) setPagingState(dataSourceName, pagedResult, { filters: pagedResult.filters });
12774
- await landRows(dataSourceName, enhancedData, { mode: 'replace', loading: false, error: null, ready: true, fresh: true, generation, readToken });
12853
+ await landRows(dataSourceName, enhancedData, { mode: 'replace', loading: false, error: null, ready: true, fresh: true, generation, readToken, ...teamLanding() });
12775
12854
  }
12776
12855
 
12777
12856
  // Return unsealed version for our proxy system
@@ -12794,6 +12873,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12794
12873
  ready: false,
12795
12874
  errorTime: Date.now() // Track when error occurred
12796
12875
  });
12876
+ window.ManifestDataStore.clearLoadTeam?.(dataSourceName);
12797
12877
  }
12798
12878
  }
12799
12879
 
@@ -12812,7 +12892,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12812
12892
  if (!landed && keepRows && !isInitializing && !superseded()) setSourceState(dataSourceName, { loading: false });
12813
12893
  }
12814
12894
  });
12815
- const done = () => { settled(); deferredLoads.delete(cacheKey); if (loadIdentities.get(cacheKey) === load) loadIdentities.delete(cacheKey); };
12895
+ const done = () => { teamRead.end(); settled(); deferredLoads.delete(cacheKey); if (loadIdentities.get(cacheKey) === load) loadIdentities.delete(cacheKey); };
12816
12896
  run.then(done, done);
12817
12897
  const result = followReplacement(load, run);
12818
12898
  if (replaced) replaced.replacement = result;
@@ -13005,6 +13085,7 @@ async function initializeDataSourcesPlugin() {
13005
13085
  _loadDataSource: reloadDataSource, // Internal: every user is a reload-after-mutation
13006
13086
  filterFilesByScope, // Export for use by getFilesForEntry
13007
13087
  requiresIdentity,
13088
+ cancelAuthRetry,
13008
13089
  setActiveQuery,
13009
13090
  forgetLiveSource,
13010
13091
  reloadSource,