/* Manifest Data Sources - Main Initialization */ // A scoped query that isn't ready yet (buildAppwriteQueries returned null — see // manifest.data.queries.js) skips the network read and waits here instead of // sending a broken/empty-equal query. Retries once when auth settles further; // dedup by key so a source pending across repeated loads doesn't stack listeners. const pendingAuthRetries = new Set(); const AUTH_RETRY_EVENTS = ['manifest:auth:initialized', 'manifest:auth:teams-loaded', 'manifest:auth:login', 'manifest:auth:anonymous']; function scheduleAuthRetry(dataSourceName, locale) { if (typeof window === 'undefined') return; const key = `${dataSourceName}:${locale}`; if (pendingAuthRetries.has(key)) return; pendingAuthRetries.add(key); const retry = () => { pendingAuthRetries.delete(key); AUTH_RETRY_EVENTS.forEach(type => window.removeEventListener(type, retry)); loadDataSource(dataSourceName, locale, { reload: true }); }; AUTH_RETRY_EVENTS.forEach(type => window.addEventListener(type, retry)); } // Teams known for this identity: login/anonymous dispatch after teams load, teams-loaded after the background load. // A cross-tab login arrives before this tab's team load; its teams-loaded follows. let teamsSettledFor = null; // A sign-in deadline already answered by an auth event no longer holds sources let answeredDeadline = 0; if (typeof window !== 'undefined') { ['manifest:auth:teams-loaded', 'manifest:auth:login', 'manifest:auth:anonymous'].forEach(type => window.addEventListener(type, e => { if (!e?.detail?.crossTab) teamsSettledFor = authUserId(currentAuth()); })); // Kept only when logout restored the same (guest) identity whose teams already loaded ['manifest:auth:logout', 'manifest:auth:session-cleared', 'manifest:auth:initialized'].forEach(type => window.addEventListener(type, () => { if (type === 'manifest:auth:initialized' || teamsSettledFor !== authUserId(currentAuth())) teamsSettledFor = null; })); ['manifest:auth:login', 'manifest:auth:anonymous', 'manifest:auth:logout', 'manifest:auth:session-cleared'].forEach(type => window.addEventListener(type, () => { answeredDeadline = currentAuth()?._signInPendingUntil || 0; })); } function currentAuth() { return typeof Alpine !== 'undefined' ? Alpine.store('auth') : null; } function authUserId(auth) { return auth?.user?.$id || auth?.user?.id || null; } // Guest-auto or an auth callback is signing in after a signed-out init (bounded by the auth store). // Not while the session is unverified (no sign-in follows until Appwrite is reachable). // Prerender never waits on (or bakes) a guest's rows function signInWaitMs(auth) { if (!auth || auth.isAuthenticated === true || auth._sessionUnverified === true || window.__manifestRender) return 0; const until = auth._signInPendingUntil || 0; if (until === answeredDeadline) return 0; return Math.max(0, until - Date.now()); } // Drop only this load's subscription; a newer one under the same name stays function dropSubscription(dataSourceName, unsubscribe) { if (typeof unsubscribe !== 'function') return; unsubscribe(); const subs = window.ManifestDataRealtime?.subscriptions; if (subs?.get?.(dataSourceName) === unsubscribe) subs.delete(dataSourceName); } // Init couldn't reach Appwrite: signed out locally until the recheck confirms or clears the session function sessionUnverified(auth) { return auth?._sessionUnverified === true && auth.isAuthenticated !== true; } // Auth settled with no identity (or no auth plugin): a scoped read can't resolve until sign-in function authSettledSignedOut() { const auth = currentAuth(); if (!auth) return true; return auth._initialized === true && auth.isAuthenticated !== true && signInWaitMs(auth) === 0; } function teamsSettled(auth, manifest) { const id = authUserId(auth); if (id && teamsSettledFor === id) return true; const teams = manifest?.appwrite?.auth?.teams; if (!teams) return true; const guests = typeof teams.guests === 'string' ? /^(true|1|yes|on)$/i.test(teams.guests.trim()) : !!teams.guests; return auth.isAnonymous === true && !guests; } // Auth fully settled (identity + teams) yet the scoped read still can't resolve: it never will function authSettledUnresolvable(manifest) { if (authSettledSignedOut()) return true; const auth = currentAuth(); return auth._initialized === true && auth.isAuthenticated === true && teamsSettled(auth, manifest); } // Rows depend on who reads them: scope / $auth. queries, or any Appwrite table/bucket (row/file permissions). // Reset on identity change only; requiresIdentity gates the auth pre-flight. function isIdentityBound(config) { if (!config || typeof config !== 'object') return false; if (window.ManifestDataConfig?.isAppwriteCollection?.(config)) return true; return requiresIdentity(config); } // Reads that need a signed-in identity (scope / $auth. queries); others read with whatever session exists function requiresIdentity(config) { if (!config || typeof config !== 'object') return false; if (window.ManifestDataConfig?.getScope?.(config)) return true; try { return JSON.stringify(config.queries || '').includes('$auth.'); } catch { return false; } } // Auth's last recorded identity (cross-tab mirror): '' signed out, null unknown function lastKnownIdentity() { try { const saved = JSON.parse(window.localStorage?.getItem('manifest:auth:state') || 'null'); if (!saved || typeof saved !== 'object') return null; return saved.isAuthenticated ? (String(saved.user?.$id || saved.user?.id || '') || null) : ''; } catch { return null; } } // Confirmed identity: '' signed out (or no auth plugin), null while booting or offline-unverified function confirmedIdentity() { const auth = currentAuth(); if (!auth) return ''; if (auth._initialized !== true || (auth._sessionUnverified === true && auth.isAuthenticated !== true)) return null; return auth.isAuthenticated === true ? (authUserId(auth) || '') : ''; } // Bumped synchronously when an identity ends (sign-out, account switch), before any source reset; covers never-loaded sources let identityEpoch = 0; // Identity change (sign-in, sign-out, account switch): identity-bound sources reload for the new identity. // A previous user's rows drop at once; rows read signed out stay live until the reload lands. function setupAuthResetListener() { let bound = (currentAuth() ? confirmedIdentity() : null) ?? lastKnownIdentity(); // Reads under an unverified session failed or came from the snapshot: confirming the same identity still reloads let unverified = currentAuth()?._sessionUnverified === true; // keepQuery: someone is signed in, so a source showing a $query shows it again under them const reset = async (clear, keepQuery = false) => { // Reads issued after this auth change already see the new identity: they stand const readAtEvent = window.ManifestDataStore?.readSeqNow?.(); const manifest = await window.ManifestDataConfig?.ensureManifest?.(); const ds = window.ManifestDataStore; const store = typeof Alpine !== 'undefined' ? Alpine.store('data') : null; if (!manifest || !ds?.resetSource || !store) return; const raw = ds.rawOf ? ds.rawOf(store) : store; const configs = { ...(manifest.appwrite || {}) }; for (const name of Object.getOwnPropertyNames(manifest.data || {})) configs[name] = manifest.data[name]; // incl. hidden inline buckets const locale = liveLocale(); for (const [name, config] of Object.entries(configs)) { if (!isIdentityBound(config) || raw[`_${name}_state`] === undefined) continue; if (!clear && keepQuery && awaitingQueries.has(name)) continue; // a $query waiting on this sign-in runs it if (!clear && readAtEvent !== undefined && (ds.currentRead?.(name) ?? 0) > readAtEvent) continue; const active = keepQuery ? (queryIntents.get(name)?.queries || activeQueries.get(name)) : null; if (clear) { window.ManifestDataRealtime?.unsubscribeFromDataSource?.(name); ds.resetSource(name); } const handler = active && window.ManifestDataProxiesAppwrite?.createAppwriteMethodsHandler?.(name, reloadDataSource); if (handler) Promise.resolve(handler('$query', active)).catch(() => { /* $error carries it */ }); else loadDataSource(name, locale, { reload: true }); } }; const onAuth = (type) => { const ended = type === 'manifest:auth:logout' || type === 'manifest:auth:session-cleared'; const next = confirmedIdentity() ?? (ended ? '' : null); if (next === null) { if (currentAuth()?._sessionUnverified === true) unverified = true; return; } const prev = bound; bound = next; const recovered = unverified; unverified = false; // Same identity, or unknown before (rows so far were read under this same session; a sign-out still drops them): // no reset, but an unverified boot's reads are redone with the rows kept live if (prev === next || (prev === null && !ended)) { if (recovered) reset(false, next !== ''); return; } // An identity switch (A to B) starts clean with the defaults; a first sign-in keeps the $query if (prev !== '') identityEpoch++; reset(prev !== '', prev === '' && next !== ''); }; ['manifest:auth:logout', 'manifest:auth:session-cleared', 'manifest:auth:login', 'manifest:auth:anonymous', 'manifest:auth:initialized'] .forEach(type => window.addEventListener(type, () => onAuth(type))); } // Client-side scope filter: Appwrite returns all accessible files, so narrow to // the current team to match database team-scope behavior. async function filterFilesByScope(files, scope) { if (!files || !Array.isArray(files) || files.length === 0) { return files; } // Get auth store const authStore = typeof Alpine !== 'undefined' ? Alpine.store('auth') : null; if (!authStore) { return files; } // Wait for auth store initialization if (!authStore._initialized || authStore.isAuthenticated === undefined) { let attempts = 0; const maxAttempts = 10; while (attempts < maxAttempts && (!authStore._initialized || authStore.isAuthenticated === undefined)) { await new Promise(resolve => setTimeout(resolve, 50)); attempts++; } } const isAuthenticated = authStore.isAuthenticated === true; if (!isAuthenticated) { return []; } const scopeArray = Array.isArray(scope) ? scope : [scope]; const hasUserScope = scopeArray.includes('user'); const hasTeamScope = scopeArray.includes('team'); const hasTeamsScope = scopeArray.includes('teams'); // Get Permission and Role helpers const Permission = window.Appwrite?.Permission; const Role = window.Appwrite?.Role; if (!Permission || !Role) { console.warn('[Manifest Data] Appwrite Permission/Role not available, cannot filter files by scope'); return files; } // Build expected permission strings based on scope const expectedPermissions = []; if (hasUserScope) { const user = authStore.user; const userId = user?.$id || user?.id; if (userId) { expectedPermissions.push(Permission.read(Role.user(userId))); } } if (hasTeamScope) { const currentTeam = authStore.currentTeam; const teamId = currentTeam?.$id || currentTeam?.id; if (teamId) { expectedPermissions.push(Permission.read(Role.team(teamId))); } else { // No current team - return empty array (matches database behavior) return []; } } if (hasTeamsScope) { const teams = authStore.teams || []; teams.forEach(team => { const teamId = team.$id || team.id; if (teamId) { expectedPermissions.push(Permission.read(Role.team(teamId))); } }); } if (expectedPermissions.length === 0) { // No scope permissions to filter by, return all files return files; } // Filter files: include file if its permissions match any of the expected permissions const filteredFiles = files.filter(file => { const filePermissions = file.$permissions || []; // Check if file has any of the expected permissions return expectedPermissions.some(expectedPerm => { // Permission strings are in format like "read(\"team:teamId\")" // We need to check if the file's permissions include this const expectedPermString = typeof expectedPerm === 'string' ? expectedPerm : String(expectedPerm); return filePermissions.some(filePerm => { const filePermString = typeof filePerm === 'string' ? filePerm : String(filePerm); // Check if permissions match (they should be identical strings) return filePermString === expectedPermString; }); }); }); return filteredFiles; } // Handle real-time storage events async function handleStorageRealtimeEvent(dataSourceName, bucketId, scope, eventType, payload, generation, queriesConfig) { // Deduplicate events (per source: shared-channel peers each process once) const eventKey = `${dataSourceName}|${getEventKey(eventType, payload)}`; if (isEventProcessed(eventKey)) { return; } markEventProcessed(eventKey); const store = Alpine.store('data'); if (!store) { return; } const currentFiles = store[dataSourceName]; if (!Array.isArray(currentFiles)) { return; } // Network landings: coalesced per frame (landRows upserts by $id), never the sync mutation path const { landRows, landRemove } = window.ManifestDataStore; if (eventType === 'create') { const file = payload?.$id ? payload : (payload?.file || payload); if (file && file.$id) { const fileMatchesScope = await checkFileMatchesScope(file, scope); if (fileMatchesScope && eventMatchesQueries(file, queriesConfig)) { if (currentFiles.find(f => f && f.$id === file.$id)) { landRows(dataSourceName, [file], { mode: 'append', generation }); } else { realtimeAppend(dataSourceName, file, currentFiles, generation); } // Emit custom event for new file creation so UI can refresh project files window.dispatchEvent(new CustomEvent('manifest:file-created', { detail: { fileId: file.$id, file: file } })); } } else { console.warn('[Manifest Data] Invalid file payload in create event:', payload); } } else if (eventType === 'update') { const file = payload?.$id ? payload : (payload?.file || payload); if (file && file.$id) { const fileMatchesScope = await checkFileMatchesScope(file, scope); if (fileMatchesScope && eventMatchesQueries(file, queriesConfig)) { if (currentFiles.find(f => f && f.$id === file.$id)) { landRows(dataSourceName, [file], { mode: 'append', generation }); } else { realtimeAppend(dataSourceName, file, currentFiles, generation); } } else { // File no longer matches scope/queries, remove it landRemove(dataSourceName, [file.$id], { generation }); } } } else if (eventType === 'delete') { const fileId = payload?.$id || payload?.file?.$id || payload?.fileId || payload; if (fileId) { landRemove(dataSourceName, [fileId.$id || fileId], { generation }); forgetRealtimeRow(dataSourceName, fileId.$id || fileId); } } } // Realtime event dedup: key by source+type+id+sequence(+timestamp). // Keyed PER SOURCE: on the shared realtime client two sources sharing a channel // each process an event once; the dedupe only absorbs replays within a source. const processedEvents = new Map(); // Map const EVENT_DEDUP_WINDOW = 2000; // ms function getEventKey(eventType, payload) { const id = payload?.$id || payload?.row?.$id || payload?.rowId || payload?.id || payload; const sequence = payload?.$sequence || payload?.sequence; const timestamp = payload?.$updatedAt || payload?.$createdAt || payload?.timestamp; // Updates add timestamp so the same sequence from different clients isn't dropped if (eventType === 'update' && timestamp) { return `${eventType}:${id}:${sequence}:${timestamp}`; } return `${eventType}:${id}:${sequence || Date.now()}`; } // Check if an event was recently processed function isEventProcessed(eventKey) { const timestamp = processedEvents.get(eventKey); if (!timestamp) { return false; } // Remove old entries if (Date.now() - timestamp > EVENT_DEDUP_WINDOW) { processedEvents.delete(eventKey); return false; } return true; } // Mark an event as processed function markEventProcessed(eventKey) { processedEvents.set(eventKey, Date.now()); // Clean up old entries periodically if (processedEvents.size > 1000) { const now = Date.now(); for (const [key, timestamp] of processedEvents.entries()) { if (now - timestamp > EVENT_DEDUP_WINDOW) { processedEvents.delete(key); } } } } // Bounded realtime growth: per-source caps + overflow counter, reset each load const realtimeMeta = new Map(); // Map function configureRealtimeMeta(dataSourceName, config, initialCount, limitQuery) { const cfg = (config && typeof config === 'object') ? config : {}; // Paged sources hold what was paged in; growth is bounded by the paging rule, not a cap if (pagingState.has(dataSourceName) && typeof cfg.maxRows !== 'number') { realtimeMeta.set(dataSourceName, { mode: 'append', maxRows: 0, appended: [], pending: 0 }); window.ManifestDataStore.setSourceState(dataSourceName, { realtimeOverflow: 0 }); return; } const mode = cfg.mode === 'window' ? 'window' : 'append'; const fallback = Math.max(500, 2 * initialCount); let maxRows; if (typeof cfg.maxRows === 'number' && cfg.maxRows >= 0) { maxRows = cfg.maxRows; // explicit 0 = unbounded (legacy opt-in, append only) if (maxRows === 0 && mode === 'window') { console.warn(`[Manifest Data] realtime maxRows 0 contradicts window mode for "${dataSourceName}"; using the default cap`); maxRows = fallback; } } else if (mode === 'window') { // Window = the limit query, else the initial count; a computed 0 is no window, so default const windowSize = (typeof limitQuery === 'number' && limitQuery > 0) ? limitQuery : initialCount; maxRows = windowSize > 0 ? windowSize : fallback; } else { maxRows = fallback; } realtimeMeta.set(dataSourceName, { mode, maxRows, appended: [], pending: 0 }); window.ManifestDataStore.setSourceState(dataSourceName, { realtimeOverflow: 0 }); } // Active $query per source (manifest-format): realtime matches, orders and // server-filters by it until the next default load replaces the rows const activeQueries = new Map(); const awaitingQueries = new Set(); // sources with a $query waiting for auth to settle const queryIntents = new Map(); // a $query in flight for a source, { queries } const deferredLoads = new Set(); // source:locale keys of in-flight loads that deferred to a $query const realtimeBinds = new Map(); // Map function realtimeQueriesFor(dataSourceName, defaults) { return activeQueries.has(dataSourceName) ? activeQueries.get(dataSourceName) : defaults; } // [['orderDesc', 'n'], ...] → [['n', -1], ...]; orderRandom has no stable position function sortSpec(queries) { if (!Array.isArray(queries)) return null; if (queries.some(q => Array.isArray(q) && q[0] === 'orderRandom')) return null; const order = queries .filter(q => Array.isArray(q) && (q[0] === 'orderAsc' || q[0] === 'orderDesc') && typeof q[1] === 'string') .map(q => [q[1], q[0] === 'orderAsc' ? 1 : -1]); return order.length ? order : null; } function rebindLive(dataSourceName) { const bind = realtimeBinds.get(dataSourceName); if (bind?.mode !== 'all') return; Promise.resolve().then(bind.rebind).catch(error => console.error(`[Manifest Data] Realtime rebind failed for "${dataSourceName}":`, error)); } // $query landing: realtime follows the new filter set (caps reset to its result) function setActiveQuery(dataSourceName, queries, rowCount) { const list = Array.isArray(queries) ? queries : []; activeQueries.set(dataSourceName, list); const bind = realtimeBinds.get(dataSourceName); if (!bind) return; const limitQ = list.find(q => Array.isArray(q) && q[0] === 'limit'); configureRealtimeMeta(dataSourceName, bind.config, rowCount || 0, limitQ ? limitQ[1] : null); rebindLive(dataSourceName); } // Default rows landed: back to the manifest queries (caps sized to those rows) function clearActiveQuery(dataSourceName, rowCount) { if (!activeQueries.delete(dataSourceName)) return; const bind = realtimeBinds.get(dataSourceName); if (bind) configureRealtimeMeta(dataSourceName, bind.config, rowCount || 0, bind.defaultLimit); rebindLive(dataSourceName); } // The manifest entry for a source, synchronously (the loader has it by the time rows exist) function sourceConfig(dataSourceName) { return (window.ManifestComponentsRegistry?.manifest || window.__manifestLoaded)?.data?.[dataSourceName] || null; } // The sort a local row should follow: the active $query's order, else the defaults' function orderFor(dataSourceName) { const dataSource = sourceConfig(dataSourceName); return dataSource ? sortSpec(pagedFilters(dataSourceName, dataSource)) : null; } // Would this row belong in the source's current read (active $query, else defaults)? // Used for local placeholders; unevaluable filters count as a match function rowFitsSource(dataSourceName, row) { const dataSource = sourceConfig(dataSourceName); if (!dataSource || typeof dataSource !== 'object') return true; const queriesConfig = window.ManifestDataConfig?.getQueries?.(dataSource); const defaults = queriesConfig ? (queriesConfig.default || queriesConfig) : []; return eventMatchesQueries(row, realtimeQueriesFor(dataSourceName, Array.isArray(defaults) ? defaults : [])); } // Source reset (identity/scope) or torn down: nothing of the old binding carries over function forgetLiveSource(dataSourceName) { activeQueries.delete(dataSourceName); queryIntents.delete(dataSourceName); pagingState.delete(dataSourceName); catchUpTargets.delete(dataSourceName); realtimeBinds.delete(dataSourceName); } // Load retry: transient failures (network, 5xx, 408/429, an SDK call that dies mid-blip) // retry with backoff before $error shows. `retry: false` | `{ attempts, delay }` per source const RETRY_DEFAULT = { attempts: 3, delay: 500 }; function retryPolicy(dataSource) { const r = dataSource && typeof dataSource === 'object' ? dataSource.retry : undefined; if (r === false || r === 0) return { attempts: 0, delay: 0 }; if (r && typeof r === 'object') { return { attempts: Number.isFinite(r.attempts) && r.attempts >= 0 ? Math.floor(r.attempts) : RETRY_DEFAULT.attempts, delay: Number.isFinite(r.delay) && r.delay >= 0 ? r.delay : RETRY_DEFAULT.delay }; } return RETRY_DEFAULT; } function isTransient(error) { // Offline: the `online` catch-up refetches, so retrying now only delays $error if (typeof navigator !== 'undefined' && navigator.onLine === false) return false; const code = error?.code ?? error?.status ?? error?.response?.code; if (typeof code === 'number' && code > 0) return code >= 500 || code === 408 || code === 429; // fetch network failure, or the SDK reading a response that never came — not config mistakes return error?.name === 'TypeError' && /fetch|network|load failed|headers/i.test(String(error.message || '')); } // Run a read, retrying transient failures with exponential backoff (delay, 2×, 4×…, jittered); // stops early once isCurrent() is false (a newer read or identity took over) async function withRetry(dataSource, fn, isCurrent = () => true) { const { attempts, delay } = retryPolicy(dataSource); for (let attempt = 0; ; attempt++) { try { return await fn(); } catch (error) { if (attempt >= attempts || !isTransient(error) || !isCurrent()) throw error; const wait = delay * 2 ** attempt * (0.75 + Math.random() * 0.5); await new Promise(resolve => setTimeout(resolve, wait)); if (!isCurrent()) throw error; } } } // Paged sources: `paging: "all" | "window" | { mode, size, max }` // all: every page up to `max` rows; window: `size` rows, `$more()` appends the next page. // The cursor is the last row the server sent (never a local or moved row), with its // sort values as of that page: the boundary between loaded and not-yet-loaded rows. const PAGED_WINDOW_QUERIES = new Set(['limit', 'offset', 'cursorAfter', 'cursorBefore']); const COUNT_CEILING = 5000; // Appwrite's default count cap const PAGE_SIZE_CAP = 4999; // a page asks for one extra row; Appwrite's limit is 5000 const pagingState = new Map(); // Map const catchUpTargets = new Map(); // Map const moreInFlight = new Map(); // Map — one $more() per source at a time const moreQueued = new Set(); // $more() asked while a read was in flight: runs when it lands function pagingSpec(dataSource) { const p = dataSource && typeof dataSource === 'object' ? dataSource.paging : null; const cfg = typeof p === 'string' ? { mode: p } : (p && typeof p === 'object' ? p : null); if (!cfg || (cfg.mode !== 'all' && cfg.mode !== 'window')) return null; const size = Number(cfg.size) > 0 ? Math.min(PAGE_SIZE_CAP, Math.floor(Number(cfg.size))) : 100; const max = Number(cfg.max) > 0 ? Math.floor(Number(cfg.max)) : 5000; return { mode: cfg.mode, size, max }; } function stripPageWindow(queries) { return (Array.isArray(queries) ? queries : []).filter(q => !(Array.isArray(q) && PAGED_WINDOW_QUERIES.has(q[0]))); } // The filters a paged source currently reads: the active $query, else its defaults function pagedFilters(dataSourceName, dataSource) { const queriesConfig = window.ManifestDataConfig.getQueries(dataSource); return activeQueries.get(dataSourceName) || (queriesConfig ? (queriesConfig.default || queriesConfig) : []); } // Fetch pages of a table: `want` rows from `after` (a row $id), `size` per request, each // asking for one extra row so "more" is exact. isCurrent() false stops the walk. // Returns { rows, total, hasMore } or null when queries can't resolve yet (auth) async function fetchPagedRows(dataSourceName, filters, { want, after = null, isCurrent = () => true } = {}) { const manifest = await window.ManifestDataConfig.ensureManifest(); const dataSource = manifest?.data?.[dataSourceName]; const spec = pagingSpec(dataSource); const appwriteConfig = await window.ManifestDataConfig.getAppwriteConfig(dataSource); const tableId = window.ManifestDataConfig.getAppwriteTableId(dataSource); if (!spec || !appwriteConfig || !tableId) throw new Error(`[Manifest Data] "${dataSourceName}" is not a paged table source`); const scope = window.ManifestDataConfig.getScope(dataSource); const scopeColumns = window.ManifestDataConfig.getScopeColumns(dataSource); const base = await window.ManifestDataQueries.buildAppwriteQueries(stripPageWindow(filters), scope, scopeColumns); if (base === null) return null; const Query = window.Appwrite.Query; const requireAuth = requiresIdentity(dataSource); const limit = Math.max(1, want || spec.size); const rows = []; let total = null; let hasMore = false; let cursor = after; while (rows.length < limit) { const n = Math.min(spec.size, limit - rows.length); const pageQueries = [...base, ...(cursor ? [Query.cursorAfter(cursor)] : []), Query.limit(n + 1)]; const page = await withRetry(dataSource, () => window.ManifestDataAppwrite.loadTablePage( appwriteConfig.databaseId, tableId, pageQueries, { requireAuth } ), isCurrent); if (total === null) total = page.total; const got = page.rows.slice(0, n); rows.push(...got); hasMore = page.rows.length > n; if (!hasMore || !got.length || !isCurrent()) break; cursor = got[got.length - 1].$id; } return { rows, total, hasMore }; } // A page landed: move the cursor to its last server row and publish $hasMore / $total. // append: a $more() page; otherwise the window restarted (load, $query, catch-up) function setPagingState(dataSourceName, page, { append = false, filters = null } = {}) { const prev = pagingState.get(dataSourceName) || {}; const spec = page.spec || prev.spec; const order = filters ? sortSpec(filters) : (prev.order || null); const loaded = (append ? (prev.loaded || 0) : 0) + page.rows.length; const last = page.rows.length ? page.rows[page.rows.length - 1] : (append ? null : undefined); const cursor = last ? last.$id : (append ? prev.cursor : null); const boundary = last ? Object.fromEntries([['$id', last.$id], ...(order || []).map(([key]) => [key, last[key]])]) : (append ? prev.boundary : null); const max = spec ? spec.max : Infinity; const hasMore = !!page.hasMore && loaded < max; const total = page.total !== undefined ? page.total : prev.total; pagingState.set(dataSourceName, { spec, hasMore, total, loaded, cursor, boundary, order }); window.ManifestDataStore.setSourceState(dataSourceName, { hasMore, total: typeof total === 'number' ? total : null, totalCapped: typeof total === 'number' && total >= COUNT_CEILING }); if (!append && moreQueued.delete(dataSourceName) && hasMore) setTimeout(() => loadMore(dataSourceName).catch(() => {}), 0); } // Rows a paged load should fetch: the window size, or (all) the cap; a catch-up keeps what is held function pagedWant(dataSourceName, spec) { const keep = catchUpTargets.get(dataSourceName) || 0; catchUpTargets.delete(dataSourceName); return spec.mode === 'all' ? spec.max : Math.min(spec.max, Math.max(spec.size, keep)); } // $more(): the next page after the cursor. One at a time; while a load or $query is in // flight it waits for that to land (its window replaces the rows), then continues function loadMore(dataSourceName) { if (moreInFlight.has(dataSourceName)) return moreInFlight.get(dataSourceName); const run = loadMoreOnce(dataSourceName).finally(() => moreInFlight.delete(dataSourceName)); moreInFlight.set(dataSourceName, run); return run; } // Overtaken by a load or $query: run again once its window has landed (now, if it has) function requeueMore(dataSourceName) { if (window.ManifestDataStore.readsInFlight(dataSourceName)) { moreQueued.add(dataSourceName); return; } setTimeout(() => loadMore(dataSourceName).catch(() => {}), 0); } async function loadMoreOnce(dataSourceName) { const { currentRead, readsInFlight, sourceGeneration, landRows, setSourceState } = window.ManifestDataStore; const read = currentRead(dataSourceName); const generation = sourceGeneration(dataSourceName); const manifest = await window.ManifestDataConfig.ensureManifest(); const dataSource = manifest?.data?.[dataSourceName]; const spec = pagingSpec(dataSource); if (!spec) throw new Error(`[Manifest Data] "${dataSourceName}" $more: set "paging" on the source`); if (readsInFlight(dataSourceName)) { moreQueued.add(dataSourceName); return 0; } const state = pagingState.get(dataSourceName); if (!state?.hasMore || !state.cursor) return 0; const isCurrent = () => currentRead(dataSourceName) === read && sourceGeneration(dataSourceName) === generation && !readsInFlight(dataSourceName); const want = Math.min(spec.size, spec.max - state.loaded); if (want <= 0) return 0; const filters = pagedFilters(dataSourceName, dataSource); setSourceState(dataSourceName, { loading: true }); try { let page; try { page = await fetchPagedRows(dataSourceName, filters, { want, after: state.cursor, isCurrent }); } catch (error) { const status = error?.code ?? error?.response?.code; if (!isCurrent()) { requeueMore(dataSourceName); return 0; } if (status !== 400 && status !== 404) throw error; // The cursor row is gone (deleted since): refetch everything held plus one page catchUpTargets.set(dataSourceName, state.loaded + want); await reloadDataSource(dataSourceName); return 0; } // Overtaken by a load or $query: its window replaces the rows, then this runs again if (!page || !isCurrent()) { if (page) requeueMore(dataSourceName); return 0; } await landRows(dataSourceName, page.rows, { mode: 'append', generation, readToken: read, order: state.order || undefined }); setPagingState(dataSourceName, { ...page, spec }, { append: true }); return page.rows.length; } finally { if (!readsInFlight(dataSourceName)) setSourceState(dataSourceName, { loading: false }); } } // Is this row past the loaded boundary? While more pages exist, such rows arrive with // $more(), not by realtime or a local add. A tie with the boundary counts as inside: if // the server puts it later, its page merges it by $id — never a row lost to the cursor function beyondLoaded(dataSourceName, row) { const state = pagingState.get(dataSourceName); if (!state?.hasMore || !state.boundary) return false; if (!state.order) return true; // unsorted: server order is creation order, new rows come last return window.ManifestDataStore.compareBy(state.order)(row, state.boundary) > 0; } // Events not applied since the last load — $x..$realtimeOverflow function bumpRealtimeOverflow(dataSourceName) { const state = Alpine.store('data')?.[`_${dataSourceName}_state`]; window.ManifestDataStore.setSourceState(dataSourceName, { realtimeOverflow: (state?.realtimeOverflow || 0) + 1 }); } // Append under the cap. 'window' evicts the oldest realtime-appended row first // (never an initially-loaded row); otherwise the event counts in $realtimeOverflow. function realtimeAppend(dataSourceName, row, currentRows, generation, order) { const { landRows, landRemove } = window.ManifestDataStore; const meta = realtimeMeta.get(dataSourceName); if (!meta || meta.maxRows === 0) { if (meta) meta.appended.push(row.$id); landRows(dataSourceName, [row], { mode: 'append', generation, order }); return; } const len = currentRows.length + meta.pending; if (len >= meta.maxRows) { if (meta.mode !== 'window') { bumpRealtimeOverflow(dataSourceName); return; } let evicted = null; for (let i = 0; i < meta.appended.length; i++) { // Oldest appended row still landed; pending (unflushed) ids stay tracked if (currentRows.some(r => r && r.$id === meta.appended[i])) { evicted = meta.appended.splice(i, 1)[0]; break; } } if (evicted === null) { bumpRealtimeOverflow(dataSourceName); return; } landRemove(dataSourceName, [evicted], { generation }); } meta.pending++; meta.appended.push(row.$id); landRows(dataSourceName, [row], { mode: 'append', generation, order }) .then(() => { meta.pending = Math.max(0, meta.pending - 1); }); } function forgetRealtimeRow(dataSourceName, id) { const meta = realtimeMeta.get(dataSourceName); if (!meta) return; const i = meta.appended.indexOf(id); if (i !== -1) meta.appended.splice(i, 1); } // realtime.serverFilter → mode: 'scope' (default) | 'all' (alias true) | null (false: no server filtering) function serverFilterMode(realtimeConfig) { const sf = (realtimeConfig && typeof realtimeConfig === 'object') ? realtimeConfig.serverFilter : undefined; if (sf === false) return null; return (sf === 'all' || sf === true) ? 'all' : 'scope'; } // Query-aware event filter: the source's own queries, evaluated client-side // (unevaluable → match; see rowMatchesQueries) function eventMatchesQueries(row, queriesConfig) { const matcher = window.ManifestDataQueries?.rowMatchesQueries; return matcher ? matcher(row, queriesConfig) : true; } // Handle real-time events for database tables async function handleTableRealtimeEvent(dataSourceName, databaseId, tableId, scope, scopeColumns, eventType, payload, generation, queriesConfig) { // Deduplicate events (per source: shared-channel peers each process once) const eventKey = `${dataSourceName}|${getEventKey(eventType, payload)}`; if (isEventProcessed(eventKey)) { return; } markEventProcessed(eventKey); const store = Alpine.store('data'); if (!store) { return; } const currentRows = store[dataSourceName]; // Handle realtime events if (!Array.isArray(currentRows)) { return; } // Network landings: coalesced per frame (landRows upserts by $id), never the sync mutation path const { landRows, landRemove } = window.ManifestDataStore; const order = sortSpec(queriesConfig); if (eventType === 'create') { const row = payload?.$id ? payload : (payload?.row || payload); if (row && row.$id) { // Scope AND queries must match before the row lands const rowMatchesScope = await checkRowMatchesScope(row, scope, scopeColumns); if (rowMatchesScope && eventMatchesQueries(row, queriesConfig)) { if (currentRows.find(r => r.$id === row.$id)) { // Echo of a row already held (optimistic create): merge, never counts as growth landRows(dataSourceName, [row], { mode: 'append', generation, order }); } else if (!beyondLoaded(dataSourceName, row)) { realtimeAppend(dataSourceName, row, currentRows, generation, order); } } } else { console.warn('[Manifest Data] Invalid row payload in create event:', payload); } } else if (eventType === 'update') { const row = payload?.$id ? payload : (payload?.row || payload); if (row && row.$id) { const existingRow = currentRows.find(r => r.$id === row.$id); const rowMatchesScope = await checkRowMatchesScope(row, scope, scopeColumns); if (!rowMatchesScope || !eventMatchesQueries(row, queriesConfig)) { // Row stopped matching scope or queries, remove it if (existingRow) { landRemove(dataSourceName, [row.$id], { generation }); forgetRealtimeRow(dataSourceName, row.$id); } return; } if (!existingRow) { // Row not in list, but matches now - add it (capped like a create) if (!beyondLoaded(dataSourceName, row)) realtimeAppend(dataSourceName, row, currentRows, generation, order); return; } // A held row whose sort value moved past the loaded boundary leaves; its page brings it back const paging = pagingState.get(dataSourceName); const sortMoved = paging?.order?.some(([key]) => key in row && !window.ManifestDataStore.sameScalarOrList(existingRow[key], row[key])); if (sortMoved && row.$id !== paging.cursor && beyondLoaded(dataSourceName, row)) { landRemove(dataSourceName, [row.$id], { generation }); return; } // Most sources update unconditionally; projects-with-fileIds get // special handling to protect optimistic uploads (see below). const existingFileIds = existingRow?.fileIds || []; const incomingFileIds = row?.fileIds || []; const hasFileIds = existingFileIds.length > 0 || incomingFileIds.length > 0; const isProjectWithFiles = hasFileIds && dataSourceName === 'projects'; let shouldUpdate = true; if (isProjectWithFiles) { const existingUpdatedAt = existingRow?.$updatedAt || existingRow?.$sequence; const newUpdatedAt = row?.$updatedAt || row?.$sequence; const shouldUpdateByTimestamp = !newUpdatedAt || !existingUpdatedAt || newUpdatedAt !== existingUpdatedAt; if (!shouldUpdateByTimestamp) { shouldUpdate = false; // identical timestamps → no-op } else { const existingFileIdsSet = new Set(existingFileIds); const incomingFileIdsSet = new Set(incomingFileIds); const isSuperset = incomingFileIds.every(id => existingFileIdsSet.has(id)) && incomingFileIds.length > existingFileIds.length; const isMissingFiles = existingFileIds.some(id => !incomingFileIdsSet.has(id)); const timestampDiff = newUpdatedAt > existingUpdatedAt ? (new Date(newUpdatedAt) - new Date(existingUpdatedAt)) : (new Date(existingUpdatedAt) - new Date(newUpdatedAt)); const isDefinitelyNewer = timestampDiff > 1000; // ms // Incoming missing files + not clearly newer = stale event // racing an optimistic update; ignore it to protect the upload. if (isMissingFiles && !isDefinitelyNewer) { console.warn('[Manifest Data] Ignoring stale realtime update (protecting optimistic update):', { projectId: row.$id, existingFileIds: existingFileIds, incomingFileIds: incomingFileIds, existingFileIdsCount: existingFileIds.length, incomingFileIdsCount: incomingFileIds.length, existingUpdatedAt, newUpdatedAt, timestampDiff, isMissingFiles, isDefinitelyNewer, reason: 'Incoming data missing files that exist in store - likely stale realtime event' }); shouldUpdate = false; } } } if (shouldUpdate) { // Check if fileIds changed (for projects with linked files) const fileIdsChanged = isProjectWithFiles && JSON.stringify(existingFileIds) !== JSON.stringify(incomingFileIds); landRows(dataSourceName, [row], { mode: 'append', generation, order }); // Emit custom event for project file updates so UI can refresh if (fileIdsChanged && dataSourceName === 'projects') { window.dispatchEvent(new CustomEvent('manifest:project-files-updated', { detail: { projectId: row.$id, fileIds: row.fileIds } })); } } } } else if (eventType === 'delete') { const rowId = payload?.$id || payload?.row?.$id || payload?.rowId || payload; if (rowId) { landRemove(dataSourceName, [rowId.$id || rowId], { generation }); forgetRealtimeRow(dataSourceName, rowId.$id || rowId); } } } // Check if a database row matches the current scope async function checkRowMatchesScope(row, scope, scopeColumns) { if (!scope || !row) { return true; // No scope, allow it } const cols = scopeColumns || { team: 'teamId', user: 'userId' }; const authStore = typeof Alpine !== 'undefined' ? Alpine.store('auth') : null; if (!authStore) { return true; } const scopeArray = Array.isArray(scope) ? scope : [scope]; const hasUserScope = scopeArray.includes('user'); const hasTeamScope = scopeArray.includes('team'); const hasTeamsScope = scopeArray.includes('teams'); // Check user scope if (hasUserScope) { const user = authStore.user; const userId = user?.$id || user?.id; if (userId && row[cols.user] === userId) { return true; // Matches user scope } } // Check team scope (singular - currentTeam) if (hasTeamScope) { const currentTeamId = authStore.currentTeam?.$id || authStore.currentTeam?.id; if (currentTeamId && row[cols.team] === currentTeamId) { return true; // Matches current team scope } } // Check teams scope (plural - all teams) if (hasTeamsScope) { const teams = authStore.teams || []; const teamIds = teams.map(t => t.$id || t.id).filter(id => id); if (teamIds.includes(row[cols.team])) { return true; // Matches one of user's teams } } // For dual scopes like ["user", "team"], if either matches, return true // This matches the OR query logic if (hasUserScope && (hasTeamScope || hasTeamsScope)) { // Already checked above, if we get here, it doesn't match return false; } // If scope is defined but doesn't match, return false // If no scope restrictions, return true return !hasUserScope && !hasTeamScope && !hasTeamsScope; } // Check if a file matches the current scope (for real-time events) async function checkFileMatchesScope(file, scope) { if (!scope || !file || !file.$permissions) { return true; // No scope or no permissions, allow it } // Use the same scope filtering logic as filterFilesByScope const authStore = typeof Alpine !== 'undefined' ? Alpine.store('auth') : null; if (!authStore) { return true; } const scopeArray = Array.isArray(scope) ? scope : [scope]; const hasUserScope = scopeArray.includes('user'); const hasTeamScope = scopeArray.includes('team'); const hasTeamsScope = scopeArray.includes('teams'); const Permission = window.Appwrite?.Permission; const Role = window.Appwrite?.Role; if (!Permission || !Role) { return true; } const expectedPermissions = []; if (hasUserScope) { const user = authStore.user; const userId = user?.$id || user?.id; if (userId) { expectedPermissions.push(Permission.read(Role.user(userId))); } } if (hasTeamScope) { const currentTeam = authStore.currentTeam; const teamId = currentTeam?.$id || currentTeam?.id; if (teamId) { expectedPermissions.push(Permission.read(Role.team(teamId))); } else { return false; // No current team, file doesn't match } } if (hasTeamsScope) { const teams = authStore.teams || []; teams.forEach(team => { const teamId = team.$id || team.id; if (teamId) { expectedPermissions.push(Permission.read(Role.team(teamId))); } }); } if (expectedPermissions.length === 0) { return true; // No scope restrictions } // Check if file has any of the expected permissions const filePermissions = file.$permissions || []; return expectedPermissions.some(expectedPerm => { const expectedPermString = typeof expectedPerm === 'string' ? expectedPerm : String(expectedPerm); return filePermissions.some(filePerm => { const filePermString = typeof filePerm === 'string' ? filePerm : String(filePerm); return filePermString === expectedPermString; }); }); } // Rows already in the store (array or object) — a reload keeps them live function hasLiveRows(dataSourceName) { const store = typeof Alpine !== 'undefined' ? Alpine.store('data') : null; const raw = store ? (window.ManifestDataStore?.rawOf?.(store) || store) : null; const current = raw ? raw[dataSourceName] : undefined; return current !== null && current !== undefined; } function liveLocale() { return (typeof document !== 'undefined' && document.documentElement?.lang) || (typeof Alpine !== 'undefined' && Alpine.store('locale')?.current) || 'en'; } // Load dataSource data. options.reload: bypass the memory cache and refetch; // existing rows stay live ($loading only), fresh rows merge by $id. async function loadDataSource(dataSourceName, locale = 'en', options = {}) { locale = locale || 'en'; const cacheKey = `${dataSourceName}:${locale}`; const { dataSourceCache, loadingPromises, isInitializing, updateStore, landRows, setSourceState, runDeduped, sourceGeneration } = window.ManifestDataStore; // Memory cache (this page-load's fetches). Serving cached data is fine, but // writing an old locale to the live store would clobber a concurrent locale // switch — so guard the store write via the `_locale` stamp. // A $query in flight, or its rows showing: lazy reads defer to it (see below) const queryHolds = () => queryIntents.has(dataSourceName) || (activeQueries.has(dataSourceName) && hasLiveRows(dataSourceName)); if (!options.reload && dataSourceCache.has(cacheKey)) { const cachedData = dataSourceCache.get(cacheKey); if (queryHolds()) return cachedData; const live = (window.Alpine && Alpine.store('locale')?.current) || document.documentElement.lang || locale; const staleLocaleHit = locale !== live && !!(cachedData && cachedData._locale); if (!isInitializing && !staleLocaleHit) { // Landing (coalesced): resolves once the cached rows are visible await landRows(dataSourceName, cachedData, { mode: 'replace', loading: false, error: null, ready: true, fresh: true }); } return cachedData; } // An explicit reload never joins a load that deferred to a $query: it runs after it // It counts as issued now: a $query called after it still wins if (options.reload && deferredLoads.has(cacheKey) && loadingPromises.has(cacheKey)) { const issued = options.issuedRead ?? window.ManifestDataStore.beginRead?.(dataSourceName); if (options.issuedRead === undefined) queryIntents.delete(dataSourceName); return loadingPromises.get(cacheKey).catch(() => null) .then(() => loadDataSource(dataSourceName, locale, { ...options, issuedRead: issued })); } // In flight for this source+locale: share it (every entry path lands here); // joining makes it the latest read again if (loadingPromises.has(cacheKey)) { window.ManifestDataStore.adoptRead?.(dataSourceName, window.ManifestDataStore.loadReadTokens?.get(cacheKey)); return loadingPromises.get(cacheKey); } // Reads are ordered by call: a $query issued after this load wins over it // A lazy read while a $query is in flight, or while a $query's rows are showing, only binds // realtime: it neither outranks that $query nor lands default rows. An explicit reload does both. // (A listener that clears the rows first — locale, team — gets the defaults as before.) const deferred = !options.reload && queryHolds(); const deferToQuery = () => deferred && queryHolds(); const readToken = deferred ? undefined : (options.issuedRead ?? window.ManifestDataStore.beginRead?.(dataSourceName)); if (deferred) deferredLoads.add(cacheKey); if (options.reload && options.issuedRead === undefined) queryIntents.delete(dataSourceName); let pagedResult = null; window.ManifestDataStore.loadReadTokens?.set(cacheKey, readToken); // Loading state: rows already landed stay live; first-ever load clears const keepRows = hasLiveRows(dataSourceName); if (!isInitializing) { if (keepRows) setSourceState(dataSourceName, { loading: true, error: null }); else updateStore(dataSourceName, null, { loading: true, error: null, ready: false }); } // Scope reset (persistence) during this load → its result is discarded const generation = sourceGeneration ? sourceGeneration(dataSourceName) : 0; const superseded = () => sourceGeneration && sourceGeneration(dataSourceName) !== generation; // Unresolvable scope (signed out, or teamless): settle empty, not $loading forever; auth events reload. // A pending sign-in holds the source unsettled (one render-ready), bounded by its deadline. const settleUnresolved = (manifest) => { if (isInitializing || superseded()) return false; const wait = signInWaitMs(currentAuth()); if (wait > 0) { setTimeout(() => { const state = Alpine.store('data')?.[`_${dataSourceName}_state`]; if (state?.ready || superseded() || !authSettledSignedOut()) return; updateStore(dataSourceName, [], { loading: false, error: null, ready: true }); }, wait + 10); return false; } if (!authSettledUnresolvable(manifest)) return false; // Offline/unverified: restored rows of the last-known identity stay (logout and identity changes still reset) if (sessionUnverified(currentAuth()) && hasLiveRows(dataSourceName)) { setSourceState(dataSourceName, { loading: false, error: null, ready: true }); return true; } updateStore(dataSourceName, [], { loading: false, error: null, ready: true }); return true; }; const settled = () => window.ManifestDataStore.endRead?.(dataSourceName, readToken); const run = runDeduped(cacheKey, async () => { let landed = false; try { const manifest = await window.ManifestDataConfig.ensureManifest(); if (!manifest) { return null; } // Check both manifest.data and manifest.appwrite for data sources let dataSource = null; if (manifest.data?.[dataSourceName]) { dataSource = manifest.data[dataSourceName]; } else if (manifest.appwrite?.[dataSourceName]) { dataSource = manifest.appwrite[dataSourceName]; } if (!dataSource) { // Only return null for dataSources that are actually being accessed // This prevents warnings for test references that might exist in HTML return null; } // Get bucketId early to check if this is a bucket (needed for data enhancement) const bucketId = window.ManifestDataConfig.getAppwriteBucketId?.(dataSource) || null; let data; // Helper to get current locale function getCurrentLocale() { return document.documentElement.lang || (window.Alpine && Alpine.store('locale')?.current) || locale || 'en'; } // Auto-detect dataSource type based on structure if (typeof dataSource === 'string') { // Local file - load from filesystem (auto-detect format) // For CSV files, pass currentLocale so parser can use locale column if available const options = dataSource.endsWith('.csv') ? { currentLocale: getCurrentLocale() } : {}; try { data = await window.ManifestDataLoaders.loadLocalFile(dataSource, options); } catch (error) { console.error(`[Manifest Data] Failed to load local file "${dataSourceName}":`, error); throw error; } } else if (dataSource.locales) { // Single CSV file with multiple locale columns (all locales in one file) const options = { currentLocale: getCurrentLocale() }; data = await window.ManifestDataLoaders.loadLocalFile(dataSource.locales, options); } else if (dataSource.url) { // Cloud API - load from HTTP endpoint (read-only) // NOTE: Basic API support is in core for localization compatibility. // Full CRUD operations will be available via manifest.api.data.js plugin (planned). data = await withRetry(dataSource, () => window.ManifestDataAPI.loadFromAPI(dataSource), () => !superseded()); } else if (window.ManifestDataConfig.isAppwriteCollection(dataSource)) { // Appwrite collection or bucket const appwriteConfig = await window.ManifestDataConfig.getAppwriteConfig(dataSource); if (!appwriteConfig) { console.warn(`[Manifest Data] Invalid Appwrite configuration for "${dataSourceName}"`); return null; } const tableId = window.ManifestDataConfig.getAppwriteTableId(dataSource); // bucketId already defined above const scope = window.ManifestDataConfig.getScope(dataSource); const scopeColumns = window.ManifestDataConfig.getScopeColumns(dataSource); const queriesConfig = window.ManifestDataConfig.getQueries(dataSource); if (tableId) { // Load from Appwrite table (TablesDB); paged sources fetch their window or walk every page const spec = pagingSpec(dataSource); if (spec && !pagingState.has(dataSourceName)) pagingState.set(dataSourceName, { hasMore: false, total: null }); const defaults = queriesConfig ? (queriesConfig.default || queriesConfig) : []; const paged = spec ? await fetchPagedRows(dataSourceName, defaults, { want: pagedWant(dataSourceName, spec), isCurrent: () => !superseded() && window.ManifestDataStore.isLatestRead(dataSourceName, readToken) }) : undefined; if (paged) pagedResult = { ...paged, spec, filters: defaults }; const queries = spec ? (paged ? [] : null) : await window.ManifestDataQueries.buildAppwriteQueries(defaults, scope, scopeColumns); // Not ready (auth/scope unresolved): skip this read, retry on an auth event if (queries === null) { scheduleAuthRetry(dataSourceName, locale); if (settleUnresolved(manifest)) landed = true; return null; } // Log auth state for debugging const authStore = typeof Alpine !== 'undefined' ? Alpine.store('auth') : null; const teamIds = authStore?.teams?.map(t => t.$id || t.id) || []; data = paged ? paged.rows : await withRetry(dataSource, () => window.ManifestDataAppwrite.loadTableRows( appwriteConfig.databaseId, tableId, queries, { requireAuth: requiresIdentity(dataSource) } ), () => !superseded()); if (superseded()) { landed = true; return null; } // Subscribe to real-time updates for this table (events from a // superseded identity drop); realtime: false opts the source out if (dataSource.realtime !== false && window.ManifestDataRealtime && window.ManifestDataRealtime.subscribeToTable) { const rtQueries = Array.isArray(queriesConfig?.default || queriesConfig) ? (queriesConfig.default || queriesConfig) : []; const limitQ = rtQueries.find(q => Array.isArray(q) && q[0] === 'limit'); if (!activeQueries.has(dataSourceName) || !realtimeMeta.has(dataSourceName)) { configureRealtimeMeta(dataSourceName, dataSource.realtime, Array.isArray(data) ? data.length : 0, limitQ ? limitQ[1] : null); } // Events server-filtered where the SDK supports realtime queries; the client // matcher below still runs. serverFilter: 'scope' (default) | 'all' (alias true) | false const rtMode = serverFilterMode(dataSource.realtime); const rtFilterSpec = rtMode ? { get queriesConfig() { return realtimeQueriesFor(dataSourceName, rtQueries); }, scope, scopeColumns, mode: rtMode } : null; const subscribe = () => window.ManifestDataRealtime.subscribeToTable( dataSourceName, appwriteConfig.databaseId, tableId, scope, async (eventType, payload) => { await handleTableRealtimeEvent(dataSourceName, appwriteConfig.databaseId, tableId, scope, scopeColumns, eventType, payload, generation, realtimeQueriesFor(dataSourceName, rtQueries)); }, () => !superseded(), rtFilterSpec ); realtimeBinds.set(dataSourceName, { config: dataSource.realtime, mode: rtMode, rebind: subscribe, defaultLimit: limitQ ? limitQ[1] : null }); const unsubscribe = await subscribe(); if (superseded()) { dropSubscription(dataSourceName, unsubscribe); landed = true; return null; } } } else if (bucketId) { // Load from Appwrite storage bucket // Note: Storage buckets don't support query-based scope filtering (no userId/teamId columns) // Appwrite automatically filters by permissions, but returns ALL files user has access to // We need to filter client-side based on scope (current team) to match database behavior const queries = queriesConfig ? await window.ManifestDataQueries.buildAppwriteQueries(queriesConfig.default || queriesConfig, null) : await window.ManifestDataQueries.buildAppwriteQueries([], null); // Not ready (a $auth. arg in queriesConfig unresolved): skip, retry on an auth event if (queries === null) { scheduleAuthRetry(dataSourceName, locale); if (settleUnresolved(manifest)) landed = true; return null; } let files = await withRetry(dataSource, () => window.ManifestDataAppwrite.listBucketFiles(bucketId, queries), () => !superseded()); // Ensure files is always an array if (!Array.isArray(files)) { console.warn(`[Manifest Data] listBucketFiles returned non-array for "${dataSourceName}":`, files); files = []; } // Filter files by scope if scope is defined (client-side filtering) // This matches the database team scope behavior if (scope && files && Array.isArray(files) && files.length > 0) { const originalCount = files.length; files = await filterFilesByScope(files, scope); } data = files; if (superseded()) { landed = true; return null; } // Subscribe to real-time updates for this bucket (events from a // superseded identity drop); realtime: false opts the source out if (dataSource.realtime !== false && window.ManifestDataRealtime && window.ManifestDataRealtime.subscribeToStorageBucket) { const rtQueries = Array.isArray(queriesConfig?.default || queriesConfig) ? (queriesConfig.default || queriesConfig) : []; const limitQ = rtQueries.find(q => Array.isArray(q) && q[0] === 'limit'); configureRealtimeMeta(dataSourceName, dataSource.realtime, Array.isArray(data) ? data.length : 0, limitQ ? limitQ[1] : null); // Buckets have no scope columns: server filtering only under serverFilter 'all' const rtMode = serverFilterMode(dataSource.realtime); const rtFilterSpec = rtMode ? { queriesConfig: rtQueries, scope: null, mode: rtMode } : null; const unsubscribe = await window.ManifestDataRealtime.subscribeToStorageBucket( dataSourceName, bucketId, scope, async (eventType, payload) => { if (superseded()) return; await handleStorageRealtimeEvent(dataSourceName, bucketId, scope, eventType, payload, generation, rtQueries); }, () => !superseded(), rtFilterSpec ); if (superseded()) { dropSubscription(dataSourceName, unsubscribe); landed = true; return null; } } } else { console.warn(`[Manifest Data] Appwrite data source "${dataSourceName}" missing tableId or bucketId`); return null; } } else if (dataSource[locale]) { // Localized dataSource - load current locale const localizedDataSource = dataSource[locale]; let currentLocaleData = null; try { if (typeof localizedDataSource === 'string') { // Localized local file (separate file per locale) // For CSV in localized structure, don't pass locale - each file is already locale-specific currentLocaleData = await window.ManifestDataLoaders.loadLocalFile(localizedDataSource); } else if (localizedDataSource.url) { // Localized cloud API currentLocaleData = await withRetry(dataSource, () => window.ManifestDataAPI.loadFromAPI(localizedDataSource), () => !superseded()); } else { console.warn(`[Manifest Data] No valid source found for dataSource "${dataSourceName}" in locale "${locale}"`); return null; } } catch (error) { // Current locale file is missing or failed to load console.warn(`[Manifest Data] Failed to load locale "${locale}" for "${dataSourceName}":`, error.message); currentLocaleData = null; // Will fallback to default } // Load default locale for fallback (if different from current locale, or if current failed) const defaultLocale = window.ManifestDataConfig.getDefaultLocale(dataSource); if (defaultLocale && (defaultLocale !== locale || !currentLocaleData)) { const defaultLocaleDataSource = dataSource[defaultLocale]; let fallbackData = null; try { if (typeof defaultLocaleDataSource === 'string') { // For CSV in localized structure, don't pass locale - each file is already locale-specific fallbackData = await window.ManifestDataLoaders.loadLocalFile(defaultLocaleDataSource); } else if (defaultLocaleDataSource?.url) { fallbackData = await withRetry(dataSource, () => window.ManifestDataAPI.loadFromAPI(defaultLocaleDataSource), () => !superseded()); } // Merge fallback data with current locale data (current takes precedence if it exists) if (fallbackData) { if (currentLocaleData) { data = window.ManifestDataLoaders.deepMergeWithFallback(currentLocaleData, fallbackData); } else { // Current locale file is missing, use fallback as primary data = fallbackData; } } else { data = currentLocaleData; } } catch (error) { // If fallback also fails, use current locale data (or null if that also failed) console.warn(`[Manifest Data] Failed to load fallback locale "${defaultLocale}" for "${dataSourceName}":`, error.message); data = currentLocaleData; } } else { // No default locale or same as current, just use current (or null if it failed) data = currentLocaleData; } } else { console.warn(`[Manifest Data] No valid source found for dataSource "${dataSourceName}"`); return null; } // Enhance data with metadata let enhancedData; const sourceType = typeof dataSource === 'string' ? 'local' : (dataSource.url ? 'api' : 'local'); const sourcePath = typeof dataSource === 'string' ? dataSource : (dataSource.url || ''); // For buckets, ensure data is always an array if (bucketId && !Array.isArray(data)) { console.warn(`[Manifest Data] Bucket "${dataSourceName}" returned non-array data:`, data); data = []; } if (Array.isArray(data)) { // Only enhance objects in arrays, not primitives enhancedData = data.map(item => { if (item !== null && typeof item === 'object') { return { ...item, contentType: dataSourceName, _loadedFrom: sourcePath, _sourceType: sourceType, _locale: locale }; } else { // For primitives, return as-is (no enhancement) return item; } }); } else if (data !== null && data !== undefined && typeof data === 'object') { enhancedData = { ...data, contentType: dataSourceName, _loadedFrom: sourcePath, _sourceType: sourceType, _locale: locale }; } else { // For null, undefined, or primitives, use data as-is enhancedData = data; } // Ensure enhancedData is an array for bucket data sources if (bucketId && !Array.isArray(enhancedData)) { console.warn(`[Manifest Data] Bucket "${dataSourceName}" enhancedData is not an array:`, enhancedData); enhancedData = []; } if (superseded()) { landed = true; return null; } // A $query issued since this load began (or one it deferred to): its rows stand, this result never lands if (deferToQuery() || (window.ManifestDataStore.isLatestRead && !window.ManifestDataStore.isLatestRead(dataSourceName, readToken))) { landed = true; if (!isInitializing) setSourceState(dataSourceName, { loading: false }); return enhancedData; } // Cache is always safe — the key carries this load's locale. dataSourceCache.set(cacheKey, enhancedData); // Stale-locale guard: if the locale changed mid-load, a localized // source's result is stale (the locale listener already reloaded the // right one). Non-localized sources still write — the listener never // reloads them, so skipping would orphan the initial load. const localeSensitive = !!(dataSource && typeof dataSource === 'object' && (dataSource.locales || dataSource[locale])); const liveLocale = (window.Alpine && Alpine.store('locale')?.current) || document.documentElement.lang || locale; const staleLocale = localeSensitive && liveLocale !== locale; // Network landing (coalesced per frame, merges by $id); resolves once visible if (!isInitializing && !staleLocale) { landed = true; clearActiveQuery(dataSourceName, Array.isArray(enhancedData) ? enhancedData.length : 0); if (pagedResult) setPagingState(dataSourceName, pagedResult, { filters: pagedResult.filters }); await landRows(dataSourceName, enhancedData, { mode: 'replace', loading: false, error: null, ready: true, fresh: true, generation, readToken }); } // Return unsealed version for our proxy system return enhancedData; } catch (error) { if (superseded()) { landed = true; return null; } // Error state (timestamped to prevent rapid retries); live rows stay if (!isInitializing) { landed = true; const errorMessage = error?.message || error?.toString() || `Failed to load dataSource "${dataSourceName}"`; if (hasLiveRows(dataSourceName)) { setSourceState(dataSourceName, { loading: false, error: errorMessage, errorTime: Date.now() }); } else if (error?.defaultValue !== undefined) { // API-URL first load failed: its defaultValue stands in (not fresh), never over live rows await landRows(dataSourceName, error.defaultValue, { mode: 'replace', loading: false, error: errorMessage, ready: true, fresh: false }); } else { updateStore(dataSourceName, null, { loading: false, error: errorMessage, ready: false, errorTime: Date.now() // Track when error occurred }); } } // Only log non-auth errors to reduce noise (401 is expected until user authenticates) const isAuthError = error?.code === 401 || error?.message?.includes('401') || error?.message?.includes('not authorized'); if (!isAuthError) { console.error(`[Manifest Data] Failed to load dataSource "${dataSourceName}":`, error); // Log the full error details for debugging if (error?.stack) { console.error(`[Manifest Data] Error stack for "${dataSourceName}":`, error.stack); } } return null; } finally { // Early exits (no source, stale locale) must not strand a live source in $loading if (!landed && keepRows && !isInitializing && !superseded()) setSourceState(dataSourceName, { loading: false }); } }); const done = () => { settled(); deferredLoads.delete(cacheKey); }; run.then(done, done); return run; } // $reload(): fetch again what the source shows — its active $query, else its default // load; a paged source keeps as many rows as it holds function reloadSource(dataSourceName) { if (pagingState.has(dataSourceName)) { const held = window.ManifestDataStore.rawOf(Alpine.store('data'))?.[dataSourceName]; catchUpTargets.set(dataSourceName, Array.isArray(held) ? held.length : 0); } const active = activeQueries.get(dataSourceName); const handler = active && window.ManifestDataProxiesAppwrite?.createAppwriteMethodsHandler?.(dataSourceName, reloadDataSource); return handler ? handler('$query', active) : reloadDataSource(dataSourceName); } // Resolves at the next auth change (sign-in settles, team switch) or after timeoutMs function waitForAuthChange(timeoutMs = 10000) { const events = ['manifest:auth:login', 'manifest:auth:initialized', 'manifest:auth:anonymous', 'manifest:auth:teams-loaded', 'manifest:auth:logout', 'manifest:auth:session-cleared']; return new Promise(resolve => { const done = () => { clearTimeout(timer); events.forEach(type => window.removeEventListener(type, done)); resolve(); }; const timer = setTimeout(done, timeoutMs); events.forEach(type => window.addEventListener(type, done)); }); } // Resolves once no read of this source is in flight (bounded); starts after a tick so // reloads that an event just kicked off are counted async function settledReads(dataSourceName, timeoutMs = 5000) { const until = Date.now() + timeoutMs; await new Promise(resolve => setTimeout(resolve, 0)); while (window.ManifestDataStore.readsInFlight(dataSourceName) && Date.now() < until) { await new Promise(resolve => setTimeout(resolve, 20)); } } // Reload: refetch past the memory cache; rows stay live and merge by $id function reloadDataSource(dataSourceName, locale) { return loadDataSource(dataSourceName, locale || liveLocale(), { reload: true }); } // Listen for URL changes to trigger reactivity function setupUrlChangeListeners() { let currentUrl = window.location.pathname; // Separate reactive object for route tracking (Alpine tracks it reliably) const routeTracker = Alpine.reactive ? Alpine.reactive({ currentUrl: window.location.pathname }) : { currentUrl: window.location.pathname }; // Expose routeTracker globally so createRouteProxy can access it if (!window.ManifestDataRouteTracker) { window.ManifestDataRouteTracker = routeTracker; } // Update store with current URL function updateCurrentUrl(newUrl) { if (newUrl !== currentUrl) { currentUrl = newUrl; const store = Alpine.store('data'); if (store && store._initialized) { // Use Object.assign so Alpine reliably tracks the change Object.assign(store, { _currentUrl: newUrl }); // Also update the reactive tracker (covers untracked store get traps) if (routeTracker) { routeTracker.currentUrl = newUrl; } const _ = store._currentUrl; // touch to force tracking // Event fallback for cases Alpine's auto-tracking might miss try { window.dispatchEvent(new CustomEvent('manifest:data-url-change', { detail: { url: newUrl } })); } catch (e) { console.warn('[Manifest Data] Failed to dispatch event:', e); } } else { console.warn('[Manifest Data] Store not initialized, cannot update _currentUrl:', { storeExists: !!store, initialized: store?._initialized }); } } } // Listen to router's route change event (primary integration point) window.addEventListener('manifest:route-change', (event) => { const newUrl = event.detail?.to ?? window.ManifestRoutingNavigation?.getCurrentRoute?.() ?? window.location.pathname; updateCurrentUrl(newUrl); // Flush route proxies after other listeners queue updates, so $x.*.$route() refreshes in place setTimeout(() => { if (window.ManifestDataRouteProxyUpdateQueue?.flushSync) { window.ManifestDataRouteProxyUpdateQueue.flushSync(); } }, 0); }); // Also listen for popstate (browser back/forward) window.addEventListener('popstate', () => { updateCurrentUrl(window.location.pathname); }); // Also listen for pushstate/replacestate (for SPA navigation) const originalPushState = history.pushState; const originalReplaceState = history.replaceState; history.pushState = function (...args) { originalPushState.apply(history, args); updateCurrentUrl(window.location.pathname); }; history.replaceState = function (...args) { originalReplaceState.apply(history, args); updateCurrentUrl(window.location.pathname); }; // Initialize with current URL updateCurrentUrl(window.location.pathname); } // Initialize plugin when either DOM is ready or Alpine is ready async function initializeDataSourcesPlugin() { const { initializeStore, setupLocaleChangeListener, setupTeamChangeListener, setIsInitializing, setInitializationComplete, updateStore, landRows } = window.ManifestDataStore; // Initialize empty data sources store initializeStore(); // Setup locale change listener setupLocaleChangeListener(); // Setup team change listener setupTeamChangeListener(); // Setup URL change listeners setupUrlChangeListeners(); setupAuthResetListener(); // Register $x magic method (only if Alpine is available) if (typeof Alpine !== 'undefined' && window.ManifestDataProxies) { window.ManifestDataProxies.registerXMagicMethod(loadDataSource); } else { // Wait for Alpine to load const checkAlpine = setInterval(() => { if (typeof Alpine !== 'undefined' && window.ManifestDataProxies) { window.ManifestDataProxies.registerXMagicMethod(loadDataSource); clearInterval(checkAlpine); } }, 10); // Timeout after 5 seconds setTimeout(() => { clearInterval(checkAlpine); if (typeof Alpine === 'undefined') { console.error('[Manifest Data] Alpine.js failed to load - $x magic method not registered'); } }, 5000); } // Export loadDataSource for use by team change listener // Catch-up: events missed while offline or asleep never arrive, so live sources // refetch (their active $query, else the default load) on reconnect or wake const CATCH_UP_HIDDEN_MS = 60000; let hiddenSince = document.hidden ? Date.now() : null; let catchUpTimer = null; const catchUpLiveSources = () => { clearTimeout(catchUpTimer); catchUpTimer = setTimeout(() => { for (const name of realtimeBinds.keys()) { Promise.resolve(reloadSource(name)).catch(() => { /* $error carries it */ }); } }, 250); }; window.addEventListener('online', catchUpLiveSources); document.addEventListener('visibilitychange', () => { if (document.hidden) { hiddenSince = Date.now(); return; } const away = hiddenSince !== null ? Date.now() - hiddenSince : 0; hiddenSince = null; if (away >= CATCH_UP_HIDDEN_MS) catchUpLiveSources(); }); window.ManifestDataMain = { loadDataSource, reloadDataSource, _loadDataSource: reloadDataSource, // Internal: every user is a reload-after-mutation filterFilesByScope, // Export for use by getFilesForEntry requiresIdentity, setActiveQuery, forgetLiveSource, reloadSource, waitForAuthChange, settledReads, awaitingQueries, noteQueryIntent: (dataSourceName, queries) => queryIntents.set(dataSourceName, queries), dropQueryIntent: (dataSourceName, queries) => { if (queryIntents.get(dataSourceName) === queries) queryIntents.delete(dataSourceName); }, withRetry, identityEpoch: () => identityEpoch, pagingSpec, fetchPagedRows, pagedWant, setPagingState, loadMore, beyondLoaded, orderFor, rowFitsSource, getActiveQuery: (dataSourceName) => activeQueries.get(dataSourceName) || null }; // Listen for manifest:dev-reload (fired by mnfst-run when a data file changes). // Re-fetches all local data sources and updates the Alpine store reactively. window.addEventListener('manifest:dev-reload', async () => { const manifest = await window.ManifestDataConfig.ensureManifest(); if (!manifest?.data) return; const locale = document.documentElement.lang || (typeof Alpine !== 'undefined' && Alpine.store('locale')?.current) || 'en'; const { dataSourceCache } = window.ManifestDataStore; const isAppwriteCollection = window.ManifestDataConfig.isAppwriteCollection; for (const [name, source] of Object.entries(manifest.data)) { if (isAppwriteCollection(source)) continue; if (source && typeof source === 'object' && source.url) continue; dataSourceCache.delete(`${name}:${locale}`); // Reload keeps rows live and merges (identity survives an edit-save) try { await loadDataSource(name, locale, { reload: true }); } catch { /* skip failed sources */ } } }); // Initialize dataSources after magic method is registered if (window.ManifestDataStore.isInitializing || window.ManifestDataStore.initializationComplete) return; setIsInitializing(true); try { // Mark the store initialized in place (never replace the store object) const dataStore = Alpine.store('data'); dataStore._initialized = true; dataStore._ready = false; if (!dataStore._currentUrl) dataStore._currentUrl = window.location.pathname; // Pre-load local file-backed sources so $x.* renders real data first pass; // Appwrite, API-URL, and "manifest" sources stay on-demand. try { const manifest = await window.ManifestDataConfig.ensureManifest(); const locale = (typeof document !== 'undefined' && document.documentElement?.lang) || (typeof Alpine !== 'undefined' && Alpine.store('locale')?.current) || 'en'; const isAppwriteCollection = window.ManifestDataConfig.isAppwriteCollection; // Persisted $x (§12.2): boot-tier snapshots land before any network load // of those sources; capped so an IndexedDB miss never delays a cold boot const persist = window.ManifestDataPersist; if (persist && manifest && persist.configure(manifest)) { await persist.hydrateBoot({ maxWaitMs: persist.BOOT_HYDRATE_MAX_WAIT_MS }); } if (manifest?.data) { const preloadNames = []; for (const [name, source] of Object.entries(manifest.data)) { if (name === 'manifest') continue; // handled separately below if (isAppwriteCollection(source)) continue; if (source && typeof source === 'object' && source.url) continue; preloadNames.push(name); } if (preloadNames.length > 0) { await Promise.all( preloadNames.map(async (name) => { try { const data = await loadDataSource(name, locale); if (data != null) { // Boot landing: every pre-loaded source lands in ONE flush await landRows(name, data, { mode: 'replace', loading: false, error: null, ready: true, fresh: true, allowDuringInit: true }); } } catch (err) { console.warn(`[Manifest Data] Failed to pre-load ${name}:`, err); } }) ); } } if (manifest && manifest.data && manifest.data.manifest) { // The manifest data source points to itself - use the manifest object directly const manifestData = manifest; // Remove internal properties that shouldn't be exposed const { data, appwrite, components, preloadedComponents, ...publicManifest } = manifestData; // allowDuringInit: setIsInitializing(true) is active, so without this // flag updateStore short-circuits and $x.manifest stays unpopulated. window.ManifestDataStore.dataSourceCache.set(`manifest:${locale}`, publicManifest); updateStore('manifest', publicManifest, { loading: false, error: null, ready: true, fresh: true, allowDuringInit: true }); } Alpine.store('data')._ready = true; } catch (error) { // If manifest pre-load fails, mark as ready anyway - it will load on-demand console.warn('[Manifest Data] Failed to pre-load manifest:', error); Alpine.store('data')._ready = true; } // Force Alpine to re-run effects that read $x.content (they may have run before pre-load and got loading proxy) const flushThenDispatch = () => { window.ManifestDataStore?.bumpAllVersions?.(); if (typeof window !== 'undefined') { window.dispatchEvent(new CustomEvent('manifest:data-ready')); } // Check if all sources are settled and dispatch manifest:render-ready if so. // Covers the initial-load path (no data sources, or only content pre-loaded). window.ManifestDataStore?.checkAndDispatchRenderReady?.(); }; if (typeof Alpine !== 'undefined' && Alpine.nextTick) { Alpine.nextTick(flushThenDispatch); } else { setTimeout(flushThenDispatch, 0); } // Other data sources remain on-demand when accessed via $x } finally { setIsInitializing(false); setInitializationComplete(true); } } // Handle both DOMContentLoaded and alpine:init // Track if we've already initialized to prevent duplicate initialization let dataSourcesInitialized = false; function tryInitialize() { if (dataSourcesInitialized) { return; } if (typeof Alpine === 'undefined') { return; } dataSourcesInitialized = true; initializeDataSourcesPlugin(); } // Try immediately if Alpine is available if (typeof Alpine !== 'undefined') { tryInitialize(); } else if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', tryInitialize); } // Also listen for alpine:init (in case Alpine loads after DOMContentLoaded) document.addEventListener('alpine:init', tryInitialize);