mnfst 0.5.275 → 0.5.276

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.275';
5
+ const MANIFEST_BUILD_VERSION = '0.5.276';
6
6
 
7
7
  /* Manifest Data Sources - Appwrite Integration */
8
8
 
@@ -195,6 +195,17 @@ async function loadTableRows(databaseId, tableId, queries = [], { requireAuth =
195
195
  }
196
196
  }
197
197
 
198
+ // One page of a table with Appwrite's count: { rows, total }
199
+ async function loadTablePage(databaseId, tableId, queries = [], { requireAuth = true } = {}) {
200
+ const services = await getAppwriteDataServices();
201
+ if (!services?.tablesDB) {
202
+ throw new Error('[Manifest Data] Appwrite TablesDB service not available');
203
+ }
204
+ if (requireAuth) await verifyAuthenticated();
205
+ const response = await services.tablesDB.listRows({ databaseId, tableId, queries });
206
+ return { rows: response.rows || [], total: typeof response.total === 'number' ? response.total : null };
207
+ }
208
+
198
209
  // Get a single row from Appwrite table
199
210
  async function getTableRow(databaseId, tableId, rowId) {
200
211
  const services = await getAppwriteDataServices();
@@ -679,6 +690,7 @@ async function getFilePreview(bucketId, fileId, widthOrOptions = null, height =
679
690
  window.ManifestDataAppwrite = {
680
691
  getAppwriteDataServices,
681
692
  loadTableRows,
693
+ loadTablePage,
682
694
  getTableRow,
683
695
  createRow,
684
696
  updateRow,
@@ -1642,6 +1654,8 @@ window.ManifestDataQueries = {
1642
1654
 
1643
1655
  /* Manifest Data Sources - Pagination (Appwrite) */
1644
1656
 
1657
+ const PAGE_LIMIT = 4999;
1658
+
1645
1659
  // Resolve the source's table or bucket
1646
1660
  async function resolvePagedSource(dataSourceName) {
1647
1661
  const manifest = await window.ManifestDataConfig.ensureManifest();
@@ -1686,6 +1700,7 @@ async function fetchPage(dataSourceName, baseQueries, pageQueries, limit) {
1686
1700
 
1687
1701
  // First page, cursor-based. Returns { items, cursor, total, hasMore }
1688
1702
  async function getFirstPage(dataSourceName, limit, baseQueries = []) {
1703
+ limit = Math.min(limit, PAGE_LIMIT); // the extra row must fit Appwrite's 5000
1689
1704
  const { rows, total, extra } = await fetchPage(dataSourceName, baseQueries, [], limit);
1690
1705
  const items = rows.slice(0, limit);
1691
1706
  return { items, cursor: items.length ? items[items.length - 1].$id : null, total, hasMore: extra };
@@ -1693,6 +1708,7 @@ async function getFirstPage(dataSourceName, limit, baseQueries = []) {
1693
1708
 
1694
1709
  // Next page after a cursor. Returns { items, cursor, total, hasMore }
1695
1710
  async function getNextPage(dataSourceName, cursor, limit, baseQueries = []) {
1711
+ limit = Math.min(limit, PAGE_LIMIT); // the extra row must fit Appwrite's 5000
1696
1712
  if (!cursor) {
1697
1713
  throw new Error('[Manifest Data] Cursor is required for next page');
1698
1714
  }
@@ -1703,6 +1719,7 @@ async function getNextPage(dataSourceName, cursor, limit, baseQueries = []) {
1703
1719
 
1704
1720
  // Previous page before a cursor. hasMore: rows exist before this page. Returns { items, cursor, total, hasMore }
1705
1721
  async function getPrevPage(dataSourceName, cursor, limit, baseQueries = []) {
1722
+ limit = Math.min(limit, PAGE_LIMIT); // the extra row must fit Appwrite's 5000
1706
1723
  if (!cursor) {
1707
1724
  throw new Error('[Manifest Data] Cursor is required for previous page');
1708
1725
  }
@@ -1714,6 +1731,7 @@ async function getPrevPage(dataSourceName, cursor, limit, baseQueries = []) {
1714
1731
 
1715
1732
  // Specific page (1-based), offset-based. Returns { items, page, total, totalPages, hasMore }
1716
1733
  async function getPage(dataSourceName, pageNumber, limit, baseQueries = []) {
1734
+ limit = Math.min(limit, PAGE_LIMIT); // the extra row must fit Appwrite's 5000
1717
1735
  if (!pageNumber || pageNumber < 1) {
1718
1736
  throw new Error('[Manifest Data] Page number must be >= 1');
1719
1737
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  (function () {
4
4
 
5
- const MANIFEST_BUILD_VERSION = '0.5.275';
5
+ const MANIFEST_BUILD_VERSION = '0.5.276';
6
6
 
7
7
  /* Manifest Data Sources - Configuration */
8
8
 
@@ -433,7 +433,9 @@ function sourceGeneration(dataSourceName) {
433
433
  function resetSource(dataSourceName) {
434
434
  sourceGen.set(dataSourceName, sourceGeneration(dataSourceName) + 1);
435
435
  latestRead.delete(dataSourceName);
436
+ inflightReads.delete(dataSourceName);
436
437
  window.ManifestDataMain?.forgetLiveSource?.(dataSourceName);
438
+ pendingWrites.delete(dataSourceName); // a new identity never sees the old one's unsettled writes
437
439
  const prefix = `${dataSourceName}:`;
438
440
  for (const key of [...dataSourceCache.keys()]) if (key.startsWith(prefix)) dataSourceCache.delete(key);
439
441
  for (const key of [...loadingPromises.keys()]) if (key.startsWith(prefix)) loadingPromises.delete(key);
@@ -471,11 +473,153 @@ function setSourceState(dataSourceName, patch) {
471
473
  return next;
472
474
  }
473
475
 
476
+ // Optimistic writes, re-applied over network landings: unsettled ones over every
477
+ // landing; settled ones only over reads issued before they settled (so data fetched
478
+ // before the write never shows the old values), until a newer read lands
479
+ const pendingWrites = new Map(); // source -> Map<$id, Array<{ token, kind, fields, snapshot, settledAt, settledTime }>>
480
+ let pendingSeq = 0;
481
+ const SETTLED_HOLD_MS = 30000;
482
+
483
+ function holdWrite(dataSourceName, id, kind, fields, snapshot = null) {
484
+ if (id === null || id === undefined) return null;
485
+ let byId = pendingWrites.get(dataSourceName);
486
+ if (!byId) pendingWrites.set(dataSourceName, byId = new Map());
487
+ const token = ++pendingSeq;
488
+ const list = byId.get(id) || [];
489
+ list.push({ token, kind, fields, snapshot, settledAt: null, settledTime: 0 });
490
+ byId.set(id, list);
491
+ touchPending(dataSourceName);
492
+ return token;
493
+ }
494
+
495
+ function dropWrite(dataSourceName, id, token) {
496
+ const byId = pendingWrites.get(dataSourceName);
497
+ const list = byId?.get(id);
498
+ if (!list) return null;
499
+ const entry = list.find(w => w.token === token) || null;
500
+ const next = list.filter(w => w.token !== token);
501
+ if (next.length) byId.set(id, next); else byId.delete(id);
502
+ if (!byId.size) pendingWrites.delete(dataSourceName);
503
+ return entry;
504
+ }
505
+
506
+ // Failed: forget it (the caller rolls back). Returns the entry
507
+ function releaseWrite(dataSourceName, id, token) {
508
+ const entry = dropWrite(dataSourceName, id, token);
509
+ touchPending(dataSourceName);
510
+ return entry;
511
+ }
512
+
513
+ // Confirmed: keep it over reads issued before now, under the server's id and values
514
+ function settleWrite(dataSourceName, id, token, { id: newId = id, fields } = {}) {
515
+ const entry = dropWrite(dataSourceName, id, token);
516
+ if (entry) {
517
+ entry.settledAt = readSeq;
518
+ entry.settledTime = Date.now();
519
+ if (fields) entry.fields = fields;
520
+ let byId = pendingWrites.get(dataSourceName);
521
+ if (!byId) pendingWrites.set(dataSourceName, byId = new Map());
522
+ byId.set(newId, [...(byId.get(newId) || []), entry]);
523
+ }
524
+ touchPending(dataSourceName);
525
+ }
526
+
527
+ function pendingWritesFor(dataSourceName, id) {
528
+ return (pendingWrites.get(dataSourceName)?.get(id) || []).filter(w => w.settledAt === null);
529
+ }
530
+
531
+ function isSaving(dataSourceName, id) {
532
+ return pendingWritesFor(dataSourceName, id).length > 0;
533
+ }
534
+
535
+ function pendingCount(dataSourceName) {
536
+ const byId = pendingWrites.get(dataSourceName);
537
+ if (!byId) return 0;
538
+ let n = 0;
539
+ for (const list of byId.values()) if (list.some(w => w.settledAt === null)) n++;
540
+ return n;
541
+ }
542
+
543
+ // $saving / $pending read this; bumps keep them reactive
544
+ function touchPending(dataSourceName) {
545
+ const store = typeof Alpine !== 'undefined' ? Alpine.store('data') : null;
546
+ if (!store) return;
547
+ const key = `_${dataSourceName}_state`;
548
+ const current = store[key] || { loading: false, error: null, ready: false, stale: true };
549
+ const pending = pendingCount(dataSourceName);
550
+ if (current.pending !== pending) store[key] = { ...current, pending };
551
+ }
552
+
553
+ // Local row insert: at its sort position on a sorted source, else at the end
554
+ function insertRow(store, dataSourceName, row) {
555
+ const target = store[dataSourceName];
556
+ const order = window.ManifestDataMain?.orderFor?.(dataSourceName);
557
+ if (!order) { target.push(row); return; }
558
+ target.splice(sortedIndex(rawOf(store)[dataSourceName], rawOf(row), compareBy(order)), 0, row);
559
+ }
560
+
561
+ // After a landing: held writes win over the landed payload. reads: this flush's read
562
+ // landings for the source, { token, ids } (ids null: a replace covering every row)
563
+ function reapplyPending(store, dataSourceName, readLandings = []) {
564
+ const byId = pendingWrites.get(dataSourceName);
565
+ if (!byId) return false;
566
+ const curRaw = rawOf(store)[dataSourceName];
567
+ if (!Array.isArray(curRaw)) return false;
568
+ const now = Date.now();
569
+ let changed = false;
570
+ for (const [id, list] of [...byId]) {
571
+ let i = curRaw.findIndex(row => rowKey(row) === id);
572
+ // Only reads that carried this row (a replace carries every row) speak for it
573
+ const reads = readLandings.filter(r => r.ids === null || r.ids.has(id)).map(r => r.token);
574
+ for (const write of [...list]) {
575
+ if (write.settledAt !== null) {
576
+ // Settled: a read issued since reflects it (or time ran out) — let go
577
+ if (reads.some(t => t > write.settledAt) || now - write.settledTime > SETTLED_HOLD_MS) {
578
+ dropWrite(dataSourceName, id, write.token);
579
+ continue;
580
+ }
581
+ if (!reads.some(t => t <= write.settledAt)) continue; // realtime is newer than the write
582
+ }
583
+ if (write.kind === 'delete') {
584
+ if (i !== -1) { store[dataSourceName].splice(i, 1); i = -1; changed = true; }
585
+ } else if (write.kind === 'create') {
586
+ // A placeholder stays only where it belongs (a $query that excludes it drops it)
587
+ if (i === -1 && (window.ManifestDataMain?.rowFitsSource?.(dataSourceName, write.fields) ?? true)) {
588
+ insertRow(store, dataSourceName, createReactiveReferences(write.fields, dataSourceName));
589
+ i = curRaw.findIndex(row => rowKey(row) === id);
590
+ changed = true;
591
+ }
592
+ } else if (i !== -1) {
593
+ const row = curRaw[i];
594
+ if (Object.keys(write.fields).some(k => !sameScalarOrList(row[k], write.fields[k]))) {
595
+ mergeRowFields(store[dataSourceName][i], write.fields, dataSourceName);
596
+ changed = true;
597
+ }
598
+ }
599
+ }
600
+ }
601
+ return changed;
602
+ }
603
+
474
604
  // Last-issued read per source: a slower earlier read ($query or load) never lands over a later one
475
605
  const latestRead = new Map();
476
606
  let readSeq = 0;
477
607
  const loadReadTokens = new Map(); // source:locale → token of the load in flight under that key
478
- function beginRead(dataSourceName) { const token = ++readSeq; latestRead.set(dataSourceName, token); return token; }
608
+ const inflightReads = new Map(); // source → Set of read tokens not yet settled
609
+ function beginRead(dataSourceName) {
610
+ const token = ++readSeq;
611
+ latestRead.set(dataSourceName, token);
612
+ let set = inflightReads.get(dataSourceName);
613
+ if (!set) inflightReads.set(dataSourceName, set = new Set());
614
+ set.add(token);
615
+ return token;
616
+ }
617
+ function endRead(dataSourceName, token) {
618
+ const set = inflightReads.get(dataSourceName);
619
+ if (set) { set.delete(token); if (!set.size) inflightReads.delete(dataSourceName); }
620
+ }
621
+ function readsInFlight(dataSourceName) { return inflightReads.has(dataSourceName); }
622
+ function currentRead(dataSourceName) { return latestRead.get(dataSourceName); }
479
623
  function adoptRead(dataSourceName, token) { if (token !== undefined) latestRead.set(dataSourceName, token); }
480
624
  // A reset clears the record: generation stamps already drop the older reads
481
625
  function isLatestRead(dataSourceName, token) { return token === undefined || !latestRead.has(dataSourceName) || latestRead.get(dataSourceName) === token; }
@@ -645,7 +789,12 @@ function writeSource(dataSourceName, data, options = {}) {
645
789
  ready: options.ready !== undefined ? options.ready : (data !== null && data !== undefined),
646
790
  errorTime: options.error !== undefined && options.error !== null ? Date.now() : (currentState.errorTime || null),
647
791
  stale: fresh ? false : currentState.stale !== false,
648
- realtimeOverflow: currentState.realtimeOverflow || 0 // set via setSourceState (realtime caps)
792
+ realtimeOverflow: currentState.realtimeOverflow || 0, // set via setSourceState (realtime caps)
793
+ // paged sources (set via setSourceState)
794
+ hasMore: currentState.hasMore || false,
795
+ total: currentState.total ?? null,
796
+ totalCapped: currentState.totalCapped || false,
797
+ pending: currentState.pending || 0
649
798
  };
650
799
  store[`_${dataSourceName}_state`] = newState;
651
800
  if (fresh) markFresh(dataSourceName);
@@ -747,6 +896,12 @@ function flushLandings() {
747
896
  console.error(`[Manifest Data] Landing failed for "${op.source}":`, error);
748
897
  }
749
898
  }
899
+ for (const source of [...touched]) {
900
+ const reads = ops
901
+ .filter(op => op.source === source && typeof op.options?.readToken === 'number' && Array.isArray(op.rows))
902
+ .map(op => ({ token: op.options.readToken, ids: op.options.mode === 'append' ? new Set(op.rows.map(rowKey)) : null }));
903
+ reapplyPending(store, source, reads);
904
+ }
750
905
  for (const [source, byId] of local) {
751
906
  for (const [id, note] of byId) {
752
907
  if (note.removed) {
@@ -1598,8 +1753,20 @@ window.ManifestDataStore = {
1598
1753
  // Stale-first + dedupe (§11.1)
1599
1754
  setSourceState,
1600
1755
  runDeduped,
1756
+ insertRow,
1757
+ holdWrite,
1758
+ releaseWrite,
1759
+ settleWrite,
1760
+ isSaving,
1761
+ pendingWritesFor,
1762
+ pendingCount,
1763
+ sameScalarOrList,
1601
1764
  beginRead,
1765
+ endRead,
1766
+ readsInFlight,
1602
1767
  adoptRead,
1768
+ currentRead,
1769
+ compareBy,
1603
1770
  loadReadTokens,
1604
1771
  isLatestRead,
1605
1772
  sourceFreshness,
@@ -3069,8 +3236,8 @@ function addEntryToStore(dataSourceName, entry, options = {}) {
3069
3236
  return false;
3070
3237
  }
3071
3238
 
3072
- // Local write: push onto the tracked array, sync
3073
- target.push(ds.createReactiveReferences(entry, dataSourceName));
3239
+ // Local write: into the tracked array (its sort position on a sorted source), sync
3240
+ ds.insertRow(Alpine.store('data'), dataSourceName, ds.createReactiveReferences(entry, dataSourceName));
3074
3241
  ds.noteLocalWrite(dataSourceName, entry?.$id, { patch: entry });
3075
3242
  ds.touchSource(dataSourceName);
3076
3243
  clearSourceCaches(dataSourceName);
@@ -3123,6 +3290,30 @@ function removeEntryFromStore(dataSourceName, entryId, options = {}) {
3123
3290
  return { originalEntry };
3124
3291
  }
3125
3292
 
3293
+ function cloneValue(value) {
3294
+ if (value === null || typeof value !== 'object') return value;
3295
+ try { return JSON.parse(JSON.stringify(value)); } catch { return value; }
3296
+ }
3297
+
3298
+ function sameValue(a, b) {
3299
+ if (a === b) return true;
3300
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
3301
+ try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; }
3302
+ }
3303
+
3304
+ // Re-insert a row at its old index (a failed delete); never duplicates one already back
3305
+ function insertEntryAt(dataSourceName, entry, index, options = {}) {
3306
+ if (window.ManifestDataStore?.isStaleWrite?.(dataSourceName, options)) return false;
3307
+ const { store, arr, index: existing } = findRawIndex(dataSourceName, entry?.$id);
3308
+ if (!store || !arr || existing !== -1) return false;
3309
+ const ds = window.ManifestDataStore;
3310
+ const at = index >= 0 && index <= arr.length ? index : arr.length;
3311
+ store[dataSourceName].splice(at, 0, ds.createReactiveReferences(entry, dataSourceName));
3312
+ ds.touchSource(dataSourceName);
3313
+ clearSourceCaches(dataSourceName);
3314
+ return true;
3315
+ }
3316
+
3126
3317
  // Rollback a mutation
3127
3318
  function rollbackMutation(mutationId) {
3128
3319
  const mutation = pendingMutations.get(mutationId);
@@ -3175,6 +3366,9 @@ async function executeMutation(mutationConfig) {
3175
3366
  let originalData = null;
3176
3367
  let optimisticData = null;
3177
3368
  let resolvedEntryId = entryId;
3369
+ let held = null; // pending-write token: re-applied over landings until settled
3370
+ let deletedAt = -1; // a failed delete returns the row to its place
3371
+ const ds0 = window.ManifestDataStore;
3178
3372
 
3179
3373
  // Get helper functions from store
3180
3374
  const {
@@ -3200,13 +3394,15 @@ async function executeMutation(mutationConfig) {
3200
3394
  }
3201
3395
 
3202
3396
  addEntryToStore(dataSourceName, optimisticData, options);
3397
+ held = ds0?.holdWrite?.(dataSourceName, tempId, 'create', optimisticData);
3203
3398
  originalData = null; // Nothing to rollback for create
3204
3399
  } else if (type === 'update') {
3205
3400
  // Snapshot for rollback (the row itself is mutated in place)
3206
3401
  const store = Alpine.store('data');
3402
+ // Snapshot only the patched fields: rollback restores those, nothing else
3207
3403
  if (store && store[dataSourceName] && Array.isArray(store[dataSourceName])) {
3208
3404
  const found = store[dataSourceName].find(e => e.$id === entryId);
3209
- originalData = found ? { ...found } : null;
3405
+ originalData = found && data ? Object.fromEntries(Object.keys(data).map(k => [k, cloneValue(found[k])])) : null;
3210
3406
  }
3211
3407
 
3212
3408
  // Set updating state
@@ -3219,11 +3415,13 @@ async function executeMutation(mutationConfig) {
3219
3415
  if (originalData) {
3220
3416
  updateEntryInStore(dataSourceName, entryId, data, options);
3221
3417
  }
3418
+ held = ds0?.holdWrite?.(dataSourceName, entryId, 'update', { ...data }, originalData ? { ...originalData } : null);
3222
3419
  } else if (type === 'delete') {
3223
3420
  // Snapshot for rollback
3224
3421
  const store = Alpine.store('data');
3225
3422
  if (store && store[dataSourceName] && Array.isArray(store[dataSourceName])) {
3226
- const found = store[dataSourceName].find(e => e.$id === entryId);
3423
+ deletedAt = findRawIndex(dataSourceName, entryId).index;
3424
+ const found = deletedAt !== -1 ? store[dataSourceName][deletedAt] : null;
3227
3425
  originalData = found ? { ...found } : null;
3228
3426
  }
3229
3427
 
@@ -3237,10 +3435,19 @@ async function executeMutation(mutationConfig) {
3237
3435
  if (originalData) {
3238
3436
  removeEntryFromStore(dataSourceName, entryId, options);
3239
3437
  }
3438
+ held = ds0?.holdWrite?.(dataSourceName, entryId, 'delete', null);
3240
3439
  }
3241
3440
 
3242
3441
  // Step 2: Perform API call
3243
3442
  const result = await apiCall();
3443
+ if (held) {
3444
+ // Confirmed: still held over reads issued before now, under the server's id and values
3445
+ if (type === 'create' && result?.$id) ds0.settleWrite(dataSourceName, resolvedEntryId, held, { id: result.$id, fields: result });
3446
+ else if (type === 'update') ds0.settleWrite(dataSourceName, resolvedEntryId, held, result?.$id ? { fields: Object.fromEntries(Object.keys(data || {}).map(k => [k, result[k]])) } : {});
3447
+ else if (type === 'delete') ds0.settleWrite(dataSourceName, resolvedEntryId, held);
3448
+ else ds0.releaseWrite(dataSourceName, resolvedEntryId, held);
3449
+ }
3450
+ held = null;
3244
3451
 
3245
3452
  // Step 3: Clear loading states after successful API call (regardless of result format)
3246
3453
  if (type === 'create' && clearCreatingEntry && resolvedEntryId) {
@@ -3307,6 +3514,10 @@ async function executeMutation(mutationConfig) {
3307
3514
  clearDeletingEntry(dataSourceName, entryId);
3308
3515
  }
3309
3516
 
3517
+ const mine = held ? ds0.releaseWrite(dataSourceName, resolvedEntryId, held) : null;
3518
+ const heldToken = held;
3519
+ held = null;
3520
+
3310
3521
  // Rollback on error
3311
3522
  console.error(`[Manifest Data] Mutation failed, rolling back:`, error);
3312
3523
 
@@ -3314,9 +3525,26 @@ async function executeMutation(mutationConfig) {
3314
3525
  if (type === 'create' && optimisticData) {
3315
3526
  removeEntryFromStore(dataSourceName, optimisticData.$id, writeOptions);
3316
3527
  } else if (type === 'update' && originalData) {
3317
- updateEntryInStore(dataSourceName, entryId, originalData, writeOptions);
3528
+ // Field-level: a field restores only if it still shows this write's value (a live
3529
+ // change meanwhile wins). A later unsettled write on the same field takes over
3530
+ // this write's snapshot instead, so the chain unwinds to the value before all of them
3531
+ const snapshot = mine?.snapshot || originalData;
3532
+ const { arr, index } = findRawIndex(dataSourceName, entryId);
3533
+ const row = index !== -1 ? arr[index] : null;
3534
+ const others = ds0?.pendingWritesFor?.(dataSourceName, entryId) || [];
3535
+ const restore = {};
3536
+ for (const key of Object.keys(snapshot)) {
3537
+ const later = others.find(w => w.kind === 'update' && w.token > heldToken && w.fields && key in w.fields);
3538
+ if (later) {
3539
+ if (later.snapshot) later.snapshot[key] = snapshot[key];
3540
+ continue;
3541
+ }
3542
+ if (!row || !sameValue(row[key], data[key])) continue;
3543
+ restore[key] = snapshot[key];
3544
+ }
3545
+ if (Object.keys(restore).length) updateEntryInStore(dataSourceName, entryId, restore, writeOptions);
3318
3546
  } else if (type === 'delete' && originalData) {
3319
- addEntryToStore(dataSourceName, originalData, writeOptions);
3547
+ insertEntryAt(dataSourceName, originalData, deletedAt, writeOptions);
3320
3548
  }
3321
3549
  };
3322
3550
 
@@ -4324,6 +4552,27 @@ function attachArrayMethods(array, dataSourceName, reloadDataSource) {
4324
4552
  }
4325
4553
  });
4326
4554
 
4555
+ // Paged sources: next page, and the paging state
4556
+ for (const prop of ['$hasMore', '$total', '$totalCapped', '$pending']) {
4557
+ Object.defineProperty(array, prop, {
4558
+ enumerable: false,
4559
+ configurable: true,
4560
+ get: () => window.ManifestDataProxiesMagic?.getStateProperty?.(prop, dataSourceName)
4561
+ });
4562
+ }
4563
+ Object.defineProperty(array, '$more', {
4564
+ enumerable: false,
4565
+ configurable: true,
4566
+ writable: false,
4567
+ value: () => window.ManifestDataMain.loadMore(dataSourceName)
4568
+ });
4569
+ Object.defineProperty(array, '$saving', {
4570
+ enumerable: false,
4571
+ configurable: true,
4572
+ writable: false,
4573
+ value: (id) => window.ManifestDataProxiesMagic.createSavingMethod(dataSourceName)(id)
4574
+ });
4575
+
4327
4576
  // Attach $search method for client-side text filtering
4328
4577
  Object.defineProperty(array, '$search', {
4329
4578
  enumerable: false,
@@ -4971,7 +5220,7 @@ function createArrayProxyWithRoute(arrayTarget, dataSourceName = null, reloadDat
4971
5220
  }
4972
5221
 
4973
5222
  // Handle state properties ($loading, $error, $ready, $stale, $fresh, $realtimeOverflow)
4974
- if (key === '$stale' || key === '$fresh' || key === '$realtimeOverflow') {
5223
+ if (key === '$stale' || key === '$fresh' || key === '$realtimeOverflow' || key === '$hasMore' || key === '$total' || key === '$totalCapped' || key === '$pending') {
4975
5224
  return window.ManifestDataProxiesMagic?.getStateProperty?.(key, dataSourceName);
4976
5225
  }
4977
5226
  if (key === '$loading' || key === '$error' || key === '$ready') {
@@ -4995,6 +5244,13 @@ function createArrayProxyWithRoute(arrayTarget, dataSourceName = null, reloadDat
4995
5244
  }
4996
5245
  }
4997
5246
 
5247
+ if (key === '$more') {
5248
+ return () => window.ManifestDataMain.loadMore(dataSourceName);
5249
+ }
5250
+ if (key === '$saving') {
5251
+ return window.ManifestDataProxiesMagic.createSavingMethod(dataSourceName);
5252
+ }
5253
+
4998
5254
  // Handle pagination methods
4999
5255
  if (key === '$first' || key === '$next' || key === '$prev' || key === '$page') {
5000
5256
  return (...args) => window.ManifestDataProxiesMagic.createPaginationMethod(key, dataSourceName)(...args);
@@ -8088,19 +8344,34 @@ function createAppwriteMethodsHandler(dataSourceName, reloadDataSource) {
8088
8344
  const { runDeduped, landRows, sourceGeneration, isLatestRead } = window.ManifestDataStore || {};
8089
8345
  const generation = sourceGeneration?.(dataSourceName);
8090
8346
  const requireAuth = window.ManifestDataMain?.requiresIdentity?.({ ...dataSource, queries: [dataSource.queries, queries] }) ?? true;
8091
- const run = () => window.ManifestDataAppwrite.loadTableRows(
8092
- appwriteConfig.databaseId,
8093
- tableId,
8094
- appwriteQueries,
8095
- { requireAuth }
8096
- );
8097
- const result = runDeduped ? await runDeduped(key, run) : await run();
8347
+ // Paged sources: the new filter set starts again at its first window (or walks all)
8348
+ const main = window.ManifestDataMain;
8349
+ const spec = main?.pagingSpec?.(dataSource);
8350
+ const want = spec ? main.pagedWant(dataSourceName, spec) : 0;
8351
+ let paged = null;
8352
+ const run = spec
8353
+ ? async () => {
8354
+ paged = await main.fetchPagedRows(dataSourceName, queries || [], {
8355
+ want,
8356
+ isCurrent: () => !isLatestRead || isLatestRead(dataSourceName, readToken)
8357
+ });
8358
+ if (paged === null) throw new Error(`[Manifest Data] "${dataSourceName}" $query: auth not ready yet — retry after auth settles`);
8359
+ return paged.rows;
8360
+ }
8361
+ : () => window.ManifestDataAppwrite.loadTableRows(
8362
+ appwriteConfig.databaseId,
8363
+ tableId,
8364
+ appwriteQueries,
8365
+ { requireAuth }
8366
+ );
8367
+ const result = (runDeduped && !spec) ? await runDeduped(key, run) : await run();
8098
8368
  // Network landing: query result replaces the source (coalesced, identity-preserving);
8099
8369
  // only the last-issued read of this source lands
8100
8370
  const latest = !isLatestRead || isLatestRead(dataSourceName, readToken);
8101
8371
  if (result !== undefined && landRows && latest && sourceGeneration?.(dataSourceName) === generation) {
8102
8372
  window.ManifestDataMain?.setActiveQuery?.(dataSourceName, queries || [], Array.isArray(result) ? result.length : 0);
8103
- await landRows(dataSourceName, result, { mode: 'replace', fresh: true, generation });
8373
+ if (paged) main.setPagingState(dataSourceName, { ...paged, spec }, { filters: queries || [] });
8374
+ await landRows(dataSourceName, result, { mode: 'replace', fresh: true, generation, readToken });
8104
8375
  }
8105
8376
  return result;
8106
8377
  }
@@ -8864,6 +9135,8 @@ function createAppwriteMethodsHandler(dataSourceName, reloadDataSource) {
8864
9135
  setErrorState(error);
8865
9136
  // Re-throw so promise chain still works if caller wants to handle it
8866
9137
  throw error;
9138
+ } finally {
9139
+ if (readToken !== undefined) window.ManifestDataStore?.endRead?.(dataSourceName, readToken);
8867
9140
  }
8868
9141
  };
8869
9142
 
@@ -8891,12 +9164,15 @@ window.ManifestDataProxiesAppwrite.createAppwriteMethodsHandler = createAppwrite
8891
9164
  // $realtimeOverflow: realtime events not applied since the last load (bounded
8892
9165
  // growth caps); reset to 0 on each load.
8893
9166
 
8894
- const STATE_PROPS = ['$loading', '$error', '$ready', '$stale', '$fresh', '$realtimeOverflow'];
9167
+ // $hasMore / $total / $totalCapped: paged sources (`paging` option)
9168
+ // $pending: rows with an unsettled write; $saving(id): that row has one
9169
+ const STATE_PROPS = ['$loading', '$error', '$ready', '$stale', '$fresh', '$realtimeOverflow', '$hasMore', '$total', '$totalCapped', '$pending'];
8895
9170
 
8896
9171
  function defaultStateValue(prop) {
8897
9172
  if (prop === '$error') return null;
8898
9173
  if (prop === '$stale') return true;
8899
- if (prop === '$realtimeOverflow') return 0;
9174
+ if (prop === '$realtimeOverflow' || prop === '$pending') return 0;
9175
+ if (prop === '$total') return null;
8900
9176
  return false;
8901
9177
  }
8902
9178
 
@@ -8927,11 +9203,27 @@ function getStateProperty(prop, dataSourceName) {
8927
9203
  return state.stale !== false;
8928
9204
  } else if (prop === '$realtimeOverflow') {
8929
9205
  return state.realtimeOverflow || 0;
9206
+ } else if (prop === '$hasMore') {
9207
+ return state.hasMore || false;
9208
+ } else if (prop === '$total') {
9209
+ return state.total ?? null;
9210
+ } else if (prop === '$totalCapped') {
9211
+ return state.totalCapped || false;
9212
+ } else if (prop === '$pending') {
9213
+ return state.pending || 0;
8930
9214
  }
8931
9215
 
8932
9216
  return undefined;
8933
9217
  }
8934
9218
 
9219
+ // $saving(id): reactive on the source's pending count
9220
+ function createSavingMethod(dataSourceName) {
9221
+ return (id) => {
9222
+ void getStateProperty('$pending', dataSourceName);
9223
+ return !!window.ManifestDataStore?.isSaving?.(dataSourceName, id);
9224
+ };
9225
+ }
9226
+
8935
9227
  // State property handler for use in proxy get() traps
8936
9228
  function createStatePropertyHandler(dataSourceName) {
8937
9229
  return function (key) {
@@ -8949,6 +9241,7 @@ if (!window.ManifestDataProxiesMagic) {
8949
9241
  window.ManifestDataProxiesMagic.STATE_PROPS = STATE_PROPS;
8950
9242
  window.ManifestDataProxiesMagic.getStateProperty = getStateProperty;
8951
9243
  window.ManifestDataProxiesMagic.createStatePropertyHandler = createStatePropertyHandler;
9244
+ window.ManifestDataProxiesMagic.createSavingMethod = createSavingMethod;
8952
9245
 
8953
9246
 
8954
9247
  /* Manifest Data Sources - Magic Method $files Handler */
@@ -9361,6 +9654,12 @@ function createAppwriteLoadingProxy(dataSourceName, reloadDataSource) {
9361
9654
  if ((key === '$first' || key === '$next' || key === '$prev' || key === '$page') && createPaginationMethod) {
9362
9655
  return createPaginationMethod(key, dataSourceName);
9363
9656
  }
9657
+ if (key === '$more') {
9658
+ return () => window.ManifestDataMain.loadMore(dataSourceName);
9659
+ }
9660
+ if (key === '$saving') {
9661
+ return window.ManifestDataProxiesMagic.createSavingMethod(dataSourceName);
9662
+ }
9364
9663
 
9365
9664
  // Appwrite CRUD
9366
9665
  if (key === '$create' || key === '$update' || key === '$delete' || key === '$query' ||
@@ -9567,6 +9866,8 @@ function registerXMagicMethod(loadDataSource) {
9567
9866
  if (stateProps.includes(key)) {
9568
9867
  return window.ManifestDataProxiesMagic.getStateProperty(key, prop);
9569
9868
  }
9869
+ if (key === '$saving') return window.ManifestDataProxiesMagic.createSavingMethod(prop);
9870
+ if (key === '$more') return () => window.ManifestDataMain.loadMore(prop);
9570
9871
  return target[key];
9571
9872
  }
9572
9873
  }));
@@ -11899,6 +12200,12 @@ const realtimeMeta = new Map(); // Map<name, { mode, maxRows, appended: [], pend
11899
12200
 
11900
12201
  function configureRealtimeMeta(dataSourceName, config, initialCount, limitQuery) {
11901
12202
  const cfg = (config && typeof config === 'object') ? config : {};
12203
+ // Paged sources hold what was paged in; growth is bounded by the paging rule, not a cap
12204
+ if (pagingState.has(dataSourceName) && typeof cfg.maxRows !== 'number') {
12205
+ realtimeMeta.set(dataSourceName, { mode: 'append', maxRows: 0, appended: [], pending: 0 });
12206
+ window.ManifestDataStore.setSourceState(dataSourceName, { realtimeOverflow: 0 });
12207
+ return;
12208
+ }
11902
12209
  const mode = cfg.mode === 'window' ? 'window' : 'append';
11903
12210
  const fallback = Math.max(500, 2 * initialCount);
11904
12211
  let maxRows;
@@ -11963,12 +12270,199 @@ function clearActiveQuery(dataSourceName, rowCount) {
11963
12270
  rebindLive(dataSourceName);
11964
12271
  }
11965
12272
 
12273
+ // The manifest entry for a source, synchronously (the loader has it by the time rows exist)
12274
+ function sourceConfig(dataSourceName) {
12275
+ return (window.ManifestComponentsRegistry?.manifest || window.__manifestLoaded)?.data?.[dataSourceName] || null;
12276
+ }
12277
+
12278
+ // The sort a local row should follow: the active $query's order, else the defaults'
12279
+ function orderFor(dataSourceName) {
12280
+ const dataSource = sourceConfig(dataSourceName);
12281
+ return dataSource ? sortSpec(pagedFilters(dataSourceName, dataSource)) : null;
12282
+ }
12283
+
12284
+ // Would this row belong in the source's current read (active $query, else defaults)?
12285
+ // Used for local placeholders; unevaluable filters count as a match
12286
+ function rowFitsSource(dataSourceName, row) {
12287
+ const dataSource = sourceConfig(dataSourceName);
12288
+ if (!dataSource || typeof dataSource !== 'object') return true;
12289
+ const queriesConfig = window.ManifestDataConfig?.getQueries?.(dataSource);
12290
+ const defaults = queriesConfig ? (queriesConfig.default || queriesConfig) : [];
12291
+ return eventMatchesQueries(row, realtimeQueriesFor(dataSourceName, Array.isArray(defaults) ? defaults : []));
12292
+ }
12293
+
11966
12294
  // Source reset (identity/scope) or torn down: nothing of the old binding carries over
11967
12295
  function forgetLiveSource(dataSourceName) {
11968
12296
  activeQueries.delete(dataSourceName);
12297
+ pagingState.delete(dataSourceName);
12298
+ catchUpTargets.delete(dataSourceName);
11969
12299
  realtimeBinds.delete(dataSourceName);
11970
12300
  }
11971
12301
 
12302
+ // Paged sources: `paging: "all" | "window" | { mode, size, max }`
12303
+ // all: every page up to `max` rows; window: `size` rows, `$more()` appends the next page.
12304
+ // The cursor is the last row the server sent (never a local or moved row), with its
12305
+ // sort values as of that page: the boundary between loaded and not-yet-loaded rows.
12306
+ const PAGED_WINDOW_QUERIES = new Set(['limit', 'offset', 'cursorAfter', 'cursorBefore']);
12307
+ const COUNT_CEILING = 5000; // Appwrite's default count cap
12308
+ const PAGE_SIZE_CAP = 4999; // a page asks for one extra row; Appwrite's limit is 5000
12309
+ const pagingState = new Map(); // Map<name, { hasMore, total, loaded, cursor, boundary, order }>
12310
+ const catchUpTargets = new Map(); // Map<name, rows to keep on a catch-up refetch>
12311
+ const moreInFlight = new Map(); // Map<name, Promise> — one $more() per source at a time
12312
+ const moreQueued = new Set(); // $more() asked while a read was in flight: runs when it lands
12313
+
12314
+ function pagingSpec(dataSource) {
12315
+ const p = dataSource && typeof dataSource === 'object' ? dataSource.paging : null;
12316
+ const cfg = typeof p === 'string' ? { mode: p } : (p && typeof p === 'object' ? p : null);
12317
+ if (!cfg || (cfg.mode !== 'all' && cfg.mode !== 'window')) return null;
12318
+ const size = Number(cfg.size) > 0 ? Math.min(PAGE_SIZE_CAP, Math.floor(Number(cfg.size))) : 100;
12319
+ const max = Number(cfg.max) > 0 ? Math.floor(Number(cfg.max)) : 5000;
12320
+ return { mode: cfg.mode, size, max };
12321
+ }
12322
+
12323
+ function stripPageWindow(queries) {
12324
+ return (Array.isArray(queries) ? queries : []).filter(q => !(Array.isArray(q) && PAGED_WINDOW_QUERIES.has(q[0])));
12325
+ }
12326
+
12327
+ // The filters a paged source currently reads: the active $query, else its defaults
12328
+ function pagedFilters(dataSourceName, dataSource) {
12329
+ const queriesConfig = window.ManifestDataConfig.getQueries(dataSource);
12330
+ return activeQueries.get(dataSourceName) || (queriesConfig ? (queriesConfig.default || queriesConfig) : []);
12331
+ }
12332
+
12333
+ // Fetch pages of a table: `want` rows from `after` (a row $id), `size` per request, each
12334
+ // asking for one extra row so "more" is exact. isCurrent() false stops the walk.
12335
+ // Returns { rows, total, hasMore } or null when queries can't resolve yet (auth)
12336
+ async function fetchPagedRows(dataSourceName, filters, { want, after = null, isCurrent = () => true } = {}) {
12337
+ const manifest = await window.ManifestDataConfig.ensureManifest();
12338
+ const dataSource = manifest?.data?.[dataSourceName];
12339
+ const spec = pagingSpec(dataSource);
12340
+ const appwriteConfig = await window.ManifestDataConfig.getAppwriteConfig(dataSource);
12341
+ const tableId = window.ManifestDataConfig.getAppwriteTableId(dataSource);
12342
+ if (!spec || !appwriteConfig || !tableId) throw new Error(`[Manifest Data] "${dataSourceName}" is not a paged table source`);
12343
+ const scope = window.ManifestDataConfig.getScope(dataSource);
12344
+ const scopeColumns = window.ManifestDataConfig.getScopeColumns(dataSource);
12345
+ const base = await window.ManifestDataQueries.buildAppwriteQueries(stripPageWindow(filters), scope, scopeColumns);
12346
+ if (base === null) return null;
12347
+ const Query = window.Appwrite.Query;
12348
+ const requireAuth = requiresIdentity(dataSource);
12349
+ const limit = Math.max(1, want || spec.size);
12350
+ const rows = [];
12351
+ let total = null;
12352
+ let hasMore = false;
12353
+ let cursor = after;
12354
+ while (rows.length < limit) {
12355
+ const n = Math.min(spec.size, limit - rows.length);
12356
+ const page = await window.ManifestDataAppwrite.loadTablePage(
12357
+ appwriteConfig.databaseId, tableId,
12358
+ [...base, ...(cursor ? [Query.cursorAfter(cursor)] : []), Query.limit(n + 1)],
12359
+ { requireAuth }
12360
+ );
12361
+ if (total === null) total = page.total;
12362
+ const got = page.rows.slice(0, n);
12363
+ rows.push(...got);
12364
+ hasMore = page.rows.length > n;
12365
+ if (!hasMore || !got.length || !isCurrent()) break;
12366
+ cursor = got[got.length - 1].$id;
12367
+ }
12368
+ return { rows, total, hasMore };
12369
+ }
12370
+
12371
+ // A page landed: move the cursor to its last server row and publish $hasMore / $total.
12372
+ // append: a $more() page; otherwise the window restarted (load, $query, catch-up)
12373
+ function setPagingState(dataSourceName, page, { append = false, filters = null } = {}) {
12374
+ const prev = pagingState.get(dataSourceName) || {};
12375
+ const spec = page.spec || prev.spec;
12376
+ const order = filters ? sortSpec(filters) : (prev.order || null);
12377
+ const loaded = (append ? (prev.loaded || 0) : 0) + page.rows.length;
12378
+ const last = page.rows.length ? page.rows[page.rows.length - 1] : (append ? null : undefined);
12379
+ const cursor = last ? last.$id : (append ? prev.cursor : null);
12380
+ const boundary = last
12381
+ ? Object.fromEntries([['$id', last.$id], ...(order || []).map(([key]) => [key, last[key]])])
12382
+ : (append ? prev.boundary : null);
12383
+ const max = spec ? spec.max : Infinity;
12384
+ const hasMore = !!page.hasMore && loaded < max;
12385
+ const total = page.total !== undefined ? page.total : prev.total;
12386
+ pagingState.set(dataSourceName, { spec, hasMore, total, loaded, cursor, boundary, order });
12387
+ window.ManifestDataStore.setSourceState(dataSourceName, {
12388
+ hasMore,
12389
+ total: typeof total === 'number' ? total : null,
12390
+ totalCapped: typeof total === 'number' && total >= COUNT_CEILING
12391
+ });
12392
+ if (!append && moreQueued.delete(dataSourceName) && hasMore) setTimeout(() => loadMore(dataSourceName).catch(() => {}), 0);
12393
+ }
12394
+
12395
+ // Rows a paged load should fetch: the window size, or (all) the cap; a catch-up keeps what is held
12396
+ function pagedWant(dataSourceName, spec) {
12397
+ const keep = catchUpTargets.get(dataSourceName) || 0;
12398
+ catchUpTargets.delete(dataSourceName);
12399
+ return spec.mode === 'all' ? spec.max : Math.min(spec.max, Math.max(spec.size, keep));
12400
+ }
12401
+
12402
+ // $more(): the next page after the cursor. One at a time; while a load or $query is in
12403
+ // flight it waits for that to land (its window replaces the rows), then continues
12404
+ function loadMore(dataSourceName) {
12405
+ if (moreInFlight.has(dataSourceName)) return moreInFlight.get(dataSourceName);
12406
+ const run = loadMoreOnce(dataSourceName).finally(() => moreInFlight.delete(dataSourceName));
12407
+ moreInFlight.set(dataSourceName, run);
12408
+ return run;
12409
+ }
12410
+
12411
+ // Overtaken by a load or $query: run again once its window has landed (now, if it has)
12412
+ function requeueMore(dataSourceName) {
12413
+ if (window.ManifestDataStore.readsInFlight(dataSourceName)) { moreQueued.add(dataSourceName); return; }
12414
+ setTimeout(() => loadMore(dataSourceName).catch(() => {}), 0);
12415
+ }
12416
+
12417
+ async function loadMoreOnce(dataSourceName) {
12418
+ const { currentRead, readsInFlight, sourceGeneration, landRows, setSourceState } = window.ManifestDataStore;
12419
+ const read = currentRead(dataSourceName);
12420
+ const generation = sourceGeneration(dataSourceName);
12421
+ const manifest = await window.ManifestDataConfig.ensureManifest();
12422
+ const dataSource = manifest?.data?.[dataSourceName];
12423
+ const spec = pagingSpec(dataSource);
12424
+ if (!spec) throw new Error(`[Manifest Data] "${dataSourceName}" $more: set "paging" on the source`);
12425
+ if (readsInFlight(dataSourceName)) { moreQueued.add(dataSourceName); return 0; }
12426
+ const state = pagingState.get(dataSourceName);
12427
+ if (!state?.hasMore || !state.cursor) return 0;
12428
+ const isCurrent = () => currentRead(dataSourceName) === read && sourceGeneration(dataSourceName) === generation && !readsInFlight(dataSourceName);
12429
+ const want = Math.min(spec.size, spec.max - state.loaded);
12430
+ if (want <= 0) return 0;
12431
+ const filters = pagedFilters(dataSourceName, dataSource);
12432
+ setSourceState(dataSourceName, { loading: true });
12433
+ try {
12434
+ let page;
12435
+ try {
12436
+ page = await fetchPagedRows(dataSourceName, filters, { want, after: state.cursor, isCurrent });
12437
+ } catch (error) {
12438
+ const status = error?.code ?? error?.response?.code;
12439
+ if (!isCurrent()) { requeueMore(dataSourceName); return 0; }
12440
+ if (status !== 400 && status !== 404) throw error;
12441
+ // The cursor row is gone (deleted since): refetch everything held plus one page
12442
+ catchUpTargets.set(dataSourceName, state.loaded + want);
12443
+ await reloadDataSource(dataSourceName);
12444
+ return 0;
12445
+ }
12446
+ // Overtaken by a load or $query: its window replaces the rows, then this runs again
12447
+ if (!page || !isCurrent()) { if (page) requeueMore(dataSourceName); return 0; }
12448
+ await landRows(dataSourceName, page.rows, { mode: 'append', generation, readToken: read, order: state.order || undefined });
12449
+ setPagingState(dataSourceName, { ...page, spec }, { append: true });
12450
+ return page.rows.length;
12451
+ } finally {
12452
+ if (!readsInFlight(dataSourceName)) setSourceState(dataSourceName, { loading: false });
12453
+ }
12454
+ }
12455
+
12456
+ // Is this row past the loaded boundary? While more pages exist, such rows arrive with
12457
+ // $more(), not by realtime or a local add. A tie with the boundary counts as inside: if
12458
+ // the server puts it later, its page merges it by $id — never a row lost to the cursor
12459
+ function beyondLoaded(dataSourceName, row) {
12460
+ const state = pagingState.get(dataSourceName);
12461
+ if (!state?.hasMore || !state.boundary) return false;
12462
+ if (!state.order) return true; // unsorted: server order is creation order, new rows come last
12463
+ return window.ManifestDataStore.compareBy(state.order)(row, state.boundary) > 0;
12464
+ }
12465
+
11972
12466
  // Events not applied since the last load — $x.<source>.$realtimeOverflow
11973
12467
  function bumpRealtimeOverflow(dataSourceName) {
11974
12468
  const state = Alpine.store('data')?.[`_${dataSourceName}_state`];
@@ -12067,7 +12561,7 @@ async function handleTableRealtimeEvent(dataSourceName, databaseId, tableId, sco
12067
12561
  if (currentRows.find(r => r.$id === row.$id)) {
12068
12562
  // Echo of a row already held (optimistic create): merge, never counts as growth
12069
12563
  landRows(dataSourceName, [row], { mode: 'append', generation, order });
12070
- } else {
12564
+ } else if (!beyondLoaded(dataSourceName, row)) {
12071
12565
  realtimeAppend(dataSourceName, row, currentRows, generation, order);
12072
12566
  }
12073
12567
  }
@@ -12089,7 +12583,14 @@ async function handleTableRealtimeEvent(dataSourceName, databaseId, tableId, sco
12089
12583
  }
12090
12584
  if (!existingRow) {
12091
12585
  // Row not in list, but matches now - add it (capped like a create)
12092
- realtimeAppend(dataSourceName, row, currentRows, generation, order);
12586
+ if (!beyondLoaded(dataSourceName, row)) realtimeAppend(dataSourceName, row, currentRows, generation, order);
12587
+ return;
12588
+ }
12589
+ // A held row whose sort value moved past the loaded boundary leaves; its page brings it back
12590
+ const paging = pagingState.get(dataSourceName);
12591
+ const sortMoved = paging?.order?.some(([key]) => key in row && !window.ManifestDataStore.sameScalarOrList(existingRow[key], row[key]));
12592
+ if (sortMoved && row.$id !== paging.cursor && beyondLoaded(dataSourceName, row)) {
12593
+ landRemove(dataSourceName, [row.$id], { generation });
12093
12594
  return;
12094
12595
  }
12095
12596
 
@@ -12338,6 +12839,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12338
12839
 
12339
12840
  // Reads are ordered by call: a $query issued after this load wins over it
12340
12841
  const readToken = window.ManifestDataStore.beginRead?.(dataSourceName);
12842
+ let pagedResult = null;
12341
12843
  window.ManifestDataStore.loadReadTokens?.set(cacheKey, readToken);
12342
12844
 
12343
12845
  // Loading state: rows already landed stay live; first-ever load clears
@@ -12374,7 +12876,8 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12374
12876
  return true;
12375
12877
  };
12376
12878
 
12377
- return runDeduped(cacheKey, async () => {
12879
+ const settled = () => window.ManifestDataStore.endRead?.(dataSourceName, readToken);
12880
+ const run = runDeduped(cacheKey, async () => {
12378
12881
  let landed = false;
12379
12882
  try {
12380
12883
  const manifest = await window.ManifestDataConfig.ensureManifest();
@@ -12445,10 +12948,18 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12445
12948
  const queriesConfig = window.ManifestDataConfig.getQueries(dataSource);
12446
12949
 
12447
12950
  if (tableId) {
12448
- // Load from Appwrite table (TablesDB)
12449
- const queries = queriesConfig
12450
- ? await window.ManifestDataQueries.buildAppwriteQueries(queriesConfig.default || queriesConfig, scope, scopeColumns)
12451
- : await window.ManifestDataQueries.buildAppwriteQueries([], scope, scopeColumns);
12951
+ // Load from Appwrite table (TablesDB); paged sources fetch their window or walk every page
12952
+ const spec = pagingSpec(dataSource);
12953
+ if (spec && !pagingState.has(dataSourceName)) pagingState.set(dataSourceName, { hasMore: false, total: null });
12954
+ const defaults = queriesConfig ? (queriesConfig.default || queriesConfig) : [];
12955
+ const paged = spec ? await fetchPagedRows(dataSourceName, defaults, {
12956
+ want: pagedWant(dataSourceName, spec),
12957
+ isCurrent: () => !superseded() && window.ManifestDataStore.isLatestRead(dataSourceName, readToken)
12958
+ }) : undefined;
12959
+ if (paged) pagedResult = { ...paged, spec, filters: defaults };
12960
+ const queries = spec
12961
+ ? (paged ? [] : null)
12962
+ : await window.ManifestDataQueries.buildAppwriteQueries(defaults, scope, scopeColumns);
12452
12963
 
12453
12964
  // Not ready (auth/scope unresolved): skip this read, retry on an auth event
12454
12965
  if (queries === null) {
@@ -12461,7 +12972,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12461
12972
  const authStore = typeof Alpine !== 'undefined' ? Alpine.store('auth') : null;
12462
12973
  const teamIds = authStore?.teams?.map(t => t.$id || t.id) || [];
12463
12974
 
12464
- data = await window.ManifestDataAppwrite.loadTableRows(
12975
+ data = paged ? paged.rows : await window.ManifestDataAppwrite.loadTableRows(
12465
12976
  appwriteConfig.databaseId,
12466
12977
  tableId,
12467
12978
  queries,
@@ -12696,7 +13207,8 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12696
13207
  if (!isInitializing && !staleLocale) {
12697
13208
  landed = true;
12698
13209
  clearActiveQuery(dataSourceName, Array.isArray(enhancedData) ? enhancedData.length : 0);
12699
- await landRows(dataSourceName, enhancedData, { mode: 'replace', loading: false, error: null, ready: true, fresh: true, generation });
13210
+ if (pagedResult) setPagingState(dataSourceName, pagedResult, { filters: pagedResult.filters });
13211
+ await landRows(dataSourceName, enhancedData, { mode: 'replace', loading: false, error: null, ready: true, fresh: true, generation, readToken });
12700
13212
  }
12701
13213
 
12702
13214
  // Return unsealed version for our proxy system
@@ -12737,6 +13249,8 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
12737
13249
  if (!landed && keepRows && !isInitializing && !superseded()) setSourceState(dataSourceName, { loading: false });
12738
13250
  }
12739
13251
  });
13252
+ run.then(settled, settled);
13253
+ return run;
12740
13254
  }
12741
13255
 
12742
13256
  // Reload: refetch past the memory cache; rows stay live and merge by $id
@@ -12876,6 +13390,10 @@ async function initializeDataSourcesPlugin() {
12876
13390
  catchUpTimer = setTimeout(() => {
12877
13391
  for (const name of realtimeBinds.keys()) {
12878
13392
  const active = activeQueries.get(name);
13393
+ if (pagingState.has(name)) {
13394
+ const held = window.ManifestDataStore.rawOf(Alpine.store('data'))?.[name];
13395
+ catchUpTargets.set(name, Array.isArray(held) ? held.length : 0);
13396
+ }
12879
13397
  const handler = active && window.ManifestDataProxiesAppwrite?.createAppwriteMethodsHandler?.(name, reloadDataSource);
12880
13398
  Promise.resolve(handler ? handler('$query', active) : reloadDataSource(name)).catch(() => { /* $error carries it */ });
12881
13399
  }
@@ -12897,6 +13415,14 @@ async function initializeDataSourcesPlugin() {
12897
13415
  requiresIdentity,
12898
13416
  setActiveQuery,
12899
13417
  forgetLiveSource,
13418
+ pagingSpec,
13419
+ fetchPagedRows,
13420
+ pagedWant,
13421
+ setPagingState,
13422
+ loadMore,
13423
+ beyondLoaded,
13424
+ orderFor,
13425
+ rowFitsSource,
12900
13426
  getActiveQuery: (dataSourceName) => activeQueries.get(dataSourceName) || null
12901
13427
  };
12902
13428
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "manifest.appwrite.auth.js": "sha384-gWLSeVPqCLMiUZB8MU7GqMg3x2yULFUsp8nTTZrPp/9Dlkix42rBn9yIimvwrHqZ",
3
- "manifest.appwrite.data.js": "sha384-DL3DcEUoVXDqLwODzd/CBtnTyBPqeFl6RVx01oBv1lCwgMkNEGQeeKdA9l132m2m",
3
+ "manifest.appwrite.data.js": "sha384-+9hmgChYfYnntO61cuLDV3qKPFsoAiJ9dQP+Nk1bCd8URdXW06DQRgHOgA5cJEiN",
4
4
  "manifest.appwrite.presences.js": "sha384-LINPhIPTCK+rA8zd+HPUzMSEgH6Sl2vQMEyItT97bnEE2FYGYKqjXX+CWdt6nl9z",
5
5
  "manifest.bindings.js": "sha384-lPtMf8Ykaic9gNVZKq8Scia1881ZeMAyxer3WCIkUNwwrgzGBWto1OXADUwjvORF",
6
6
  "manifest.charts.js": "sha384-AFbP7mQnigy7DU1s+YE30yKTeQAKfgNazhbfSNbfd9ZpLgeulZKaPi/fAq3gJHDO",
@@ -11,7 +11,7 @@
11
11
  "manifest.combobox.js": "sha384-/lJo6vaxKjgnBSRs/dzkhK1dzGk3GBw8FISoNJZB70mwAVwu1k5veZyBXjOb4keS",
12
12
  "manifest.components.js": "sha384-1el5WMdgmzu/2ocaYN21OjLi/lfjllvA8aju1J3knYuOizw+XFfJU1+rvGqYW7qk",
13
13
  "manifest.computed.js": "sha384-GYML/e81gQfN+iDbqhPUgny8bINCyL+SrbTofoGk4hlCnLLjv51mCv42JMqq+ku5",
14
- "manifest.data.js": "sha384-pOXyFP7tUdQG4c52usKJkWYgGxMN5g2a6dWAKYGAJEHrJL4gZDYRNgOsSq/+jnTm",
14
+ "manifest.data.js": "sha384-MaXt6e553ThEOjE+MjvlE52AtlQaMuTGk2w4ZNHVpvGbhrt9mn0M4ABVvoc1sjlO",
15
15
  "manifest.datepicker.js": "sha384-EzlMwvIxlla/0BuyhAEqxN0M8TGcWIWgEIg840V0akKQQK1uY648wPWMkobvtq/o",
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-hyn8eZtfGN2VxD1+L4AxEyI7CQlPPguEkG5AgjB19A2Ca/W4HhOnTiF3QfoAMnLq",
32
+ "manifest.sw.js": "sha384-PUnPvg68d9B7fXz2/a4wyYngngTZDCeD5PtVEAfWjWwfIc8eyH3UKI0uCKF2TEOQ",
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
38
  "manifest.utilities.js": "sha384-h17EquaRtNcEW0yfhk7R+a+2+CzTlBxPuFryO6i9NV/OiIRMihREoyzQ77QawoQ7",
39
- "manifest.virtual.js": "sha384-ru/eYigBWgJHcHCP0yGKRaF1FNsKisWN61LBWaH16+8ZIh5H8fWtP3aMe0s9/mrg",
39
+ "manifest.virtual.js": "sha384-PtIDx042i29mkxEYZH+y3whBzKgBgV01CU1XzzeEl/8TBPl9qvny4ppyXgYI5DsM",
40
40
  "manifest.js": "sha384-7+hNmvzD6OPQt6q4pZEDoqf5C8LHucIqlfKJQAAH6b4tsmvpX0viCvdYqqGOjqET"
41
41
  }
@@ -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.275';
19
+ const BUILD_VERSION = '0.5.276';
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)
@@ -108,6 +108,8 @@ function initializeVirtualPlugin() {
108
108
  const rendered = new Map(); // key -> { node, scope, removeScope }
109
109
  let data = [];
110
110
  let cumulative = new Float64Array(1); // line-top offsets; last = total
111
+ let endNotifiedAt = -1; // data length `virtual-end` last fired for
112
+ let endHead; // first item's key then: a replaced list fires again
111
113
  let lines = []; // gallery: [{ start, end, height }]
112
114
  let pos = []; // masonry: per-index { x, y, w, h }
113
115
  let sortedTop = []; // masonry: indices sorted by y
@@ -218,6 +220,16 @@ function initializeVirtualPlugin() {
218
220
 
219
221
  // ---- Render ----
220
222
 
223
+ // The last item is rendered: `virtual-end` fires once per data length (load the next page here)
224
+ function notifyEnd(reached) {
225
+ const head = data.length ? keyFn(data[0]) : undefined;
226
+ if (data.length < endNotifiedAt || head !== endHead) endNotifiedAt = -1;
227
+ endHead = head;
228
+ if (!reached || !data.length || endNotifiedAt === data.length) return;
229
+ endNotifiedAt = data.length;
230
+ el.dispatchEvent(new CustomEvent('virtual-end', { bubbles: true, detail: { length: data.length } }));
231
+ }
232
+
221
233
  function render() {
222
234
  if (isMasonry) return renderMasonry();
223
235
  if (!data.length) { clearRows(); setHeight(topSpacer, 0); setHeight(botSpacer, 0); return; }
@@ -238,6 +250,7 @@ function initializeVirtualPlugin() {
238
250
  // Resolve the item range for these units.
239
251
  const startItem = isGallery ? lines[startUnit].start : startUnit;
240
252
  const endItem = isGallery ? lines[endUnit - 1].end : endUnit;
253
+ notifyEnd(endItem >= data.length);
241
254
 
242
255
  const visible = new Set();
243
256
  const keys = [];
@@ -324,6 +337,7 @@ function initializeVirtualPlugin() {
324
337
  for (const [key, entry] of rendered) {
325
338
  if (!visible.has(key)) removeRow(key, entry);
326
339
  }
340
+ notifyEnd(visible.has(keyFn(data[data.length - 1])));
327
341
  scheduleMeasure(keys);
328
342
  }
329
343
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mnfst",
3
- "version": "0.5.275",
3
+ "version": "0.5.276",
4
4
  "private": false,
5
5
  "workspaces": [
6
6
  "templates/starter",
@@ -52,6 +52,7 @@
52
52
  "test:e2e:upload": "node tests/e2e/upload-first-load.e2e.mjs",
53
53
  "test:e2e:test-kit": "node tests/e2e/test-kit-journeys.e2e.mjs",
54
54
  "test:e2e:submissions": "node tests/e2e/submissions.e2e.mjs",
55
+ "test:e2e:data-paging": "node tests/e2e/data-paging.e2e.mjs",
55
56
  "test:e2e:modules": "node tests/e2e/modules.e2e.mjs",
56
57
  "test:e2e:contract": "node tests/e2e/contract.e2e.mjs && node tests/e2e/contract-checks.e2e.mjs",
57
58
  "lint": "echo 'No linting configured'",