mnfst 0.5.274 → 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.
- package/lib/manifest.appwrite.data.js +139 -1
- package/lib/manifest.data.js +566 -35
- package/lib/manifest.integrity.json +4 -4
- package/lib/manifest.schema.json +22 -0
- package/lib/manifest.sw.js +1 -1
- package/lib/manifest.virtual.js +14 -0
- package/package.json +3 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
(function () {
|
|
4
4
|
|
|
5
|
-
const MANIFEST_BUILD_VERSION = '0.5.
|
|
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
|
}
|
|
@@ -1731,4 +1749,124 @@ window.ManifestDataPagination = {
|
|
|
1731
1749
|
};
|
|
1732
1750
|
|
|
1733
1751
|
|
|
1752
|
+
/* Manifest Data Sources - Contract checks */
|
|
1753
|
+
|
|
1754
|
+
// Rows of Appwrite sources whose table the contract declares throw when app code
|
|
1755
|
+
// reads a column that is undeclared and never seen on a row. Dev hosts by default.
|
|
1756
|
+
(function () {
|
|
1757
|
+
const proxies = new WeakMap();
|
|
1758
|
+
const targets = new WeakMap();
|
|
1759
|
+
const warned = new Set();
|
|
1760
|
+
// Read by the framework on every row; storage columns are added per source
|
|
1761
|
+
const ALLOWED = new Set(['then', 'catch', 'finally', 'toJSON', 'length', 'contentType', 'fileIds']);
|
|
1762
|
+
let enabled;
|
|
1763
|
+
let tables = null;
|
|
1764
|
+
const tableBySource = new Map();
|
|
1765
|
+
const seenBySource = new Map();
|
|
1766
|
+
let appwriteSources = null;
|
|
1767
|
+
|
|
1768
|
+
function devHost(h) {
|
|
1769
|
+
return h === 'localhost' || h === '127.0.0.1' || h === '[::1]' || h === '::1' || h === '0.0.0.0' ||
|
|
1770
|
+
h.endsWith('.localhost') || h.endsWith('.local') || h.endsWith('.test');
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
function hostMatches(pattern, host) {
|
|
1774
|
+
const re = new RegExp('^' + String(pattern).toLowerCase().replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^.]*') + '$');
|
|
1775
|
+
return re.test(host);
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
function config(manifest) {
|
|
1779
|
+
const c = manifest && manifest.contract;
|
|
1780
|
+
if (typeof c === 'string') return { module: c, checks: 'dev' };
|
|
1781
|
+
if (c && typeof c === 'object' && typeof c.module === 'string') return { module: c.module, checks: c.checks === undefined ? 'dev' : c.checks };
|
|
1782
|
+
return null;
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
function decide(manifest) {
|
|
1786
|
+
const cfg = config(manifest);
|
|
1787
|
+
if (!cfg || cfg.checks === false) return false;
|
|
1788
|
+
const host = String(location.hostname || '').toLowerCase();
|
|
1789
|
+
if (cfg.checks === true) return cfg;
|
|
1790
|
+
if (devHost(host)) return cfg;
|
|
1791
|
+
return Array.isArray(cfg.checks) && cfg.checks.some(p => hostMatches(p, host)) ? cfg : false;
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
function load(manifest, cfg) {
|
|
1795
|
+
import(new URL(cfg.module, location.origin + '/').href).then(mod => {
|
|
1796
|
+
tables = mod && mod.tables && typeof mod.tables === 'object' ? mod.tables : {};
|
|
1797
|
+
const defaultDb = manifest.appwrite && (manifest.appwrite.databaseId || manifest.appwrite.database);
|
|
1798
|
+
for (const [source, src] of Object.entries(manifest.data || {})) {
|
|
1799
|
+
if (!src || typeof src.appwriteTableId !== 'string') continue;
|
|
1800
|
+
const db = src.appwriteDatabaseId || defaultDb;
|
|
1801
|
+
const hit = Object.entries(tables).find(([key, t]) => t && (t.id || key) === src.appwriteTableId && (!t.database || !db || t.database === db));
|
|
1802
|
+
if (!hit || !Array.isArray(hit[1].columns)) continue;
|
|
1803
|
+
const columns = new Set(hit[1].columns);
|
|
1804
|
+
for (const c of Object.values(src.storage || {})) columns.add(typeof c === 'string' ? c : (c && c.column) || 'fileIds');
|
|
1805
|
+
tableBySource.set(source, { key: hit[0], columns });
|
|
1806
|
+
}
|
|
1807
|
+
}).catch(e => {
|
|
1808
|
+
console.warn(`[Manifest] contract ${cfg.module} failed to load; column checks are off`, e);
|
|
1809
|
+
tables = {};
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
function isEnabled() {
|
|
1814
|
+
if (enabled !== undefined) return enabled;
|
|
1815
|
+
const manifest = window.__manifestLoaded;
|
|
1816
|
+
if (!manifest) return false;
|
|
1817
|
+
const cfg = decide(manifest);
|
|
1818
|
+
enabled = !!cfg;
|
|
1819
|
+
if (cfg) {
|
|
1820
|
+
appwriteSources = new Set(Object.entries(manifest.data || {}).filter(([, s]) => s && typeof s.appwriteTableId === 'string').map(([k]) => k));
|
|
1821
|
+
load(manifest, cfg);
|
|
1822
|
+
}
|
|
1823
|
+
return enabled;
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
const known = (key, table) => key[0] === '$' || key[0] === '_' || ALLOWED.has(key) || table.columns.has(key);
|
|
1827
|
+
|
|
1828
|
+
function drift(source, table, row) {
|
|
1829
|
+
for (const key of Object.keys(row)) {
|
|
1830
|
+
if (known(key, table) || warned.has(source + '\0' + key)) continue;
|
|
1831
|
+
warned.add(source + '\0' + key);
|
|
1832
|
+
console.warn(`[Manifest] data source "${source}" has column "${key}", which the contract does not declare for "${table.key}"`);
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
function guard(source, row) {
|
|
1837
|
+
if (!row || typeof row !== 'object' || Array.isArray(row) || !isEnabled() || !appwriteSources.has(source)) return row;
|
|
1838
|
+
const existing = proxies.get(row);
|
|
1839
|
+
if (existing) return existing;
|
|
1840
|
+
let seen = seenBySource.get(source);
|
|
1841
|
+
if (!seen) seenBySource.set(source, seen = new Set());
|
|
1842
|
+
for (const key of Object.keys(row)) seen.add(key);
|
|
1843
|
+
let checked = false;
|
|
1844
|
+
const proxy = new Proxy(row, {
|
|
1845
|
+
// App reads arrive through Alpine's reactive proxy; its own old-value reads use this one
|
|
1846
|
+
get(target, key, receiver) {
|
|
1847
|
+
if (typeof key === 'string' && tables && receiver !== proxy) {
|
|
1848
|
+
const table = tableBySource.get(source);
|
|
1849
|
+
if (table) {
|
|
1850
|
+
if (!checked) { checked = true; drift(source, table, target); }
|
|
1851
|
+
if (!known(key, table) && !(key in target) && !seen.has(key)) {
|
|
1852
|
+
throw new Error(`[Manifest] "${key}" is not a column of "${table.key}" in the contract (data source "${source}")`);
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
return Reflect.get(target, key, receiver);
|
|
1857
|
+
}
|
|
1858
|
+
});
|
|
1859
|
+
proxies.set(row, proxy);
|
|
1860
|
+
proxies.set(proxy, proxy);
|
|
1861
|
+
targets.set(proxy, row);
|
|
1862
|
+
return proxy;
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
// Framework reads go through the unchecked row
|
|
1866
|
+
const raw = (obj) => (obj && targets.get(obj)) || obj;
|
|
1867
|
+
|
|
1868
|
+
window.ManifestDataContract = { guard, raw };
|
|
1869
|
+
})();
|
|
1870
|
+
|
|
1871
|
+
|
|
1734
1872
|
})();
|
package/lib/manifest.data.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
(function () {
|
|
4
4
|
|
|
5
|
-
const MANIFEST_BUILD_VERSION = '0.5.
|
|
5
|
+
const MANIFEST_BUILD_VERSION = '0.5.276';
|
|
6
6
|
|
|
7
7
|
/* Manifest Data Sources - Configuration */
|
|
8
8
|
|
|
@@ -397,7 +397,7 @@ function mergeRowFields(target, fields, dataSourceName) {
|
|
|
397
397
|
if (key === '$files') continue;
|
|
398
398
|
const value = fields[key];
|
|
399
399
|
if (sameScalarOrList(raw[key], value)) continue;
|
|
400
|
-
target[key] = createReactiveReferences(value, dataSourceName);
|
|
400
|
+
target[key] = createReactiveReferences(value, dataSourceName, true);
|
|
401
401
|
}
|
|
402
402
|
}
|
|
403
403
|
|
|
@@ -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
|
-
|
|
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) {
|
|
@@ -799,24 +954,25 @@ function getRawData(dataSourceName) {
|
|
|
799
954
|
}
|
|
800
955
|
|
|
801
956
|
// New object/array references (incl. nested arrays like fileIds) so Alpine tracks changes
|
|
802
|
-
function createReactiveReferences(data, dataSourceName = null) {
|
|
957
|
+
function createReactiveReferences(data, dataSourceName = null, nested = false) {
|
|
803
958
|
if (data === null || data === undefined) {
|
|
804
959
|
return data;
|
|
805
960
|
}
|
|
806
961
|
|
|
807
962
|
if (Array.isArray(data)) {
|
|
808
963
|
// Create new array with new references for each item
|
|
809
|
-
return data.map(item => createReactiveReferences(item, dataSourceName));
|
|
964
|
+
return data.map(item => createReactiveReferences(item, dataSourceName, nested));
|
|
810
965
|
}
|
|
811
966
|
|
|
812
967
|
if (typeof data === 'object') {
|
|
813
968
|
// Object.keys, not for…in + .hasOwnProperty (see deepSeal). Hot path for
|
|
814
969
|
// every Appwrite mutation result and realtime event.
|
|
815
970
|
const newObj = {};
|
|
971
|
+
let self = newObj;
|
|
816
972
|
for (const key of Object.keys(data)) {
|
|
817
973
|
const value = data[key];
|
|
818
974
|
// Recursively create new references for nested objects/arrays
|
|
819
|
-
newObj[key] = createReactiveReferences(value, dataSourceName);
|
|
975
|
+
newObj[key] = createReactiveReferences(value, dataSourceName, true);
|
|
820
976
|
}
|
|
821
977
|
|
|
822
978
|
// Detect file objects (have mimeType or sizeOriginal)
|
|
@@ -855,7 +1011,7 @@ function createReactiveReferences(data, dataSourceName = null) {
|
|
|
855
1011
|
data.$id,
|
|
856
1012
|
bucketName,
|
|
857
1013
|
columnName,
|
|
858
|
-
{ owner:
|
|
1014
|
+
{ owner: self }
|
|
859
1015
|
);
|
|
860
1016
|
|
|
861
1017
|
// Assign computed array to entry
|
|
@@ -1042,7 +1198,11 @@ function createReactiveReferences(data, dataSourceName = null) {
|
|
|
1042
1198
|
});
|
|
1043
1199
|
}
|
|
1044
1200
|
|
|
1045
|
-
|
|
1201
|
+
// Contract checks wrap top-level Appwrite rows (dev and opted-in hosts)
|
|
1202
|
+
if (!nested && isDatabaseEntry && dataSourceName && window.ManifestDataContract) {
|
|
1203
|
+
self = window.ManifestDataContract.guard(dataSourceName, newObj);
|
|
1204
|
+
}
|
|
1205
|
+
return self;
|
|
1046
1206
|
}
|
|
1047
1207
|
|
|
1048
1208
|
// Primitives can be returned as-is
|
|
@@ -1593,8 +1753,20 @@ window.ManifestDataStore = {
|
|
|
1593
1753
|
// Stale-first + dedupe (§11.1)
|
|
1594
1754
|
setSourceState,
|
|
1595
1755
|
runDeduped,
|
|
1756
|
+
insertRow,
|
|
1757
|
+
holdWrite,
|
|
1758
|
+
releaseWrite,
|
|
1759
|
+
settleWrite,
|
|
1760
|
+
isSaving,
|
|
1761
|
+
pendingWritesFor,
|
|
1762
|
+
pendingCount,
|
|
1763
|
+
sameScalarOrList,
|
|
1596
1764
|
beginRead,
|
|
1765
|
+
endRead,
|
|
1766
|
+
readsInFlight,
|
|
1597
1767
|
adoptRead,
|
|
1768
|
+
currentRead,
|
|
1769
|
+
compareBy,
|
|
1598
1770
|
loadReadTokens,
|
|
1599
1771
|
isLatestRead,
|
|
1600
1772
|
sourceFreshness,
|
|
@@ -3064,8 +3236,8 @@ function addEntryToStore(dataSourceName, entry, options = {}) {
|
|
|
3064
3236
|
return false;
|
|
3065
3237
|
}
|
|
3066
3238
|
|
|
3067
|
-
// Local write:
|
|
3068
|
-
|
|
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));
|
|
3069
3241
|
ds.noteLocalWrite(dataSourceName, entry?.$id, { patch: entry });
|
|
3070
3242
|
ds.touchSource(dataSourceName);
|
|
3071
3243
|
clearSourceCaches(dataSourceName);
|
|
@@ -3118,6 +3290,30 @@ function removeEntryFromStore(dataSourceName, entryId, options = {}) {
|
|
|
3118
3290
|
return { originalEntry };
|
|
3119
3291
|
}
|
|
3120
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
|
+
|
|
3121
3317
|
// Rollback a mutation
|
|
3122
3318
|
function rollbackMutation(mutationId) {
|
|
3123
3319
|
const mutation = pendingMutations.get(mutationId);
|
|
@@ -3170,6 +3366,9 @@ async function executeMutation(mutationConfig) {
|
|
|
3170
3366
|
let originalData = null;
|
|
3171
3367
|
let optimisticData = null;
|
|
3172
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;
|
|
3173
3372
|
|
|
3174
3373
|
// Get helper functions from store
|
|
3175
3374
|
const {
|
|
@@ -3195,13 +3394,15 @@ async function executeMutation(mutationConfig) {
|
|
|
3195
3394
|
}
|
|
3196
3395
|
|
|
3197
3396
|
addEntryToStore(dataSourceName, optimisticData, options);
|
|
3397
|
+
held = ds0?.holdWrite?.(dataSourceName, tempId, 'create', optimisticData);
|
|
3198
3398
|
originalData = null; // Nothing to rollback for create
|
|
3199
3399
|
} else if (type === 'update') {
|
|
3200
3400
|
// Snapshot for rollback (the row itself is mutated in place)
|
|
3201
3401
|
const store = Alpine.store('data');
|
|
3402
|
+
// Snapshot only the patched fields: rollback restores those, nothing else
|
|
3202
3403
|
if (store && store[dataSourceName] && Array.isArray(store[dataSourceName])) {
|
|
3203
3404
|
const found = store[dataSourceName].find(e => e.$id === entryId);
|
|
3204
|
-
originalData = found ?
|
|
3405
|
+
originalData = found && data ? Object.fromEntries(Object.keys(data).map(k => [k, cloneValue(found[k])])) : null;
|
|
3205
3406
|
}
|
|
3206
3407
|
|
|
3207
3408
|
// Set updating state
|
|
@@ -3214,11 +3415,13 @@ async function executeMutation(mutationConfig) {
|
|
|
3214
3415
|
if (originalData) {
|
|
3215
3416
|
updateEntryInStore(dataSourceName, entryId, data, options);
|
|
3216
3417
|
}
|
|
3418
|
+
held = ds0?.holdWrite?.(dataSourceName, entryId, 'update', { ...data }, originalData ? { ...originalData } : null);
|
|
3217
3419
|
} else if (type === 'delete') {
|
|
3218
3420
|
// Snapshot for rollback
|
|
3219
3421
|
const store = Alpine.store('data');
|
|
3220
3422
|
if (store && store[dataSourceName] && Array.isArray(store[dataSourceName])) {
|
|
3221
|
-
|
|
3423
|
+
deletedAt = findRawIndex(dataSourceName, entryId).index;
|
|
3424
|
+
const found = deletedAt !== -1 ? store[dataSourceName][deletedAt] : null;
|
|
3222
3425
|
originalData = found ? { ...found } : null;
|
|
3223
3426
|
}
|
|
3224
3427
|
|
|
@@ -3232,10 +3435,19 @@ async function executeMutation(mutationConfig) {
|
|
|
3232
3435
|
if (originalData) {
|
|
3233
3436
|
removeEntryFromStore(dataSourceName, entryId, options);
|
|
3234
3437
|
}
|
|
3438
|
+
held = ds0?.holdWrite?.(dataSourceName, entryId, 'delete', null);
|
|
3235
3439
|
}
|
|
3236
3440
|
|
|
3237
3441
|
// Step 2: Perform API call
|
|
3238
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;
|
|
3239
3451
|
|
|
3240
3452
|
// Step 3: Clear loading states after successful API call (regardless of result format)
|
|
3241
3453
|
if (type === 'create' && clearCreatingEntry && resolvedEntryId) {
|
|
@@ -3302,6 +3514,10 @@ async function executeMutation(mutationConfig) {
|
|
|
3302
3514
|
clearDeletingEntry(dataSourceName, entryId);
|
|
3303
3515
|
}
|
|
3304
3516
|
|
|
3517
|
+
const mine = held ? ds0.releaseWrite(dataSourceName, resolvedEntryId, held) : null;
|
|
3518
|
+
const heldToken = held;
|
|
3519
|
+
held = null;
|
|
3520
|
+
|
|
3305
3521
|
// Rollback on error
|
|
3306
3522
|
console.error(`[Manifest Data] Mutation failed, rolling back:`, error);
|
|
3307
3523
|
|
|
@@ -3309,9 +3525,26 @@ async function executeMutation(mutationConfig) {
|
|
|
3309
3525
|
if (type === 'create' && optimisticData) {
|
|
3310
3526
|
removeEntryFromStore(dataSourceName, optimisticData.$id, writeOptions);
|
|
3311
3527
|
} else if (type === 'update' && originalData) {
|
|
3312
|
-
|
|
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);
|
|
3313
3546
|
} else if (type === 'delete' && originalData) {
|
|
3314
|
-
|
|
3547
|
+
insertEntryAt(dataSourceName, originalData, deletedAt, writeOptions);
|
|
3315
3548
|
}
|
|
3316
3549
|
};
|
|
3317
3550
|
|
|
@@ -4319,6 +4552,27 @@ function attachArrayMethods(array, dataSourceName, reloadDataSource) {
|
|
|
4319
4552
|
}
|
|
4320
4553
|
});
|
|
4321
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
|
+
|
|
4322
4576
|
// Attach $search method for client-side text filtering
|
|
4323
4577
|
Object.defineProperty(array, '$search', {
|
|
4324
4578
|
enumerable: false,
|
|
@@ -4966,7 +5220,7 @@ function createArrayProxyWithRoute(arrayTarget, dataSourceName = null, reloadDat
|
|
|
4966
5220
|
}
|
|
4967
5221
|
|
|
4968
5222
|
// Handle state properties ($loading, $error, $ready, $stale, $fresh, $realtimeOverflow)
|
|
4969
|
-
if (key === '$stale' || key === '$fresh' || key === '$realtimeOverflow') {
|
|
5223
|
+
if (key === '$stale' || key === '$fresh' || key === '$realtimeOverflow' || key === '$hasMore' || key === '$total' || key === '$totalCapped' || key === '$pending') {
|
|
4970
5224
|
return window.ManifestDataProxiesMagic?.getStateProperty?.(key, dataSourceName);
|
|
4971
5225
|
}
|
|
4972
5226
|
if (key === '$loading' || key === '$error' || key === '$ready') {
|
|
@@ -4990,6 +5244,13 @@ function createArrayProxyWithRoute(arrayTarget, dataSourceName = null, reloadDat
|
|
|
4990
5244
|
}
|
|
4991
5245
|
}
|
|
4992
5246
|
|
|
5247
|
+
if (key === '$more') {
|
|
5248
|
+
return () => window.ManifestDataMain.loadMore(dataSourceName);
|
|
5249
|
+
}
|
|
5250
|
+
if (key === '$saving') {
|
|
5251
|
+
return window.ManifestDataProxiesMagic.createSavingMethod(dataSourceName);
|
|
5252
|
+
}
|
|
5253
|
+
|
|
4993
5254
|
// Handle pagination methods
|
|
4994
5255
|
if (key === '$first' || key === '$next' || key === '$prev' || key === '$page') {
|
|
4995
5256
|
return (...args) => window.ManifestDataProxiesMagic.createPaginationMethod(key, dataSourceName)(...args);
|
|
@@ -8083,19 +8344,34 @@ function createAppwriteMethodsHandler(dataSourceName, reloadDataSource) {
|
|
|
8083
8344
|
const { runDeduped, landRows, sourceGeneration, isLatestRead } = window.ManifestDataStore || {};
|
|
8084
8345
|
const generation = sourceGeneration?.(dataSourceName);
|
|
8085
8346
|
const requireAuth = window.ManifestDataMain?.requiresIdentity?.({ ...dataSource, queries: [dataSource.queries, queries] }) ?? true;
|
|
8086
|
-
|
|
8087
|
-
|
|
8088
|
-
|
|
8089
|
-
|
|
8090
|
-
|
|
8091
|
-
|
|
8092
|
-
|
|
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();
|
|
8093
8368
|
// Network landing: query result replaces the source (coalesced, identity-preserving);
|
|
8094
8369
|
// only the last-issued read of this source lands
|
|
8095
8370
|
const latest = !isLatestRead || isLatestRead(dataSourceName, readToken);
|
|
8096
8371
|
if (result !== undefined && landRows && latest && sourceGeneration?.(dataSourceName) === generation) {
|
|
8097
8372
|
window.ManifestDataMain?.setActiveQuery?.(dataSourceName, queries || [], Array.isArray(result) ? result.length : 0);
|
|
8098
|
-
|
|
8373
|
+
if (paged) main.setPagingState(dataSourceName, { ...paged, spec }, { filters: queries || [] });
|
|
8374
|
+
await landRows(dataSourceName, result, { mode: 'replace', fresh: true, generation, readToken });
|
|
8099
8375
|
}
|
|
8100
8376
|
return result;
|
|
8101
8377
|
}
|
|
@@ -8859,6 +9135,8 @@ function createAppwriteMethodsHandler(dataSourceName, reloadDataSource) {
|
|
|
8859
9135
|
setErrorState(error);
|
|
8860
9136
|
// Re-throw so promise chain still works if caller wants to handle it
|
|
8861
9137
|
throw error;
|
|
9138
|
+
} finally {
|
|
9139
|
+
if (readToken !== undefined) window.ManifestDataStore?.endRead?.(dataSourceName, readToken);
|
|
8862
9140
|
}
|
|
8863
9141
|
};
|
|
8864
9142
|
|
|
@@ -8886,12 +9164,15 @@ window.ManifestDataProxiesAppwrite.createAppwriteMethodsHandler = createAppwrite
|
|
|
8886
9164
|
// $realtimeOverflow: realtime events not applied since the last load (bounded
|
|
8887
9165
|
// growth caps); reset to 0 on each load.
|
|
8888
9166
|
|
|
8889
|
-
|
|
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'];
|
|
8890
9170
|
|
|
8891
9171
|
function defaultStateValue(prop) {
|
|
8892
9172
|
if (prop === '$error') return null;
|
|
8893
9173
|
if (prop === '$stale') return true;
|
|
8894
|
-
if (prop === '$realtimeOverflow') return 0;
|
|
9174
|
+
if (prop === '$realtimeOverflow' || prop === '$pending') return 0;
|
|
9175
|
+
if (prop === '$total') return null;
|
|
8895
9176
|
return false;
|
|
8896
9177
|
}
|
|
8897
9178
|
|
|
@@ -8922,11 +9203,27 @@ function getStateProperty(prop, dataSourceName) {
|
|
|
8922
9203
|
return state.stale !== false;
|
|
8923
9204
|
} else if (prop === '$realtimeOverflow') {
|
|
8924
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;
|
|
8925
9214
|
}
|
|
8926
9215
|
|
|
8927
9216
|
return undefined;
|
|
8928
9217
|
}
|
|
8929
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
|
+
|
|
8930
9227
|
// State property handler for use in proxy get() traps
|
|
8931
9228
|
function createStatePropertyHandler(dataSourceName) {
|
|
8932
9229
|
return function (key) {
|
|
@@ -8944,6 +9241,7 @@ if (!window.ManifestDataProxiesMagic) {
|
|
|
8944
9241
|
window.ManifestDataProxiesMagic.STATE_PROPS = STATE_PROPS;
|
|
8945
9242
|
window.ManifestDataProxiesMagic.getStateProperty = getStateProperty;
|
|
8946
9243
|
window.ManifestDataProxiesMagic.createStatePropertyHandler = createStatePropertyHandler;
|
|
9244
|
+
window.ManifestDataProxiesMagic.createSavingMethod = createSavingMethod;
|
|
8947
9245
|
|
|
8948
9246
|
|
|
8949
9247
|
/* Manifest Data Sources - Magic Method $files Handler */
|
|
@@ -9356,6 +9654,12 @@ function createAppwriteLoadingProxy(dataSourceName, reloadDataSource) {
|
|
|
9356
9654
|
if ((key === '$first' || key === '$next' || key === '$prev' || key === '$page') && createPaginationMethod) {
|
|
9357
9655
|
return createPaginationMethod(key, dataSourceName);
|
|
9358
9656
|
}
|
|
9657
|
+
if (key === '$more') {
|
|
9658
|
+
return () => window.ManifestDataMain.loadMore(dataSourceName);
|
|
9659
|
+
}
|
|
9660
|
+
if (key === '$saving') {
|
|
9661
|
+
return window.ManifestDataProxiesMagic.createSavingMethod(dataSourceName);
|
|
9662
|
+
}
|
|
9359
9663
|
|
|
9360
9664
|
// Appwrite CRUD
|
|
9361
9665
|
if (key === '$create' || key === '$update' || key === '$delete' || key === '$query' ||
|
|
@@ -9562,6 +9866,8 @@ function registerXMagicMethod(loadDataSource) {
|
|
|
9562
9866
|
if (stateProps.includes(key)) {
|
|
9563
9867
|
return window.ManifestDataProxiesMagic.getStateProperty(key, prop);
|
|
9564
9868
|
}
|
|
9869
|
+
if (key === '$saving') return window.ManifestDataProxiesMagic.createSavingMethod(prop);
|
|
9870
|
+
if (key === '$more') return () => window.ManifestDataMain.loadMore(prop);
|
|
9565
9871
|
return target[key];
|
|
9566
9872
|
}
|
|
9567
9873
|
}));
|
|
@@ -11894,6 +12200,12 @@ const realtimeMeta = new Map(); // Map<name, { mode, maxRows, appended: [], pend
|
|
|
11894
12200
|
|
|
11895
12201
|
function configureRealtimeMeta(dataSourceName, config, initialCount, limitQuery) {
|
|
11896
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
|
+
}
|
|
11897
12209
|
const mode = cfg.mode === 'window' ? 'window' : 'append';
|
|
11898
12210
|
const fallback = Math.max(500, 2 * initialCount);
|
|
11899
12211
|
let maxRows;
|
|
@@ -11958,12 +12270,199 @@ function clearActiveQuery(dataSourceName, rowCount) {
|
|
|
11958
12270
|
rebindLive(dataSourceName);
|
|
11959
12271
|
}
|
|
11960
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
|
+
|
|
11961
12294
|
// Source reset (identity/scope) or torn down: nothing of the old binding carries over
|
|
11962
12295
|
function forgetLiveSource(dataSourceName) {
|
|
11963
12296
|
activeQueries.delete(dataSourceName);
|
|
12297
|
+
pagingState.delete(dataSourceName);
|
|
12298
|
+
catchUpTargets.delete(dataSourceName);
|
|
11964
12299
|
realtimeBinds.delete(dataSourceName);
|
|
11965
12300
|
}
|
|
11966
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
|
+
|
|
11967
12466
|
// Events not applied since the last load — $x.<source>.$realtimeOverflow
|
|
11968
12467
|
function bumpRealtimeOverflow(dataSourceName) {
|
|
11969
12468
|
const state = Alpine.store('data')?.[`_${dataSourceName}_state`];
|
|
@@ -12062,7 +12561,7 @@ async function handleTableRealtimeEvent(dataSourceName, databaseId, tableId, sco
|
|
|
12062
12561
|
if (currentRows.find(r => r.$id === row.$id)) {
|
|
12063
12562
|
// Echo of a row already held (optimistic create): merge, never counts as growth
|
|
12064
12563
|
landRows(dataSourceName, [row], { mode: 'append', generation, order });
|
|
12065
|
-
} else {
|
|
12564
|
+
} else if (!beyondLoaded(dataSourceName, row)) {
|
|
12066
12565
|
realtimeAppend(dataSourceName, row, currentRows, generation, order);
|
|
12067
12566
|
}
|
|
12068
12567
|
}
|
|
@@ -12084,7 +12583,14 @@ async function handleTableRealtimeEvent(dataSourceName, databaseId, tableId, sco
|
|
|
12084
12583
|
}
|
|
12085
12584
|
if (!existingRow) {
|
|
12086
12585
|
// Row not in list, but matches now - add it (capped like a create)
|
|
12087
|
-
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 });
|
|
12088
12594
|
return;
|
|
12089
12595
|
}
|
|
12090
12596
|
|
|
@@ -12333,6 +12839,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
|
|
|
12333
12839
|
|
|
12334
12840
|
// Reads are ordered by call: a $query issued after this load wins over it
|
|
12335
12841
|
const readToken = window.ManifestDataStore.beginRead?.(dataSourceName);
|
|
12842
|
+
let pagedResult = null;
|
|
12336
12843
|
window.ManifestDataStore.loadReadTokens?.set(cacheKey, readToken);
|
|
12337
12844
|
|
|
12338
12845
|
// Loading state: rows already landed stay live; first-ever load clears
|
|
@@ -12369,7 +12876,8 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
|
|
|
12369
12876
|
return true;
|
|
12370
12877
|
};
|
|
12371
12878
|
|
|
12372
|
-
|
|
12879
|
+
const settled = () => window.ManifestDataStore.endRead?.(dataSourceName, readToken);
|
|
12880
|
+
const run = runDeduped(cacheKey, async () => {
|
|
12373
12881
|
let landed = false;
|
|
12374
12882
|
try {
|
|
12375
12883
|
const manifest = await window.ManifestDataConfig.ensureManifest();
|
|
@@ -12440,10 +12948,18 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
|
|
|
12440
12948
|
const queriesConfig = window.ManifestDataConfig.getQueries(dataSource);
|
|
12441
12949
|
|
|
12442
12950
|
if (tableId) {
|
|
12443
|
-
// Load from Appwrite table (TablesDB)
|
|
12444
|
-
const
|
|
12445
|
-
|
|
12446
|
-
|
|
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);
|
|
12447
12963
|
|
|
12448
12964
|
// Not ready (auth/scope unresolved): skip this read, retry on an auth event
|
|
12449
12965
|
if (queries === null) {
|
|
@@ -12456,7 +12972,7 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
|
|
|
12456
12972
|
const authStore = typeof Alpine !== 'undefined' ? Alpine.store('auth') : null;
|
|
12457
12973
|
const teamIds = authStore?.teams?.map(t => t.$id || t.id) || [];
|
|
12458
12974
|
|
|
12459
|
-
data = await window.ManifestDataAppwrite.loadTableRows(
|
|
12975
|
+
data = paged ? paged.rows : await window.ManifestDataAppwrite.loadTableRows(
|
|
12460
12976
|
appwriteConfig.databaseId,
|
|
12461
12977
|
tableId,
|
|
12462
12978
|
queries,
|
|
@@ -12691,7 +13207,8 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
|
|
|
12691
13207
|
if (!isInitializing && !staleLocale) {
|
|
12692
13208
|
landed = true;
|
|
12693
13209
|
clearActiveQuery(dataSourceName, Array.isArray(enhancedData) ? enhancedData.length : 0);
|
|
12694
|
-
|
|
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 });
|
|
12695
13212
|
}
|
|
12696
13213
|
|
|
12697
13214
|
// Return unsealed version for our proxy system
|
|
@@ -12732,6 +13249,8 @@ async function loadDataSource(dataSourceName, locale = 'en', options = {}) {
|
|
|
12732
13249
|
if (!landed && keepRows && !isInitializing && !superseded()) setSourceState(dataSourceName, { loading: false });
|
|
12733
13250
|
}
|
|
12734
13251
|
});
|
|
13252
|
+
run.then(settled, settled);
|
|
13253
|
+
return run;
|
|
12735
13254
|
}
|
|
12736
13255
|
|
|
12737
13256
|
// Reload: refetch past the memory cache; rows stay live and merge by $id
|
|
@@ -12871,6 +13390,10 @@ async function initializeDataSourcesPlugin() {
|
|
|
12871
13390
|
catchUpTimer = setTimeout(() => {
|
|
12872
13391
|
for (const name of realtimeBinds.keys()) {
|
|
12873
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
|
+
}
|
|
12874
13397
|
const handler = active && window.ManifestDataProxiesAppwrite?.createAppwriteMethodsHandler?.(name, reloadDataSource);
|
|
12875
13398
|
Promise.resolve(handler ? handler('$query', active) : reloadDataSource(name)).catch(() => { /* $error carries it */ });
|
|
12876
13399
|
}
|
|
@@ -12892,6 +13415,14 @@ async function initializeDataSourcesPlugin() {
|
|
|
12892
13415
|
requiresIdentity,
|
|
12893
13416
|
setActiveQuery,
|
|
12894
13417
|
forgetLiveSource,
|
|
13418
|
+
pagingSpec,
|
|
13419
|
+
fetchPagedRows,
|
|
13420
|
+
pagedWant,
|
|
13421
|
+
setPagingState,
|
|
13422
|
+
loadMore,
|
|
13423
|
+
beyondLoaded,
|
|
13424
|
+
orderFor,
|
|
13425
|
+
rowFitsSource,
|
|
12895
13426
|
getActiveQuery: (dataSourceName) => activeQueries.get(dataSourceName) || null
|
|
12896
13427
|
};
|
|
12897
13428
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"manifest.appwrite.auth.js": "sha384-gWLSeVPqCLMiUZB8MU7GqMg3x2yULFUsp8nTTZrPp/9Dlkix42rBn9yIimvwrHqZ",
|
|
3
|
-
"manifest.appwrite.data.js": "sha384
|
|
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-
|
|
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-
|
|
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-
|
|
39
|
+
"manifest.virtual.js": "sha384-PtIDx042i29mkxEYZH+y3whBzKgBgV01CU1XzzeEl/8TBPl9qvny4ppyXgYI5DsM",
|
|
40
40
|
"manifest.js": "sha384-7+hNmvzD6OPQt6q4pZEDoqf5C8LHucIqlfKJQAAH6b4tsmvpX0viCvdYqqGOjqET"
|
|
41
41
|
}
|
package/lib/manifest.schema.json
CHANGED
|
@@ -137,6 +137,28 @@
|
|
|
137
137
|
"type": "string"
|
|
138
138
|
}
|
|
139
139
|
},
|
|
140
|
+
"contract": {
|
|
141
|
+
"description": "Shared contract module, a path from the project root (e.g. /shared/contract.js), whose `tables` export declares Appwrite tables and columns. mnfst-test checks data sources against it; on dev hosts (or hosts listed in `checks`) app code reading a column of an Appwrite row that is undeclared and absent from every row of the source throws.",
|
|
142
|
+
"oneOf": [
|
|
143
|
+
{ "type": "string" },
|
|
144
|
+
{
|
|
145
|
+
"type": "object",
|
|
146
|
+
"properties": {
|
|
147
|
+
"module": { "type": "string" },
|
|
148
|
+
"checks": {
|
|
149
|
+
"description": "Where column checks run: 'dev' (default, local hosts), true (everywhere), false (nowhere), or host patterns such as '*-staging.example.com' (dev hosts included).",
|
|
150
|
+
"oneOf": [
|
|
151
|
+
{ "type": "boolean" },
|
|
152
|
+
{ "type": "string", "enum": ["dev"] },
|
|
153
|
+
{ "type": "array", "items": { "type": "string" } }
|
|
154
|
+
]
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
"required": ["module"],
|
|
158
|
+
"additionalProperties": false
|
|
159
|
+
}
|
|
160
|
+
]
|
|
161
|
+
},
|
|
140
162
|
"data": {
|
|
141
163
|
"type": "object",
|
|
142
164
|
"description": "Named data sources made available via $x.<sourceName>. Each value is either a string path/URL or a config object.",
|
package/lib/manifest.sw.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
// Build stamps the published version here; unstamped (dev) falls back to the
|
|
18
18
|
// registration URL's `v`, then 'dev'.
|
|
19
|
-
const BUILD_VERSION = '0.5.
|
|
19
|
+
const BUILD_VERSION = '0.5.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)
|
package/lib/manifest.virtual.js
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "0.5.276",
|
|
4
4
|
"private": false,
|
|
5
5
|
"workspaces": [
|
|
6
6
|
"templates/starter",
|
|
@@ -52,7 +52,9 @@
|
|
|
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",
|
|
57
|
+
"test:e2e:contract": "node tests/e2e/contract.e2e.mjs && node tests/e2e/contract-checks.e2e.mjs",
|
|
56
58
|
"lint": "echo 'No linting configured'",
|
|
57
59
|
"release:docs": "node scripts/release-bump.mjs packages/docs && cd packages/docs && npm publish --auth-type=web",
|
|
58
60
|
"release:check": "node scripts/release-check.mjs"
|