statum-core.js 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. /*!
  2. * Statum - client-side state library (core module).
  3. *
  4. * An HTMX-inspired state layer. The library manages signed "snapshots" of
  5. * application state (one per slot type), keeps them fresh via the server's
  6. * `transmit_after` / `invalid_after` timestamps, and binds them to the DOM
  7. * through `stm-*` attributes. See model.md for the full specification.
  8. *
  9. * The client ships as modules, each a plain IIFE with no dependencies and no
  10. * build step, loaded in this order:
  11. *
  12. * 1. statum-core.js - this file: the slot protocol (persistence, the
  13. * X-Statum-Slot request machinery, directive
  14. * application, the realtime channel), the
  15. * alert/confirm/notify overrides, boot, and the
  16. * module seam (`statum._bridge` /
  17. * `statum.registerAttribute`). Self-sufficient;
  18. * creates `window.statum`.
  19. * 2. statum-document.js - the render walk and the structural/DOM bindings.
  20. * 3. statum-markdown.js - the CommonMark engine and `stm-markdown`.
  21. *
  22. * Targets modern evergreen browsers (uses fetch, BroadcastChannel,
  23. * queueMicrotask, URLSearchParams, FormData).
  24. */
  25. (function () {
  26. 'use strict';
  27. /** Content-Type used by every Statum directive response. */
  28. var STATUM_CONTENT_TYPE = 'application/vnd.statum+json';
  29. /** Request/response header carrying one slot's reference (or base64 frame). */
  30. var SLOT_HEADER = 'X-Statum-Slot';
  31. /** Request header carrying an action's opaque `private` blob. */
  32. var PRIVATE_HEADER = 'X-Statum-Private';
  33. /** Session-cookie marker used to detect a fresh browser session. */
  34. var SESSION_COOKIE = '_statum_sdc';
  35. /** BroadcastChannel name used to sync session/device state across tabs. */
  36. var CHANNEL_NAME = 'statum';
  37. /** localStorage / sessionStorage key prefix for persisted frames. */
  38. var STORAGE_PREFIX = 'statum:';
  39. // ---------------------------------------------------------------------------
  40. // Configuration
  41. // ---------------------------------------------------------------------------
  42. /**
  43. * Endpoint URLs. These defaults may be overridden per-page with the
  44. * `stm-entrypoint` and `stm-slots` attributes on the `<body>` element.
  45. *
  46. * @type {{entrypointUrl: string, slotsUrl: string}}
  47. */
  48. var config = {
  49. entrypointUrl: '/_statum/entrypoint',
  50. slotsUrl: '/_statum/slots',
  51. channelUrl: '/_statum/channel',
  52. // The realtime worker is embedded in the library as a default resource
  53. // (served at /_statum/resource/statum-worker.js); override with stm-worker.
  54. workerUrl: '/_statum/resource/statum-worker.js'
  55. };
  56. // ---------------------------------------------------------------------------
  57. // State store
  58. // ---------------------------------------------------------------------------
  59. /**
  60. * In-memory store, keyed by slot type. Each value is `{frame, snapshot}`
  61. * where `snapshot` is the parsed `frame.content`. This map is the single
  62. * source of truth for rendering; persistent backends merely hydrate it.
  63. *
  64. * @type {Map<string, {frame: object, snapshot: object}>}
  65. */
  66. var store = new Map();
  67. /** Listeners, keyed by type name. @type {Map<string, Set<Function>>} */
  68. var listeners = new Map();
  69. /**
  70. * Idempotency tracking: slot key -> last-applied frame `signature`. Held in
  71. * memory only (per tab), so a frame already persisted by another tab still
  72. * re-draws a tab whose tracking lags. Entries are dropped on clear so a
  73. * replayed frame re-applies.
  74. * @type {Map<string, string>}
  75. */
  76. var signatures = new Map();
  77. /** Optional UI handlers (set via `statum.on*Handler`). */
  78. var handlers = { onConfirm: null, onNotify: null, onError: null };
  79. /** @type {BroadcastChannel|null} */
  80. var channel = null;
  81. /** Whether {@link init} has already run. */
  82. var initialized = false;
  83. /** Whether the entrypoint has been fetched (guards without pre-entrypoint
  84. * only evaluate after this). */
  85. var entrypointLoaded = false;
  86. /** Set when a guard has triggered a redirect, so further work is skipped. */
  87. var guardRedirected = false;
  88. // ---------------------------------------------------------------------------
  89. // Small utilities
  90. // ---------------------------------------------------------------------------
  91. /**
  92. * Parse an ISO 8601 timestamp to epoch millis, or `undefined`.
  93. * @param {string|undefined} s
  94. * @returns {number|undefined}
  95. */
  96. function parseTime(s) {
  97. if (!s) return undefined;
  98. var t = new Date(s).getTime();
  99. return isNaN(t) ? undefined : t;
  100. }
  101. /**
  102. * Base64-encode a UTF-8 string (safe for frames containing non-Latin1 data).
  103. * @param {string} str
  104. * @returns {string}
  105. */
  106. function b64encode(str) {
  107. var bytes = new TextEncoder().encode(str);
  108. var bin = '';
  109. var chunk = 0x8000;
  110. for (var i = 0; i < bytes.length; i += chunk) {
  111. bin += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
  112. }
  113. return btoa(bin);
  114. }
  115. /** Read a cookie value, or `null` if absent. @param {string} name */
  116. function getCookie(name) {
  117. var escaped = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
  118. var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
  119. return match ? decodeURIComponent(match[1]) : null;
  120. }
  121. /** Set a session cookie (no expiry => cleared when the browser closes). */
  122. function setCookie(name, value) {
  123. document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; SameSite=Lax';
  124. }
  125. // ---------------------------------------------------------------------------
  126. // Expression evaluation
  127. // ---------------------------------------------------------------------------
  128. /**
  129. * Compiled-expression cache. Expressions are evaluated as JavaScript against
  130. * a scope object (the page's HTML is trusted, per the model).
  131. * @type {Map<string, Function>}
  132. */
  133. var exprCache = new Map();
  134. /**
  135. * Wrap a scope for expression evaluation so bare identifiers resolve in a
  136. * controlled order: names on the scope (slot types, loop variables,
  137. * `stm-def-*` locals) win; names missing from the scope but present on
  138. * `globalThis` (`Math`, `parseInt`, `String`, …) forward to that global;
  139. * anything else resolves to `undefined` instead of throwing a
  140. * `ReferenceError` or leaking an unintended global. The `has` trap claims
  141. * every name so `with` never falls through around the proxy, and the inner
  142. * try/catch of the compiled expression still turns property access on a
  143. * resolved `undefined`/`null` into `undefined` for that expression alone.
  144. * @param {object} scope
  145. * @returns {Proxy<object>}
  146. */
  147. function evalScope(scope) {
  148. return new Proxy(scope, {
  149. has: function () { return true; },
  150. get: function (target, name) {
  151. if (name in target) return target[name];
  152. if (typeof name === 'string' && name in globalThis) return globalThis[name];
  153. return undefined;
  154. }
  155. });
  156. }
  157. /**
  158. * Compile (and cache) an expression string into a function of `scope`.
  159. * Uses `with` so that arbitrary type names and loop variables are resolved
  160. * as bare identifiers. Returns a function that yields `undefined` on any
  161. * runtime or compile error.
  162. * @param {string} expr
  163. * @returns {Function}
  164. */
  165. function compileExpr(expr) {
  166. var cached = exprCache.get(expr);
  167. if (cached !== undefined) return cached;
  168. var fn;
  169. try {
  170. // Function-constructor bodies are non-strict by default, so `with` is
  171. // permitted. The inner try/catch turns runtime errors (property access
  172. // on an unset slot's `undefined`) into `undefined` so a missing path
  173. // simply yields no value; missing identifiers already resolve to
  174. // `undefined` via the evalScope proxy.
  175. fn = new Function('scope', 'with(scope){try{return (' + expr + ');}catch(e){return undefined;}}');
  176. } catch (e) {
  177. fn = function () { return undefined; };
  178. }
  179. exprCache.set(expr, fn);
  180. return fn;
  181. }
  182. /**
  183. * Evaluate an expression against a scope.
  184. * @param {string} expr
  185. * @param {object} [scope]
  186. * @returns {*} `undefined` if the expression is empty or fails.
  187. */
  188. function evalExpr(expr, scope) {
  189. if (expr == null || expr === '') return undefined;
  190. try {
  191. return compileExpr(expr)(evalScope(scope || {}));
  192. } catch (e) {
  193. return undefined;
  194. }
  195. }
  196. /**
  197. * Build a child scope that inherits the parent (so type bindings remain
  198. * visible) and adds one own loop variable.
  199. * @param {object} parent
  200. * @param {string} name
  201. * @param {*} value
  202. * @returns {object}
  203. */
  204. function childScope(parent, name, value) {
  205. var scope = Object.create(parent || null);
  206. scope[name] = value;
  207. return scope;
  208. }
  209. // ---------------------------------------------------------------------------
  210. // StatumError
  211. // ---------------------------------------------------------------------------
  212. /**
  213. * Error type thrown for HTTP failures and `error` directives.
  214. * @param {string} [message]
  215. * @param {string} [code]
  216. * @param {object} [data]
  217. */
  218. function StatumError(message, code, data) {
  219. this.name = 'StatumError';
  220. this.message = message || '';
  221. this.code = code || undefined;
  222. this.data = data || undefined;
  223. }
  224. StatumError.prototype = Object.create(Error.prototype);
  225. // ---------------------------------------------------------------------------
  226. // UI handlers (confirm / notify / error)
  227. // ---------------------------------------------------------------------------
  228. /**
  229. * Run the `notify` directive's default behaviour or the custom
  230. * `statum.onNotifyHandler`. The default surfaces the message via `alert()`.
  231. * @param {string} [kind] Application-defined category (freeform).
  232. * @param {string} [message]
  233. */
  234. function triggerNotify(kind, message) {
  235. var fn = handlers.onNotify;
  236. try {
  237. if (fn) fn(kind, message);
  238. else if (message != null) window.alert(message);
  239. } catch (e) { console.error('[statum] notify handler error', e); }
  240. }
  241. /**
  242. * Run the `stm-confirm` gate: the custom `statum.onConfirmHandler` if set,
  243. * otherwise `window.confirm`. Supports async handlers (custom modals).
  244. * @param {string} message
  245. * @param {HTMLElement} element
  246. * @returns {Promise<boolean>} truthy if the action should proceed.
  247. */
  248. async function triggerConfirm(message, element) {
  249. var fn = handlers.onConfirm;
  250. try {
  251. if (fn) return !!(await fn(message, element));
  252. return !!window.confirm(message);
  253. } catch (e) {
  254. console.error('[statum] confirm handler error', e);
  255. return false;
  256. }
  257. }
  258. /**
  259. * Run the custom `statum.onErrorHandler`, if set. Returns whether the default
  260. * behaviour (promise rejection + `stm-on-error` classes) should proceed: the
  261. * handler suppresses the default by returning (or resolving) `false`.
  262. * @param {StatumError} error
  263. * @param {HTMLElement|null} element
  264. * @returns {Promise<boolean>}
  265. */
  266. async function triggerError(error, element) {
  267. var fn = handlers.onError;
  268. if (!fn) return true;
  269. try {
  270. var suppress = await fn(error, element);
  271. return suppress !== false;
  272. } catch (e) {
  273. console.error('[statum] error handler error', e);
  274. return true;
  275. }
  276. }
  277. /**
  278. * Surface a failure: run `triggerError`, and if the default is not
  279. * suppressed, apply `stm-on-error` classes (when an origin element exists)
  280. * and re-throw so the originating promise rejects.
  281. * @param {StatumError} error
  282. * @param {HTMLElement|null} element
  283. */
  284. async function reportFailure(error, element) {
  285. if (await triggerError(error, element)) {
  286. if (element) applyErrorClasses(element, true);
  287. throw error;
  288. }
  289. }
  290. // ---------------------------------------------------------------------------
  291. // Persistence
  292. // ---------------------------------------------------------------------------
  293. /**
  294. * Pick the storage backend for a scope.
  295. * @param {string} scope
  296. * @returns {Storage|null} `null` for in-memory scopes.
  297. */
  298. function storageFor(scope) {
  299. if (scope === 'device' || scope === 'session') return localStorage;
  300. if (scope === 'flow') return sessionStorage;
  301. return null; // page / transient
  302. }
  303. /**
  304. * Persist a slot's frame to the backend matching its scope, removing any
  305. * stale copy from the other backend first (in case the scope changed).
  306. * @param {string} type
  307. * @param {{frame: object, snapshot: object}} entry
  308. */
  309. function persistEntry(type, entry) {
  310. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  311. removePersisted(type);
  312. var storage = storageFor(scope);
  313. if (!storage) return;
  314. try {
  315. storage.setItem(STORAGE_PREFIX + type, JSON.stringify(entry.frame));
  316. } catch (e) {
  317. /* storage full or unavailable; remain in-memory only */
  318. }
  319. }
  320. /** Remove a persisted frame from both backends. @param {string} type */
  321. function removePersisted(type) {
  322. try { localStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  323. try { sessionStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  324. }
  325. /** Load every persisted frame from a backend into the in-memory store. */
  326. function loadFrom(storage) {
  327. for (var i = 0; i < storage.length; i++) {
  328. var key = storage.key(i);
  329. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  330. try {
  331. var frame = JSON.parse(storage.getItem(key));
  332. var snapshot = JSON.parse(frame.content);
  333. var type = snapshot.slot && snapshot.slot.type;
  334. if (type && !store.has(type)) store.set(type, { frame: frame, snapshot: snapshot });
  335. } catch (e) {
  336. /* corrupt entry: ignore */
  337. }
  338. }
  339. }
  340. /** Hydrate the store from localStorage and sessionStorage. */
  341. function hydrate() {
  342. try { loadFrom(localStorage); } catch (e) {}
  343. try { loadFrom(sessionStorage); } catch (e) {}
  344. }
  345. // ---------------------------------------------------------------------------
  346. // Session-cookie initialization
  347. // ---------------------------------------------------------------------------
  348. /**
  349. * Detect a fresh browser session using the `_statum_sdc` session cookie.
  350. * On a fresh session, clear all `session`-scoped persisted frames, then set
  351. * the marker. Session cookies are shared across tabs, so a tab opened
  352. * mid-session sees the marker and leaves session data intact.
  353. */
  354. function initSession() {
  355. if (getCookie(SESSION_COOKIE) !== null) return;
  356. clearSessionSlotsFromStorage();
  357. setCookie(SESSION_COOKIE, '1');
  358. }
  359. /** Remove all `session`-scoped frames from localStorage. */
  360. function clearSessionSlotsFromStorage() {
  361. var toRemove = [];
  362. for (var i = 0; i < localStorage.length; i++) {
  363. var key = localStorage.key(i);
  364. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  365. try {
  366. var frame = JSON.parse(localStorage.getItem(key));
  367. var snapshot = JSON.parse(frame.content);
  368. if (snapshot.slot && snapshot.slot.scope === 'session') toRemove.push(key);
  369. } catch (e) {}
  370. }
  371. for (var j = 0; j < toRemove.length; j++) localStorage.removeItem(toRemove[j]);
  372. }
  373. // ---------------------------------------------------------------------------
  374. // Listeners & cross-tab broadcast
  375. // ---------------------------------------------------------------------------
  376. /**
  377. * Fire all listeners for a type. (Renamed from `notify` to avoid confusion
  378. * with the `notify` directive.)
  379. * @param {string} type
  380. * @param {object|null} frame
  381. * @param {object|null} snapshot
  382. */
  383. function fireListeners(type, frame, snapshot) {
  384. var set = listeners.get(type);
  385. if (!set) return;
  386. var event = { type: type, frame: frame, snapshot: snapshot };
  387. set.forEach(function (cb) {
  388. try { cb(event); } catch (e) { console.error('[statum] listener error', e); }
  389. });
  390. }
  391. /**
  392. * Broadcast a state change to other tabs. Only `session`/`device` scopes are
  393. * shared (flow/page/transient are per-tab).
  394. * @param {object} message
  395. * @param {string} [scope]
  396. */
  397. function broadcast(message, scope) {
  398. if (!channel) return;
  399. if (scope !== 'session' && scope !== 'device') return;
  400. try { channel.postMessage(message); } catch (e) {}
  401. }
  402. /**
  403. * Broadcast a message to other tabs regardless of slot scope. Used to relay
  404. * realtime (live) events so they reach every tab, not just session/device
  405. * ones.
  406. */
  407. function broadcastAlways(message) {
  408. if (!channel) return;
  409. try { channel.postMessage(message); } catch (e) {}
  410. }
  411. /** Open the BroadcastChannel and wire inbound messages. */
  412. function setupChannel() {
  413. if (typeof BroadcastChannel === 'undefined') return;
  414. try {
  415. channel = new BroadcastChannel(CHANNEL_NAME);
  416. } catch (e) {
  417. channel = null;
  418. return;
  419. }
  420. channel.onmessage = function (ev) {
  421. var msg = ev.data;
  422. if (!msg) return;
  423. if (msg.kind === 'set' && msg.frame) {
  424. try {
  425. var snapshot = JSON.parse(msg.frame.content);
  426. var type = snapshot.slot && snapshot.slot.type;
  427. if (type && commitSet(msg.frame, snapshot, type, false)) renderAll();
  428. } catch (e) { /* ignore malformed */ }
  429. } else if (msg.kind === 'clear') {
  430. var t = msg.type;
  431. if (!t && msg.key != null) {
  432. store.forEach(function (entry, type) {
  433. if (entry.snapshot.slot && entry.snapshot.slot.key === msg.key) t = type;
  434. });
  435. }
  436. if (t) clearType(t, { broadcast: false });
  437. else if (msg.key != null) signatures.delete(msg.key);
  438. renderAll();
  439. }
  440. };
  441. }
  442. // ---------------------------------------------------------------------------
  443. // State mutation
  444. // ---------------------------------------------------------------------------
  445. /**
  446. * Remove a type from the store, un-persist it, drop its idempotency entry,
  447. * fire listeners, and (optionally) broadcast the clear to other tabs.
  448. * @param {string} type
  449. * @param {{broadcast?: boolean}} [opts]
  450. */
  451. function clearType(type, opts) {
  452. var entry = store.get(type);
  453. if (!entry) return;
  454. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  455. var key = entry.snapshot.slot && entry.snapshot.slot.key;
  456. store.delete(type);
  457. removePersisted(type);
  458. if (key) signatures.delete(key);
  459. fireListeners(type, null, null);
  460. if (opts && opts.broadcast) broadcast({ kind: 'clear', key: key, type: type }, scope);
  461. }
  462. /**
  463. * Resolve a slot key to its type and clear it. Used by the `clear` directive
  464. * (keyed) and by live `clear` events.
  465. * @param {string} key
  466. * @param {boolean} [broadcast]
  467. */
  468. function clearByKey(key, broadcast) {
  469. var typeToRemove = null;
  470. store.forEach(function (entry, type) {
  471. if (entry.snapshot.slot && entry.snapshot.slot.key === key) typeToRemove = type;
  472. });
  473. if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
  474. else if (key) signatures.delete(key);
  475. }
  476. /**
  477. * Resolve a frame signature to its slot type and clear it. Used by the
  478. * `invalidate` directive, which references a signature (not a key) because the
  479. * server reports a bad signature without trusting the frame's content.
  480. * @param {string} signature
  481. * @param {boolean} [broadcast]
  482. */
  483. function clearBySignature(signature, broadcast) {
  484. var typeToRemove = null;
  485. store.forEach(function (entry, type) {
  486. if (entry.frame && entry.frame.signature === signature) typeToRemove = type;
  487. });
  488. if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
  489. else if (signature) signatures.delete(signature);
  490. }
  491. /**
  492. * Commit a `set` to the in-memory store, persist it, and fire listeners.
  493. * Idempotent: if the frame's `signature` matches the last-applied signature
  494. * for this slot (tracked in {@link signatures}), nothing happens and `false`
  495. * is returned. When `doBroadcast` is true the set is forwarded to other tabs
  496. * via the scope-gated broadcast (session/device only).
  497. * @param {object} frame
  498. * @param {object} snapshot
  499. * @param {string} type
  500. * @param {boolean} doBroadcast
  501. * @returns {boolean} `true` if state changed.
  502. */
  503. function commitSet(frame, snapshot, type, doBroadcast) {
  504. var key = snapshot.slot && snapshot.slot.key;
  505. var sig = frame.signature;
  506. if (key && sig !== undefined && signatures.get(key) === sig) return false;
  507. var entry = { frame: frame, snapshot: snapshot };
  508. store.set(type, entry);
  509. persistEntry(type, entry);
  510. fireListeners(type, frame, snapshot);
  511. if (key && sig !== undefined) signatures.set(key, sig);
  512. if (doBroadcast) {
  513. var scope = snapshot.slot && snapshot.slot.scope;
  514. broadcast({ kind: 'set', frame: frame }, scope);
  515. }
  516. return true;
  517. }
  518. /**
  519. * Apply a `set` directive: store/refresh a slot's snapshot (idempotently),
  520. * broadcasting to other tabs.
  521. * @param {object} directive `{ snapshot_frame }`
  522. */
  523. function applySet(directive) {
  524. var frame = directive.snapshot_frame;
  525. if (!frame || !frame.content) return;
  526. var snapshot;
  527. try { snapshot = JSON.parse(frame.content); } catch (e) { return; }
  528. var type = snapshot.slot && snapshot.slot.type;
  529. if (!type) return;
  530. commitSet(frame, snapshot, type, true);
  531. }
  532. /**
  533. * Apply a `clear` directive. The directive carries a slot key, so the type
  534. * holding that key is resolved and removed.
  535. * @param {object} directive `{ key }`
  536. */
  537. function applyClear(directive) {
  538. if (directive.key == null) return;
  539. clearByKey(directive.key, true);
  540. }
  541. /**
  542. * Apply a live `set` event received over the realtime channel. The frame is
  543. * committed (idempotently) and, when new, broadcast to sibling tabs via the
  544. * scope-agnostic {@link broadcastAlways} so every tab sees it regardless of
  545. * which (or how many) tabs hold a subscription.
  546. * @param {object} frame
  547. */
  548. function applyRemoteSet(frame) {
  549. try {
  550. var snapshot = JSON.parse(frame.content);
  551. var type = snapshot.slot && snapshot.slot.type;
  552. if (!type) return;
  553. if (commitSet(frame, snapshot, type, false)) {
  554. broadcastAlways({ kind: 'set', frame: frame });
  555. renderAll();
  556. }
  557. } catch (e) { /* malformed frame */ }
  558. }
  559. /** Apply a live `clear` event received over the realtime channel. */
  560. function applyRemoteClear(key) {
  561. if (key == null) return;
  562. signatures.delete(key);
  563. clearByKey(key, false);
  564. broadcastAlways({ kind: 'clear', key: key });
  565. renderAll();
  566. }
  567. // ---------------------------------------------------------------------------
  568. // Snapshot freshness & request headers
  569. // ---------------------------------------------------------------------------
  570. /**
  571. * Categorize a held snapshot relative to the current time.
  572. * @returns {'silent'|'always'|'invalid'|'stale'|'fresh'}
  573. * - `silent`: unidirectional (`transmit_after` undefined) - never sent.
  574. * - `always`: `transmit_after === as_at` - send the base64 frame each time.
  575. * - `invalid`: past `invalid_after` - drop and refetch.
  576. * - `stale`: past `transmit_after` but not yet invalid - pre-flight first.
  577. * - `fresh`: still cached server-side - send the `as_at` reference.
  578. */
  579. function entryCategory(entry) {
  580. var snap = entry.snapshot;
  581. var transmit = snap.transmit_after;
  582. if (transmit === undefined || transmit === null) return 'silent';
  583. if (transmit === snap.as_at) return 'always';
  584. var now = Date.now();
  585. var invalidAt = parseTime(snap.invalid_after);
  586. var transmitAt = parseTime(transmit);
  587. if (invalidAt !== undefined && now >= invalidAt) return 'invalid';
  588. if (transmitAt !== undefined && now >= transmitAt) return 'stale';
  589. return 'fresh';
  590. }
  591. /**
  592. * Drop locally-invalid snapshots and pre-flight any stale ones. Pre-flighting
  593. * posts the stale frames to the slot endpoint and applies the returned `set`
  594. * directives, refreshing their `as_at` values before the real request runs.
  595. *
  596. * Single-flight: concurrent callers share one in-flight preparation.
  597. * @returns {Promise<void>}
  598. */
  599. var preparePromise = null;
  600. function prepareSlots() {
  601. if (preparePromise) return preparePromise;
  602. preparePromise = doPrepareSlots().then(function () {
  603. preparePromise = null;
  604. }, function () {
  605. preparePromise = null;
  606. });
  607. return preparePromise;
  608. }
  609. async function doPrepareSlots() {
  610. var stale = [];
  611. store.forEach(function (entry, type) {
  612. var cat = entryCategory(entry);
  613. if (cat === 'invalid') {
  614. clearType(type, { broadcast: false });
  615. } else if (cat === 'stale') {
  616. stale.push(entry.frame);
  617. }
  618. });
  619. if (stale.length) {
  620. var directives = await postSlots(stale);
  621. var pfResult = applyDirectives(directives, { originElement: null });
  622. executeTerminal(pfResult);
  623. }
  624. }
  625. /**
  626. * Build the `X-Statum-Slot` header values for every held slot, using the
  627. * freshness rules. Assumes {@link prepareSlots} has just run.
  628. * @returns {string[]}
  629. */
  630. function buildSlotHeaders() {
  631. var headers = [];
  632. store.forEach(function (entry) {
  633. var snap = entry.snapshot;
  634. var cat = entryCategory(entry);
  635. if (cat === 'silent' || cat === 'invalid') return;
  636. if (cat === 'always') {
  637. headers.push(b64encode(JSON.stringify(entry.frame)));
  638. } else {
  639. headers.push('key=' + snap.slot.key + '; as_at=' + snap.as_at);
  640. }
  641. });
  642. return headers;
  643. }
  644. /**
  645. * Collect the current frames held for the given slot keys, in the order the
  646. * keys are first supplied. Used by the `transmit` directive (which forces a
  647. * slot's frame to be posted as if its `transmit_after` had elapsed). Keys the
  648. * client does not currently hold are skipped.
  649. * @param {string[]} keys
  650. * @returns {object[]}
  651. */
  652. function collectFramesForKeys(keys) {
  653. var keySet = Object.create(null);
  654. for (var i = 0; i < keys.length; i++) keySet[keys[i]] = true;
  655. var frames = [];
  656. store.forEach(function (entry) {
  657. var key = entry.snapshot.slot && entry.snapshot.slot.key;
  658. if (key && keySet[key]) {
  659. frames.push(entry.frame);
  660. delete keySet[key];
  661. }
  662. });
  663. return frames;
  664. }
  665. // ---------------------------------------------------------------------------
  666. // HTTP helpers
  667. // ---------------------------------------------------------------------------
  668. /** True if a response is a Statum directive response. */
  669. function isStatum(res) {
  670. return (res.headers.get('Content-Type') || '').indexOf(STATUM_CONTENT_TYPE) !== -1;
  671. }
  672. /**
  673. * POST an array of frames to the slot endpoint (the pre-flight target) and
  674. * return its directive array. This request intentionally carries no slot
  675. * headers (it is itself the refresh).
  676. * @param {object[]} frames
  677. * @returns {Promise<object[]>}
  678. */
  679. async function postSlots(frames) {
  680. var headers = new Headers();
  681. headers.set('Accept', STATUM_CONTENT_TYPE);
  682. headers.set('Content-Type', 'application/json');
  683. var res = await fetch(config.slotsUrl, {
  684. method: 'POST',
  685. headers: headers,
  686. body: JSON.stringify(frames),
  687. credentials: 'same-origin'
  688. });
  689. if (!isStatum(res)) return [];
  690. try { return await res.json(); } catch (e) { return []; }
  691. }
  692. /**
  693. * Apply the non-terminal directives from a response (set/clear/subscribe/
  694. * unsubscribe/notify/transmit-collection), then `render`.
  695. *
  696. * Terminal directives (`navigate`, `post`, `reenter`), error directives, and
  697. * any transmit/retry intent are collected on the returned result rather than
  698. * executed here: {@link handleResponse} performs the asynchronous
  699. * transmission (and optional retry) and then runs terminal navigation, so
  700. * that a `transmit` with `retry` can re-issue the request before the page is
  701. * navigated away.
  702. * @param {object[]} directives
  703. * @param {{originElement?: HTMLElement}} [ctx]
  704. * @returns {{errors: StatumError[], transmitKeys: string[], retry: boolean, navigate: object|null, post: object|null, reenter: boolean}}
  705. */
  706. function applyDirectives(directives, ctx) {
  707. var result = { errors: [], transmitKeys: [], retry: false, navigate: null, post: null, reenter: false, formSubmits: [], formResets: [] };
  708. var list = Array.isArray(directives) ? directives : [];
  709. for (var i = 0; i < list.length; i++) {
  710. var d = list[i];
  711. if (!d || typeof d !== 'object') continue;
  712. switch (d.type) {
  713. case 'set': applySet(d); break;
  714. case 'clear': applyClear(d); break;
  715. case 'invalidate':
  716. if (d.signature != null) {
  717. console.warn('[statum] server could not verify slot frame ' + d.signature + '; clearing it');
  718. clearBySignature(d.signature, true);
  719. }
  720. break;
  721. case 'subscribe': channelSubscribe(d.key); break;
  722. case 'unsubscribe': channelUnsubscribe(d.key); break;
  723. case 'notify': triggerNotify(d.kind, d.message); break;
  724. case 'transmit':
  725. if (d.key != null) {
  726. if (result.transmitKeys.indexOf(d.key) === -1) result.transmitKeys.push(d.key);
  727. if (d.retry) result.retry = true;
  728. }
  729. break;
  730. case 'error':
  731. {
  732. var err = new StatumError(d.message, d.code, d.data);
  733. var detail = d.code ? (d.message + ' [' + d.code + ']') : d.message;
  734. console.error('[statum] error directive: ' + (detail || '(no message)'));
  735. result.errors.push(err);
  736. }
  737. break;
  738. case 'navigate': result.navigate = d; break;
  739. case 'reenter': result.reenter = true; break;
  740. case 'post': result.post = d; break;
  741. case 'form-submit': result.formSubmits.push(d); break;
  742. case 'form-reset': result.formResets.push(d); break;
  743. }
  744. }
  745. renderAll();
  746. return result;
  747. }
  748. /**
  749. * Execute the terminal directives collected by {@link applyDirectives}.
  750. *
  751. * Order: `form-reset`/`form-submit` first (their work is synchronous), then
  752. * a `reenter` (the entrypoint refresh is awaited so the action's promise
  753. * resolves only once the re-entered state has been applied), then
  754. * `navigate`/`post` — navigation wins over reenter's refresh when both are
  755. * present, running after it. Async because of reenter.
  756. */
  757. async function executeTerminal(result) {
  758. result.formResets.forEach(doFormReset);
  759. result.formSubmits.forEach(doFormSubmit);
  760. if (result.reenter) {
  761. try {
  762. await loadEntrypoint();
  763. } catch (err) {
  764. console.error('[statum] reenter: entrypoint refresh failed', err);
  765. }
  766. }
  767. if (result.navigate) doNavigate(result.navigate);
  768. if (result.post) doPost(result.post);
  769. }
  770. /** Execute a `form-submit` directive: optionally override action/method, then submit. */
  771. function doFormSubmit(d) {
  772. var form = document.getElementById(d.form);
  773. if (form) {
  774. if (d.action) form.setAttribute('action', d.action);
  775. if (d.method) form.setAttribute('method', d.method);
  776. form.submit();
  777. }
  778. }
  779. /** Execute a `form-reset` directive. */
  780. function doFormReset(d) {
  781. var form = document.getElementById(d.form);
  782. if (form) form.reset();
  783. }
  784. /** Execute a `navigate` directive as a full page load. */
  785. function doNavigate(d) {
  786. if (d.uri) window.location.href = d.uri;
  787. }
  788. /** Execute a `post` directive as a real (navigating) form POST. */
  789. function doPost(d) {
  790. if (!d.uri) return;
  791. var form = document.createElement('form');
  792. form.method = 'POST';
  793. form.action = d.uri;
  794. form.style.display = 'none';
  795. var data = d.data || {};
  796. Object.keys(data).forEach(function (name) {
  797. var input = document.createElement('input');
  798. input.type = 'hidden';
  799. input.name = name;
  800. input.value = data[name] == null ? '' : String(data[name]);
  801. form.appendChild(input);
  802. });
  803. document.body.appendChild(form);
  804. form.submit();
  805. }
  806. /**
  807. * Handle a fetch response: if it is a Statum response, apply its directives;
  808. * otherwise throw on HTTP errors and no-op on other successful responses.
  809. *
  810. * Directive ordering: non-terminal directives are applied and the page
  811. * rendered; then any `transmit` directives force their slot frames to be
  812. * posted (applying the directives the slot endpoint returns); then, if a
  813. * transmit requested a retry, the originating request (`ctx.retry`) is
  814. * re-issued and this response's terminal directives and errors are skipped.
  815. * Otherwise terminal directives run — form resets/submits, then an awaited
  816. * `reenter` entrypoint refresh (a failure is logged, never propagated), then
  817. * `navigate`/`post` — and finally error directives are surfaced. Because
  818. * the terminal phase is awaited, an action promise resolves only after a
  819. * `reenter` refresh has been applied.
  820. * @param {Response} res
  821. * @param {{originElement?: HTMLElement, retry?: Function}} [ctx]
  822. */
  823. async function handleResponse(res, ctx) {
  824. var el = ctx && ctx.originElement;
  825. if (!isStatum(res)) {
  826. if (!res.ok) await reportFailure(new StatumError('HTTP ' + res.status), el);
  827. return;
  828. }
  829. var directives;
  830. try { directives = await res.json(); } catch (e) { directives = []; }
  831. var result = applyDirectives(directives, ctx);
  832. if (result.transmitKeys && result.transmitKeys.length) {
  833. var frames = collectFramesForKeys(result.transmitKeys);
  834. if (frames.length) {
  835. var txDirectives = await postSlots(frames);
  836. applyDirectives(txDirectives, { originElement: el });
  837. }
  838. }
  839. if (result.retry && ctx && typeof ctx.retry === 'function') {
  840. await ctx.retry();
  841. return;
  842. }
  843. await executeTerminal(result);
  844. var errors = result.errors || [];
  845. for (var i = 0; i < errors.length; i++) {
  846. await reportFailure(errors[i], el);
  847. }
  848. }
  849. // ---------------------------------------------------------------------------
  850. // Entrypoint & action requests
  851. // ---------------------------------------------------------------------------
  852. /**
  853. * Fetch the entrypoint for the current URL, applying its directives. Carries
  854. * slot headers (and pre-flights) like any other request. The request is
  855. * wrapped in an `attempt` closure passed as the response `retry` callback, so
  856. * a `transmit` directive with `retry` can re-issue it after transmission.
  857. * @returns {Promise<void>}
  858. */
  859. function loadEntrypoint() {
  860. if (guardRedirected) return Promise.resolve();
  861. // From this point on guards are "post-entrypoint" (all of them evaluate).
  862. entrypointLoaded = true;
  863. var attempt = async function () {
  864. await prepareSlots();
  865. var headers = new Headers();
  866. headers.set('Accept', STATUM_CONTENT_TYPE);
  867. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  868. var url = config.entrypointUrl + '?uri=' + encodeURIComponent(window.location.href);
  869. var res = await fetch(url, { headers: headers, credentials: 'same-origin' });
  870. await handleResponse(res, { originElement: null, retry: attempt });
  871. };
  872. return attempt();
  873. }
  874. /**
  875. * Perform an action request.
  876. *
  877. * The request is wrapped in an `attempt` closure passed as the response
  878. * `retry` callback, so a `transmit` directive with `retry` can re-issue the
  879. * same action after the transmission (rebuilding headers from current state).
  880. *
  881. * @param {object} action `{ uri, method, private }`
  882. * @param {object} [data] Key/value parameters. Encoded as query string for
  883. * GET/HEAD, otherwise as `application/x-www-form-urlencoded`.
  884. * @param {HTMLElement} [originElement] Element that triggered the action, so
  885. * that `stm-on-error` classes can be applied on an `error` directive.
  886. * @returns {Promise<void>} Resolves once the request completes and its
  887. * directives have run; rejects on HTTP failure or an `error` directive.
  888. */
  889. function performAction(action, data, originElement) {
  890. var attempt = async function () {
  891. await prepareSlots();
  892. var headers = new Headers();
  893. headers.set('Accept', STATUM_CONTENT_TYPE);
  894. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  895. if (action.private) headers.set(PRIVATE_HEADER, action.private);
  896. var method = (action.method || 'GET').toUpperCase();
  897. var params = data || {};
  898. var init = { method: method, headers: headers, credentials: 'same-origin' };
  899. var url = action.uri;
  900. if (method === 'GET' || method === 'HEAD') {
  901. var qs = new URLSearchParams(params).toString();
  902. if (qs) url += (url.indexOf('?') !== -1 ? '&' : '?') + qs;
  903. } else {
  904. init.body = new URLSearchParams(params).toString();
  905. headers.set('Content-Type', 'application/x-www-form-urlencoded');
  906. }
  907. var res;
  908. try {
  909. res = await fetch(url, init);
  910. } catch (networkErr) {
  911. await reportFailure(new StatumError('Network error'), originElement);
  912. return;
  913. }
  914. await handleResponse(res, { originElement: originElement, retry: attempt });
  915. };
  916. return attempt();
  917. }
  918. // ---------------------------------------------------------------------------
  919. // Realtime channel (subscribe/unsubscribe directives)
  920. // ---------------------------------------------------------------------------
  921. /**
  922. * Per-tab fallback engine, used when `SharedWorker` is unavailable. Owns an
  923. * `EventSource`, reads the channel id from the first `event: channel`,
  924. * reference-counts slot keys within this tab, PATCHes subscription changes,
  925. * applies incoming set/clear events (broadcasting them to siblings), and
  926. * closes the stream once it has no subscriptions.
  927. */
  928. function createFallbackEngine() {
  929. var es = null;
  930. var channelId = null;
  931. var refs = new Map(); // slotKey -> count
  932. var pending = { subscribe: [], unsubscribe: [] };
  933. var patchScheduled = false;
  934. function openStream() {
  935. if (es) return;
  936. try { es = new EventSource(config.channelUrl); }
  937. catch (e) { es = null; return; }
  938. es.addEventListener('channel', function (ev) { channelId = ev.data; flushPatch(); });
  939. es.addEventListener('set', function (ev) {
  940. try { applyRemoteSet(JSON.parse(ev.data)); } catch (e) {}
  941. });
  942. es.addEventListener('clear', function (ev) { applyRemoteClear(ev.data); });
  943. es.onerror = function () { /* EventSource auto-reconnects */ };
  944. }
  945. function closeStream() {
  946. if (es) { try { es.close(); } catch (e) {} es = null; }
  947. channelId = null;
  948. }
  949. function schedulePatch() {
  950. if (patchScheduled) return;
  951. patchScheduled = true;
  952. Promise.resolve().then(function () { patchScheduled = false; flushPatch(); });
  953. }
  954. function flushPatch() {
  955. if (!channelId) return;
  956. var sub = pending.subscribe, uns = pending.unsubscribe;
  957. if (!sub.length && !uns.length) return;
  958. pending = { subscribe: [], unsubscribe: [] };
  959. var body = {};
  960. if (sub.length) body.subscribe = sub;
  961. if (uns.length) body.unsubscribe = uns;
  962. try {
  963. fetch(config.channelUrl + '/' + encodeURIComponent(channelId), {
  964. method: 'PATCH',
  965. headers: { 'Content-Type': 'application/json' },
  966. credentials: 'same-origin',
  967. body: JSON.stringify(body)
  968. }).catch(function () {});
  969. } catch (e) {}
  970. }
  971. return {
  972. subscribe: function (key) {
  973. var c = refs.get(key) || 0;
  974. refs.set(key, c + 1);
  975. if (c === 0) { openStream(); pending.subscribe.push(key); schedulePatch(); }
  976. },
  977. unsubscribe: function (key) {
  978. var c = refs.get(key) || 0;
  979. if (c <= 0) return;
  980. if (c - 1 <= 0) {
  981. refs.delete(key);
  982. pending.unsubscribe.push(key);
  983. schedulePatch();
  984. if (refs.size === 0) setTimeout(function () { if (refs.size === 0) closeStream(); }, 0);
  985. } else {
  986. refs.set(key, c - 1);
  987. }
  988. }
  989. };
  990. }
  991. /**
  992. * Channel manager. Prefers a `SharedWorker` (which owns the single SSE
  993. * connection, reference-counts subscriptions across tabs, and relays events
  994. * through the cross-tab `BroadcastChannel`); falls back to a per-tab
  995. * `EventSource` engine when `SharedWorker` is unavailable or the worker
  996. * script fails to load. Tracks the true per-slot subscription count so it can
  997. * replay active subscriptions into the fallback on a mid-session switch.
  998. */
  999. function createChannelManager() {
  1000. var port = null;
  1001. var workerObj = null;
  1002. var fallback = null;
  1003. var mode = null; // 'worker' | 'fallback' | null
  1004. var counts = new Map(); // slotKey -> count (true subscription state)
  1005. function switchToFallback() {
  1006. if (mode === 'fallback') return;
  1007. mode = 'fallback';
  1008. port = null;
  1009. workerObj = null;
  1010. fallback = createFallbackEngine();
  1011. counts.forEach(function (c, key) {
  1012. for (var i = 0; i < c; i++) fallback.subscribe(key);
  1013. });
  1014. }
  1015. function ensure() {
  1016. if (mode !== null) return;
  1017. if (typeof SharedWorker !== 'undefined') {
  1018. try {
  1019. workerObj = new SharedWorker(config.workerUrl);
  1020. port = workerObj.port;
  1021. port.start();
  1022. port.postMessage({ op: 'init', url: config.channelUrl });
  1023. // The worker delivers events via the BroadcastChannel, so nothing is
  1024. // required on this port beyond command messages.
  1025. port.onmessage = function () {};
  1026. workerObj.onerror = function () {
  1027. console.warn('[statum] realtime worker failed; falling back to per-tab channel');
  1028. switchToFallback();
  1029. };
  1030. window.addEventListener('pagehide', function () {
  1031. if (mode === 'worker' && port) {
  1032. try { port.postMessage({ op: 'disconnect' }); } catch (e) {}
  1033. }
  1034. });
  1035. mode = 'worker';
  1036. return;
  1037. } catch (e) { workerObj = null; port = null; }
  1038. }
  1039. switchToFallback();
  1040. }
  1041. return {
  1042. subscribe: function (key) {
  1043. if (key == null) return;
  1044. ensure();
  1045. counts.set(key, (counts.get(key) || 0) + 1);
  1046. if (mode === 'worker') { try { port.postMessage({ op: 'subscribe', key: key }); } catch (e) {} }
  1047. else fallback.subscribe(key);
  1048. },
  1049. unsubscribe: function (key) {
  1050. if (key == null) return;
  1051. var c = (counts.get(key) || 0) - 1;
  1052. if (c <= 0) counts.delete(key); else counts.set(key, c);
  1053. ensure();
  1054. if (mode === 'worker') { try { port.postMessage({ op: 'unsubscribe', key: key }); } catch (e) {} }
  1055. else fallback.unsubscribe(key);
  1056. }
  1057. };
  1058. }
  1059. var channelManager = createChannelManager();
  1060. function channelSubscribe(key) { channelManager.subscribe(key); }
  1061. function channelUnsubscribe(key) { channelManager.unsubscribe(key); }
  1062. // ---------------------------------------------------------------------------
  1063. // Error-state classes
  1064. // ---------------------------------------------------------------------------
  1065. // (Moved from the render-walk section in statum-document.js so that
  1066. // reportFailure above is self-contained without that module.)
  1067. /** Apply or remove `stm-on-error` classes on an action element. */
  1068. function applyErrorClasses(el, on) {
  1069. if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
  1070. var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
  1071. classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
  1072. }
  1073. // ---------------------------------------------------------------------------
  1074. // Module seam: attribute-handler registry + render driver
  1075. // ---------------------------------------------------------------------------
  1076. //
  1077. // statum-core.js is self-sufficient: it owns the slot protocol, the UI
  1078. // handler overrides and the boot sequence, and never references the other
  1079. // modules. statum-document.js (the render walk) and statum-markdown.js
  1080. // (the CommonMark engine) load AFTER core and register through this seam.
  1081. //
  1082. // `_bridge` (underscore = private by convention, like `_testMarkdown`) is
  1083. // the internal cross-module surface; `statum.registerAttribute` is the
  1084. // public entry point module authors use.
  1085. /**
  1086. * Resolved execution order of the per-element `stm-*` bindings: an ordered
  1087. * list of `{name, fn, prefix}`. The render walk (statum-document.js)
  1088. * iterates it for every element. A throwing handler aborts that render
  1089. * cycle through renderAll's try/catch, exactly as the previous hardcoded
  1090. * call chain did, so handlers get no per-handler try/catch here.
  1091. * @type {Array<{name: string, fn: Function, prefix: boolean}>}
  1092. */
  1093. var attributeHandlers = [];
  1094. /**
  1095. * Register a handler for an `stm-*` attribute.
  1096. *
  1097. * `name` is either an exact attribute name (`'stm-disabled'`) or, when it
  1098. * ends with a dot, a prefix matcher (`'stm-class.'` matches any
  1099. * `stm-class.{name}`). The handler is called once per element per render
  1100. * cycle when the element carries at least one matching attribute; it then
  1101. * iterates the element's attributes itself (several may match a prefix).
  1102. *
  1103. * `opts.after` / `opts.before` name another registered attribute and the
  1104. * handler is inserted directly after / before it. A constraint naming an
  1105. * unregistered attribute warns and keeps plain registration order, so
  1106. * loading a module early cannot break the page. Registering the same name
  1107. * twice warns and ignores the second handler.
  1108. *
  1109. * @param {string} name
  1110. * @param {Function} fn `fn(el, scope)`
  1111. * @param {{after?: string, before?: string}} [opts]
  1112. */
  1113. function registerAttribute(name, fn, opts) {
  1114. if (typeof name !== 'string' || !name || typeof fn !== 'function') {
  1115. console.warn('[statum] registerAttribute: expected an attribute name and a handler function');
  1116. return;
  1117. }
  1118. for (var i = 0; i < attributeHandlers.length; i++) {
  1119. if (attributeHandlers[i].name === name) {
  1120. console.warn('[statum] registerAttribute: "' + name + '" is already registered; ignoring');
  1121. return;
  1122. }
  1123. }
  1124. var entry = { name: name, fn: fn, prefix: name.charAt(name.length - 1) === '.' };
  1125. var anchor = opts && (opts.after || opts.before);
  1126. var at = anchor ? handlerIndex(anchor) : -1;
  1127. if (anchor && at === -1) {
  1128. console.warn('[statum] registerAttribute: "' + anchor +
  1129. '" is not registered; keeping registration order for "' + name + '"');
  1130. }
  1131. if (at !== -1 && opts.after) at += 1; // insert directly after the anchor
  1132. if (at === -1) attributeHandlers.push(entry);
  1133. else attributeHandlers.splice(at, 0, entry);
  1134. }
  1135. /** Position of a registered handler by name, or -1. */
  1136. function handlerIndex(name) {
  1137. for (var i = 0; i < attributeHandlers.length; i++) {
  1138. if (attributeHandlers[i].name === name) return i;
  1139. }
  1140. return -1;
  1141. }
  1142. /**
  1143. * The render driver: installed by statum-document.js at load time, called
  1144. * by renderAll to walk the document. When absent (core loaded alone)
  1145. * render cycles still run the evaluate hooks and guards but skip the DOM
  1146. * walk.
  1147. * @type {Function|null}
  1148. */
  1149. var renderDriver = null;
  1150. /** Install the render driver. @param {Function} fn `fn(scope)` */
  1151. function installRenderDriver(fn) {
  1152. if (typeof fn === 'function') renderDriver = fn;
  1153. }
  1154. /**
  1155. * The module bridge: everything the other modules need from core (and the
  1156. * one thing core needs from them, the render driver) crosses here. The
  1157. * evaluate hooks stay core-private on purpose — no other module needs
  1158. * them; modules register attribute handlers instead.
  1159. */
  1160. var bridge = {
  1161. /** Expression machinery (core-owned). */
  1162. evalExpr: evalExpr,
  1163. childScope: childScope,
  1164. stateScope: stateScope,
  1165. /** Render cycle + requests. */
  1166. renderAll: renderAll,
  1167. loadEntrypoint: loadEntrypoint,
  1168. performAction: performAction,
  1169. /** UI handler overrides (runElementAction gates on confirm). */
  1170. triggerConfirm: triggerConfirm,
  1171. triggerNotify: triggerNotify,
  1172. triggerError: triggerError,
  1173. handlers: handlers,
  1174. /** Error-state classes for action elements. */
  1175. applyErrorClasses: applyErrorClasses,
  1176. /** The seam itself. */
  1177. registerAttribute: registerAttribute,
  1178. attributeHandlers: attributeHandlers,
  1179. installRenderDriver: installRenderDriver
  1180. };
  1181. /**
  1182. * Evaluate every `<link rel="stm-guard">` in the document head. A guard whose
  1183. * `require` predicate is false redirects the page to its `href`.
  1184. *
  1185. * Guards marked `pre-entrypoint` are evaluated on every cycle (including the
  1186. * initial, pre-entrypoint render, which uses only hydrated state); guards
  1187. * without it are evaluated only once the entrypoint has loaded. On every later
  1188. * evaluate cycle (set/clear) all guards are re-checked, so logging out, for
  1189. * example, can bounce the user off a guarded page.
  1190. */
  1191. function evaluateGuards() {
  1192. if (guardRedirected) return;
  1193. var scope = stateScope();
  1194. var guards = document.querySelectorAll('link[rel~="stm-guard"]');
  1195. for (var i = 0; i < guards.length; i++) {
  1196. var g = guards[i];
  1197. var preEntrypoint = g.hasAttribute('pre-entrypoint');
  1198. if (!preEntrypoint && !entrypointLoaded) continue;
  1199. var require = g.getAttribute('require');
  1200. if (!require) continue;
  1201. if (!evalExpr(require, scope)) {
  1202. guardRedirected = true;
  1203. var href = g.getAttribute('href') || '/';
  1204. console.warn('[statum] guard failed (' + require + '); redirecting to ' + href);
  1205. window.location.href = href;
  1206. return;
  1207. }
  1208. }
  1209. }
  1210. // ---------------------------------------------------------------------------
  1211. // Evaluation hooks (no-arg callbacks before/after each render cycle)
  1212. // ---------------------------------------------------------------------------
  1213. var beforeHooks = [];
  1214. var afterHooks = [];
  1215. /** Re-render the whole document against the current state. */
  1216. function renderAll() {
  1217. if (guardRedirected) return;
  1218. beforeHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] beforeEvaluate hook error', e); } });
  1219. try {
  1220. // The DOM walk lives in statum-document.js and is installed through
  1221. // the seam; without it the cycle still runs hooks and guards.
  1222. if (renderDriver) renderDriver(stateScope());
  1223. }
  1224. catch (e) { console.error('[statum] render error', e); }
  1225. afterHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] afterEvaluate hook error', e); } });
  1226. evaluateGuards();
  1227. }
  1228. // ---------------------------------------------------------------------------
  1229. // Boot visibility (stm-preloader / stm-content)
  1230. // ---------------------------------------------------------------------------
  1231. /**
  1232. * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
  1233. * loading, `stm-preloader` elements are shown and `stm-content` elements
  1234. * hidden; once ready, the reverse.
  1235. *
  1236. * To avoid a flash of un-bound template before the script runs, authors may
  1237. * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
  1238. * `<div stm-content hidden>`); the library removes it once ready. The library
  1239. * also sets `hidden` itself during loading as a fallback for authors who do
  1240. * not pre-set it.
  1241. * @param {boolean} ready
  1242. */
  1243. function setBootState(ready) {
  1244. var preloaders = document.querySelectorAll('[stm-preloader]');
  1245. var contents = document.querySelectorAll('[stm-content]');
  1246. for (var i = 0; i < preloaders.length; i++) {
  1247. ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
  1248. }
  1249. for (var j = 0; j < contents.length; j++) {
  1250. ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
  1251. }
  1252. }
  1253. // ---------------------------------------------------------------------------
  1254. // Public state accessors
  1255. // ---------------------------------------------------------------------------
  1256. /** Build the scope used for expression evaluation: `{ typeName: public }`. */
  1257. function stateScope() {
  1258. var scope = {};
  1259. store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
  1260. return scope;
  1261. }
  1262. /** Read a type's `public` data (what the attributes bind to). */
  1263. function read(type) {
  1264. var entry = store.get(type);
  1265. return entry ? entry.snapshot.public : undefined;
  1266. }
  1267. /** Read a type's full snapshot object. */
  1268. function getSnapshot(type) {
  1269. var entry = store.get(type);
  1270. return entry ? entry.snapshot : undefined;
  1271. }
  1272. /** Read the frame wrapping a type's snapshot. */
  1273. function getFrame(type) {
  1274. var entry = store.get(type);
  1275. return entry ? entry.frame : undefined;
  1276. }
  1277. /** Build an object of `{ typeName: public }` for every held type. */
  1278. function state() {
  1279. var result = {};
  1280. store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
  1281. return result;
  1282. }
  1283. /**
  1284. * Clear state. With a type argument, clears that type only; without, clears
  1285. * all held state.
  1286. * @param {string} [type]
  1287. */
  1288. function clear(type) {
  1289. if (type === undefined) {
  1290. Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
  1291. } else {
  1292. clearType(type, { broadcast: true });
  1293. }
  1294. renderAll();
  1295. }
  1296. /**
  1297. * Perform an action. `action` may be an action object or a string path that
  1298. * resolves to an action object within the current state.
  1299. * @param {object|string} action
  1300. * @param {object} [data]
  1301. * @returns {Promise<void>}
  1302. */
  1303. function act(action, data) {
  1304. var resolved = action;
  1305. if (typeof action === 'string') resolved = evalExpr(action, stateScope());
  1306. if (!resolved || typeof resolved.uri !== 'string') {
  1307. return Promise.reject(new StatumError('Invalid action'));
  1308. }
  1309. return performAction(resolved, data, null);
  1310. }
  1311. /** Attach a state listener for a type. */
  1312. function addStateListener(type, callback) {
  1313. if (typeof callback !== 'function') return;
  1314. if (!listeners.has(type)) listeners.set(type, new Set());
  1315. listeners.get(type).add(callback);
  1316. }
  1317. /** Remove a previously-attached state listener. */
  1318. function removeStateListener(type, callback) {
  1319. var set = listeners.get(type);
  1320. if (!set) return;
  1321. set.delete(callback);
  1322. if (set.size === 0) listeners.delete(type);
  1323. }
  1324. // ---------------------------------------------------------------------------
  1325. // Initialization
  1326. // ---------------------------------------------------------------------------
  1327. /**
  1328. * Inject the stylesheet that makes the `hidden` attribute authoritative.
  1329. * Statum toggles `stm-if`/`stm-else` branches and loop holders via
  1330. * `hidden`, whose user-agent rule loses specificity battles to ordinary
  1331. * author CSS (a rule like `li { display: flex }` let hidden loop holders
  1332. * leak as phantom rows). Idempotent: skipped when the stylesheet is
  1333. * already present.
  1334. */
  1335. function injectHiddenStyle() {
  1336. var id = 'statum-hidden-style';
  1337. if (document.getElementById(id)) return;
  1338. var head = document.head;
  1339. if (!head) return;
  1340. var style = document.createElement('style');
  1341. style.id = id;
  1342. style.textContent = '[hidden]{display:none !important}';
  1343. head.appendChild(style);
  1344. }
  1345. /**
  1346. * Scan the document for `pstm-*` attributes and `<pstm-*>` elements, which
  1347. * are intended for server-side pre-rendering and should never reach the
  1348. * browser. Emits a single `console.warn` summarizing them.
  1349. */
  1350. function warnServerSideMarkup() {
  1351. var found = [];
  1352. var els = document.querySelectorAll('*');
  1353. for (var i = 0; i < els.length; i++) {
  1354. var el = els[i];
  1355. var tag = el.tagName.toLowerCase();
  1356. if (tag.indexOf('pstm-') === 0) found.push('<' + tag + '>');
  1357. var attrs = el.attributes;
  1358. for (var j = 0; j < attrs.length; j++) {
  1359. var name = attrs[j].name;
  1360. if (name.indexOf('pstm-') === 0) found.push('<' + tag + '> ' + name);
  1361. }
  1362. }
  1363. if (found.length) {
  1364. console.warn('[statum] ' + found.length + ' server-side pstm-* attribute/element(s) ' +
  1365. 'found in the DOM; they should have been resolved during pre-rendering: ' +
  1366. found.slice(0, 10).join(', ') + (found.length > 10 ? ' …' : ''));
  1367. }
  1368. }
  1369. /**
  1370. * Initialize Statum: read URL overrides, run the session-cookie check,
  1371. * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
  1372. * and render. Safe to call multiple times.
  1373. * @returns {Promise<void>}
  1374. */
  1375. async function init() {
  1376. if (initialized) return;
  1377. initialized = true;
  1378. // Before the first render and the boot visibility toggling, so `hidden`
  1379. // wins over author CSS from the very first paint.
  1380. injectHiddenStyle();
  1381. var body = document.body;
  1382. if (body) {
  1383. if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
  1384. if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
  1385. if (body.hasAttribute('stm-channel')) config.channelUrl = body.getAttribute('stm-channel');
  1386. if (body.hasAttribute('stm-worker')) config.workerUrl = body.getAttribute('stm-worker');
  1387. }
  1388. try { warnServerSideMarkup(); } catch (e) {}
  1389. try { initSession(); } catch (e) {}
  1390. try { hydrate(); } catch (e) {}
  1391. setupChannel();
  1392. setBootState(false);
  1393. renderAll(); // bind against any persisted/hydrated state immediately
  1394. try {
  1395. await loadEntrypoint();
  1396. } catch (err) {
  1397. console.error('[statum] entrypoint load failed', err);
  1398. } finally {
  1399. setBootState(true);
  1400. }
  1401. }
  1402. function autoInit() {
  1403. if (document.readyState === 'loading') {
  1404. document.addEventListener('DOMContentLoaded', init);
  1405. } else {
  1406. init();
  1407. }
  1408. }
  1409. // ---------------------------------------------------------------------------
  1410. // Public API
  1411. // ---------------------------------------------------------------------------
  1412. /** @namespace statum */
  1413. window.statum = {
  1414. /** Library version. */
  1415. version: '0.1.0',
  1416. /** Mutable endpoint configuration. */
  1417. config: config,
  1418. /** (Re)initialize the library. Usually runs automatically on load. */
  1419. init: init,
  1420. /** Read a type's `public` data. */
  1421. read: read,
  1422. /** Read a type's full snapshot object. */
  1423. getSnapshot: getSnapshot,
  1424. /** Read the frame wrapping a type's snapshot. */
  1425. getFrame: getFrame,
  1426. /** Build `{ typeName: public }` for every held type. */
  1427. state: state,
  1428. /** Clear one type (`clear("x")`) or all state (`clear()`). */
  1429. clear: clear,
  1430. /** Perform an action object or named action. */
  1431. act: act,
  1432. /** Attach a state-changed listener for a type. */
  1433. addStateListener: addStateListener,
  1434. /** Remove a previously-attached listener. */
  1435. removeStateListener: removeStateListener,
  1436. /**
  1437. * Register a handler for an `stm-*` attribute (module seam — see the
  1438. * registry in statum-core.js). `name` is an exact attribute name, or a
  1439. * prefix matcher when it ends with `.`; `opts.after` / `opts.before`
  1440. * order the handler against another registered attribute.
  1441. */
  1442. registerAttribute: registerAttribute,
  1443. /** Register a callback that runs before each render cycle (no arguments). */
  1444. beforeEvaluate: function (fn) { if (typeof fn === 'function') beforeHooks.push(fn); },
  1445. /** Register a callback that runs after each render cycle (no arguments). */
  1446. afterEvaluate: function (fn) { if (typeof fn === 'function') afterHooks.push(fn); },
  1447. /** The Statum error type (thrown by `act` and surfaced to handlers). */
  1448. Error: StatumError,
  1449. get onConfirmHandler() { return handlers.onConfirm; },
  1450. set onConfirmHandler(v) { handlers.onConfirm = typeof v === 'function' ? v : null; },
  1451. get onNotifyHandler() { return handlers.onNotify; },
  1452. set onNotifyHandler(v) { handlers.onNotify = typeof v === 'function' ? v : null; },
  1453. get onErrorHandler() { return handlers.onError; },
  1454. set onErrorHandler(v) { handlers.onError = typeof v === 'function' ? v : null; }
  1455. };
  1456. // The seam must be exposed before any other module loads. autoInit only
  1457. // ever runs on DOMContentLoaded (or immediately at load); both happen
  1458. // outside this script tag, so the later module tags always see the bridge.
  1459. window.statum._bridge = bridge;
  1460. autoInit();
  1461. })();