hearth-runtime 0.1.0

Local-first web applications written in Rust. Server rendering, reactive queries and optimistic writes.
1
2
3
4
5
function Kt(n){return import($n(n))}function $n(n){return new URL(n,window.location.origin).href}var Hn=/^\s*::hearth::signal\(([\s\S]*)\)\s*$/,Un=/^\s*::hearth::dep\("([0-9a-f]+)"\)\s*$/,zn=/^\s*::hearth::connect\s*$/,qn=/^\s*::hearth::expr::start\("([^"]*)"\)\s*$/,jn=/^\s*::hearth::expr::end\s*$/,Wn=/^\s*::hearth::region::start\(([0-9a-f]+)\)\s*$/,Kn=/^\s*::hearth::region::end\(([0-9a-f]+)\)\s*$/,Jn=/^\s*::hearth::shard::start\(("[^"]*"), ("[^"]*"), (\[[\s\S]*\])\)\s*$/,Yn=/^\s*::hearth::shard::end\(("[^"]+")\)\s*$/,bt=/"([^"]*)"/g;function $e(n){let e=n.data,t=Hn.exec(e);if(t){let l=JSON.parse(St(t[1]??""));if(l.t!=="signal"||typeof l.id!="string")throw new Error("Invalid signal marker");return{kind:"signal",id:l.id,value:l.v}}let r=Un.exec(e);if(r)return{kind:"dep",id:r[1]??""};if(zn.test(e))return{kind:"connect"};let i=qn.exec(e);if(i)return{kind:"expr-start",js:St(i[1]??"")};if(jn.test(e))return{kind:"expr-end"};let o=Wn.exec(e);if(o)return{kind:"region-start",id:o[1]??""};let s=Kn.exec(e);if(s)return{kind:"region-end",id:s[1]??""};let a=Jn.exec(e);if(a){let l=[];bt.lastIndex=0;let u=bt.exec(a[3]??"");for(;u!==null;)l.push(St(u[1]??"")),u=bt.exec(a[3]??"");return{kind:"shard-start",path:JSON.parse(a[1]??""),identity:JSON.parse(a[2]??""),exprs:l}}let c=Yn.exec(e);return c?{kind:"shard-end",identity:JSON.parse(c[1]??"")}:null}function St(n){let e=new DOMParser().parseFromString(n,"text/html").documentElement.textContent;if(e===null)throw new Error("Failed to decode comment marker");return e}var He=[];function Yt(){return He}function Te(n){let e=He;return He=n,e}var xt=new Map,Jt=new Map,Tt=new Map;function Xn(n){let e=new Set,t=o=>{let s=/^#([a-f0-9]{64}):/.exec(o)?.[1];if(s){e.add(s);let a=JSON.parse(o.slice(66));a&&!Array.isArray(a)&&Array.isArray(a.expressions)&&a.expressions.forEach(t)}},r=o=>o.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),i=o=>{let s=document.createTreeWalker(o,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let a=s.nextNode();a;a=s.nextNode())if(a.nodeType===Node.ELEMENT_NODE){let c=a;for(let l of c.attributes)(l.name.startsWith("data-hearth-on:")||l.name.startsWith("data-hearth-bind:"))&&t(l.value);c instanceof HTMLTemplateElement&&i(c.content)}else{let c=a,l=c.data.trim();if(l.startsWith("::hearth::expr::start(")||l.startsWith("::hearth::shard::start(")){let u=$e(c);u?.kind==="expr-start"&&t(u.js),u?.kind==="shard-start"&&u.exprs.forEach(t)}else if(l.startsWith("::hearth::js("))r(l.slice(13,-1)).split("").forEach(t);else{let u=/^::hearth::(list|when)::start\(([\s\S]*)\)$/.exec(l);if(u){let d=JSON.parse(r(u[2]));u[1]==="list"?d.params.forEach(t):t(d.cond)}}}};return i(n),e}async function X(n,e=!1){let t;if(typeof n=="string")if(e)t=new DOMParser().parseFromString(n,"text/html");else{let s=document.createElement("template");s.innerHTML=n,t=s.content}else t=n;let r=[...Xn(t)].filter(s=>!xt.has(s)).sort(),i=[],o=r.filter(s=>{let a=Tt.get(s);return a?(i.push(a),!1):!0});for(let s=0;s<o.length;s+=32){let a=o.slice(s,s+32),c=`/_hearth/expressions.js?ids=${a.join(",")}`,l=Kt(c).then(u=>{for(let d of a){let m=u.default[d];if(typeof m!="function")throw new Error(`Missing expression ${d}`);xt.set(d,m)}}).finally(()=>{for(let u of a)Tt.delete(u)});for(let u of a)Tt.set(u,l);i.push(l)}await Promise.all(i)}function z(n,e){let t=n;if(t.startsWith("@")){let c=He[Number(t.slice(1))];if(c===void 0)throw new Error(`Unknown JS reference ${t} in ${e}`);t=c}let r=/^#([a-f0-9]{64}):([\s\S]*)$/.exec(t);if(!r)throw new Error(`Invalid expression reference in ${e}`);let i=xt.get(r[1]);if(!i)throw new Error(`Expression not loaded in ${e}: ${r[1]}`);let o=Jt.get(t);if(o)return o;let s=JSON.parse(r[2]),a=c=>i(c,s);return Jt.set(t,a),a}var ne="application/x-ndjson";async function*fe(n){let e=n.body;if(e===null){yield*kt((await n.text()).split(`
`));return}let t=e.getReader(),r=new TextDecoder,i="";try{for(;;){let{done:o,value:s}=await t.read();i+=r.decode(s,{stream:!o});let a=i.split(`
`);if(i=a.pop()??"",yield*kt(a),o)break}}finally{t.releaseLock()}yield*kt([i])}function*kt(n){for(let e of n)e.trim()!==""&&(yield JSON.parse(e))}function re(){return Symbol("render")}function Ue(n,e,t,r){switch(e.t){case"snapshot":n.replaceContent(e.html,r);break;case"swap":n.applySwap(e.region,e.html,r);break;case"redirect":location.assign(e.location);break;case"error":throw new Error(`${t} render failed: ${e.status}`)}}var qe="X-Hearth-Runtime",ze=class{constructor(e,t){this.lifetime=e;this.reportError=t;e.addEventListener("abort",()=>this.cancel(),{once:!0})}lifetime;reportError;controller=null;pending=!1;cancel(){this.controller?.abort(),this.controller=null}schedule(e){this.pending||this.lifetime.aborted||(this.cancel(),this.pending=!0,queueMicrotask(()=>{this.pending=!1,!this.lifetime.aborted&&e().catch(this.reportError)}))}async run(e,t,r,i=!1){if(this.lifetime.aborted)return;this.cancel();let o=new AbortController;this.controller=o;let s=()=>!this.lifetime.aborted&&this.controller===o;try{let a=await e(o.signal);if(!s())return;if(a.redirected){location.assign(a.url);return}if(!a.ok)throw new Error(`${r} request failed: ${a.status} ${a.statusText}`);for await(let c of fe(a)){if(!s()||(c.t==="snapshot"||c.t==="swap")&&(await X(c.html,c.t==="snapshot"&&i),!s())||(this.controller=null,t(c),this.controller!==null))return;this.controller=o}}catch(a){if(o.signal.aborted||this.lifetime.aborted)return;throw a}finally{this.controller===o&&(this.controller=null)}}};var Et=3e4,Gn=8,Qn=2,Zn=1024*1024,Xt="hearth:invalidate-prefetches";function Gt(){typeof window>"u"||window.dispatchEvent(new Event(Xt))}var Ne=class{constructor(e,t,r=null){this.url=e;this.body=t;this.limit=r,this.done=new Promise(i=>{this.resolveDone=i}),this.head=this.start(),this.head.catch(()=>{})}url;body;head;arrived=null;controller=new AbortController;buffer=[];buffered=0;limit;finished=!1;failure=null;wake=null;done;resolveDone;get isFinished(){return this.finished}get failed(){return this.failure!==null}get usable(){return this.failed?!1:this.arrived===null||performance.now()<=this.arrived.usableUntil}abort(){this.controller.abort(),this.fail(new DOMException("Page request aborted","AbortError"))}async*frames(){for(this.limit=null;;){let e=this.buffer.shift();if(e!==void 0){yield e;continue}if(this.failure!==null)throw this.failure;if(this.finished)return;await new Promise(t=>{this.wake=t})}}async start(){let e=await fetch(this.url,{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",[qe]:"true",Accept:ne},body:this.body,signal:this.controller.signal}).catch(o=>{throw this.fail(o),o}),r=e.headers.get("Content-Type")?.split(";")[0]?.trim().toLowerCase()===ne,i={url:e.url||this.url,frames:r,usableUntil:performance.now()+er(e.headers)};return this.arrived=i,r?this.pump(e):(this.controller.abort(),this.finish()),i}async pump(e){try{for await(let t of fe(e)){if(this.failure!==null)return;if(this.buffer.push(t),this.buffered+="html"in t?t.html.length:0,this.limit!==null&&this.buffered>this.limit){this.abort();return}this.notify()}this.finish()}catch(t){this.fail(t)}}finish(){this.finished=!0,this.notify(),this.resolveDone()}fail(e){this.finished||this.failure!==null||(this.failure=e,this.notify(),this.resolveDone())}notify(){let e=this.wake;this.wake=null,e?.()}};function er(n){let e=(n.get("Cache-Control")??"").toLowerCase().split(",").map(t=>t.trim());if(e.includes("no-store")||e.includes("no-cache"))return 0;for(let t of e){let[r,i]=t.split("=");if(r?.trim()!=="max-age"||i===void 0)continue;let o=Number.parseInt(i.trim(),10);if(Number.isFinite(o))return Math.min(Et,o*1e3)}return Et}var je=class{entries=new Map;listen(e){window.addEventListener(Xt,()=>this.clear(),{signal:e})}prefetch(e,t){let r=this.entries.get(e);if(r!==void 0){if(r.body===t&&r.usable)return!0;this.drop(e)}let i=0;for(let s of this.entries.values())!s.isFinished&&!s.failed&&(i+=1);if(i>=Qn)return!1;let o=new Ne(e,t,Zn);for(this.entries.set(e,o),o.done.then(()=>{o.failed&&this.entries.get(e)===o&&this.entries.delete(e)});this.entries.size>Gn;){let s=this.entries.keys().next().value;if(s===void 0)break;this.drop(s)}return setTimeout(()=>{this.entries.get(e)===o&&this.drop(e)},Et),!0}take(e,t){let r=this.entries.get(e);return r===void 0?null:(this.entries.delete(e),r.body!==t||!r.usable?(r.abort(),null):r)}clear(){for(let e of[...this.entries.keys()])this.drop(e)}drop(e){this.entries.get(e)?.abort(),this.entries.delete(e)}};var Je="data-hearth-link",tr=80,nr=150,Nt="hearth",rr=new Set(["","module","text/javascript","application/javascript"]),Ke=class{constructor(e){this.runtime=e}runtime;controller=new AbortController;prefetches=new je;current=null;generation=0;streaming=null;documentUrl="";scripts=new Set;managesScroll=!1;scrollTimer=null;hovered=null;hoverTimer=null;viewport=null;start(){this.documentUrl=ie(location.href),this.prefetches.listen(this.controller.signal);for(let r of Qt(document,location.href))this.scripts.add(r);let e=en(history.state);e!==null&&(this.manageScroll(),window.scrollTo(e.x,e.y));let t=this.controller.signal;document.addEventListener("click",r=>this.onClick(r),{signal:t}),window.addEventListener("popstate",()=>this.onPopState(),{signal:t}),window.addEventListener("scroll",()=>this.scheduleScrollSave(),{passive:!0,signal:t}),window.addEventListener("pagehide",()=>this.saveScroll(),{signal:t}),window.addEventListener("pageshow",r=>{r.persisted&&this.prefetches.clear()},{signal:t}),document.addEventListener("mouseover",r=>this.onHover(r),{signal:t}),document.addEventListener("mouseout",r=>{let i=r.relatedTarget;i instanceof Node&&this.hovered?.contains(i)||this.cancelHover()},{signal:t}),document.addEventListener("focusin",r=>{let i=We(r);i!==null&&Rt(i)==="intent"&&this.prefetch(i)},{signal:t}),document.addEventListener("touchstart",r=>{let i=We(r);i!==null&&Rt(i)==="intent"&&this.prefetch(i)},{passive:!0,signal:t})}dispose(){this.controller.abort(),this.prefetches.clear(),this.current?.abort(),this.viewport?.disconnect(),this.cancelHover()}get pending(){return this.streaming}observe(e,t){if(typeof IntersectionObserver>"u"||t.aborted)return;this.viewport??=new IntersectionObserver(i=>{for(let o of i){if(!o.isIntersecting)continue;let s=o.target;this.prefetch(s)&&this.viewport?.unobserve(s)}});let r=this.viewport;r.observe(e),t.addEventListener("abort",()=>r.unobserve(e),{once:!0})}prefetch(e){let t=this.destination(e);if(t===null)return!0;if(or())return!1;let r=ie(t.href);return r===ie(location.href)?!0:this.prefetches.prefetch(r,this.runtime.page.signalBody())}async navigate(e,t,r=null){this.generation+=1;let i=this.generation;this.current?.abort();let o=ie(e.href),s=this.runtime.page.signalBody(),a=this.prefetches.take(o,s)??new Ne(o,s);this.current=a;let c,l=new Promise(d=>{c=d});this.streaming=l;let u=()=>i===this.generation&&!this.controller.signal.aborted;try{await this.follow(a,e,t,r,u)}finally{this.streaming===l&&(this.streaming=null),c()}}async follow(e,t,r,i,o){let s;try{s=await e.head}catch{o()&&Ie(t,r);return}if(!o())return;if(!s.frames){Ie(t,r);return}let a=new URL(s.url,location.href);a.hash===""&&(a.hash=t.hash);let{page:c}=this.runtime,l=re(),u=!1;try{for await(let d of e.frames()){if(!o()||(d.t==="snapshot"||d.t==="swap")&&(await X(d.html,d.t==="snapshot"),!o()))return;switch(d.t){case"snapshot":{if(u){c.replaceContent(d.html,l);break}let m=new DOMParser().parseFromString(d.html,"text/html");if(!this.canCommit(m,a)){e.abort(),Ie(a,r);return}this.commit(m,a,r,i,l),u=!0;break}case"swap":u&&c.applySwap(d.region,d.html,l);break;case"redirect":{e.abort();let m=new URL(d.location,a);if(m.origin!==window.location.origin){window.location.assign(m.href);return}let N=u||r==="traverse"?"replace":r;this.navigate(m,N);return}case"error":throw new Error(`Navigation render failed: ${d.status}`)}}!u&&o()&&Ie(a,r)}catch(d){if(!o())return;if(!u){Ie(a,r);return}this.runtime.reportError(d)}}canCommit(e,t){let r=o=>{let s=o.doctype;return JSON.stringify(s&&[s.name,s.publicId,s.systemId])},i=o=>o.querySelector("base")?.outerHTML??null;return r(document)===r(e)&&i(document)===i(e)&&Qt(e,t.href).every(o=>this.scripts.has(o))}commit(e,t,r,i,o){switch(this.prefetches.clear(),this.cancelHover(),this.manageScroll(),r){case"push":this.saveScroll(),history.pushState(Ct(null,null),"",t.href);break;case"replace":history.replaceState(Ct(history.state,null),"",t.href);break;case"traverse":t.href!==location.href&&history.replaceState(history.state,"",t.href);break}this.documentUrl=ie(t.href),this.runtime.page.replaceDocument(e,o);let s=Zt(t);r==="traverse"&&i!==null?window.scrollTo(i.x,i.y):s!==null?s.scrollIntoView():window.scrollTo(0,0),sr(s)}onClick(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=We(e);if(t===null)return;let r=this.destination(t);r!==null&&(e.preventDefault(),this.navigate(r,r.href===location.href?"replace":"push"))}onPopState(){this.scrollTimer!==null&&(clearTimeout(this.scrollTimer),this.scrollTimer=null);let e=history.state;if(e!==null&&!tn(e))return;let t=new URL(location.href),r=en(e);if(ie(t.href)!==this.documentUrl){this.navigate(t,"traverse",r);return}this.managesScroll&&(r!==null?window.scrollTo(r.x,r.y):Zt(t)?.scrollIntoView())}onHover(e){let t=We(e),r=t!==null&&Rt(t)==="intent"?t:null;r!==this.hovered&&(this.cancelHover(),r!==null&&(this.hovered=r,this.hoverTimer=setTimeout(()=>{this.hoverTimer=null,this.prefetch(r)},tr)))}cancelHover(){this.hoverTimer!==null&&clearTimeout(this.hoverTimer),this.hoverTimer=null,this.hovered=null}destination(e){if(e.hasAttribute("download")||!e.hasAttribute("href"))return null;let t=ir(e).toLowerCase();if(t!==""&&t!=="_self")return null;let r;try{r=new URL(e.href,location.href)}catch{return null}return r.origin!==location.origin||r.protocol!=="http:"&&r.protocol!=="https:"||r.href.includes("#")&&ie(r.href)===ie(location.href)?null:r}manageScroll(){this.managesScroll||(this.managesScroll=!0,history.scrollRestoration="manual",this.saveScroll())}scheduleScrollSave(){this.managesScroll&&(this.scrollTimer!==null&&clearTimeout(this.scrollTimer),this.scrollTimer=setTimeout(()=>{this.scrollTimer=null,this.saveScroll()},nr))}saveScroll(){if(!this.managesScroll)return;this.scrollTimer!==null&&clearTimeout(this.scrollTimer),this.scrollTimer=null;let e={x:window.scrollX,y:window.scrollY};history.replaceState(Ct(history.state,e),"")}};function ie(n){let e=n.indexOf("#");return e===-1?n:n.slice(0,e)}function We(n){for(let e of n.composedPath())if(e instanceof HTMLAnchorElement)return e.hasAttribute(Je)?e:null;return null}function ir(n){return n.hasAttribute("target")?n.getAttribute("target")??"":n.ownerDocument.querySelector("base[target]")?.getAttribute("target")??""}function Rt(n){return n.getAttribute(Je)}function or(){return navigator.connection?.saveData===!0}function Qt(n,e){let t=[];for(let r of Array.from(n.scripts)){let i=r.getAttribute("type")?.trim().toLowerCase()??"";if(!rr.has(i))continue;let o=i==="module"?"module":"classic",s=r.getAttribute("src");s!==null?t.push(`${o} src ${new URL(s,e).href}`):t.push(`${o} inline ${r.text}`)}return t}function Ie(n,e){e==="push"?location.assign(n.href):location.replace(n.href)}function Zt(n){let e;try{e=decodeURIComponent(n.hash.slice(1))}catch{return null}if(e==="")return null;let t=document.getElementById(e);if(t!==null)return t;for(let r of Array.from(document.getElementsByName(e)))if(r instanceof HTMLAnchorElement)return r;return null}function sr(n){let e=document.querySelector("[autofocus]");if(e instanceof HTMLElement){e.focus();return}let t=n??document.body,r=!t.hasAttribute("tabindex");r&&t.setAttribute("tabindex","-1"),t.focus({preventScroll:!0}),r&&t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0})}function tn(n){return typeof n=="object"&&n!==null&&Nt in n}function en(n){return tn(n)?n[Nt].scroll??null:null}function Ct(n,e){return{...typeof n=="object"&&n!==null?n:{},[Nt]:{scroll:e}}}function me(n,e,t,r,i={}){let o=Array.from(r),s=ar(n,e,t),a=lr(n,s,o,i);rn(a,n,e?e.nextSibling:n.firstChild,t,o)}function ar(n,e,t){let r=[],i=e?e.nextSibling:n.firstChild;for(;i&&i!==t;)r.push(i),i=i.nextSibling;return r}function lr(n,e,t,r){let i=new Map;for(let l of e)for(let u of It(l))i.set(u.id,u);let o=new Set;for(let l of t)for(let u of It(l))i.has(u.id)&&o.add(u.id);let s=new Map,a=l=>{for(let u of l)for(let d of It(u)){if(!o.has(d.id))continue;let m=d;for(;m;){let N=s.get(m);if(N||(N=new Set,s.set(m,N)),N.add(d.id),m===u)break;m=m.parentNode}}};a(e),a(t);let c=new Map;for(let l of o){let u=i.get(l);u&&c.set(l,u)}return{options:r,preservedSelects:new WeakSet,persistent:o,idSets:s,oldById:c,active:n.ownerDocument?.activeElement??null}}function It(n){if(!(n instanceof Element))return[];let e=Array.from(n.querySelectorAll("[id]"));return n.id&&e.unshift(n),e}function rn(n,e,t,r,i){let o=t;for(let s of i){if(e instanceof Element&&s instanceof Element){let a=e.closest("select");if(a&&n.preservedSelects.has(a)){let c=s instanceof HTMLOptionElement?[s]:Array.from(s.querySelectorAll("option"));for(let l of c)l.removeAttribute("selected"),l.selected=!1}}if(o&&o!==r){let a=cr(n,s,o,r);if(a){dr(o,a),o=At(n,a,s).nextSibling;continue}}if(s instanceof Element&&n.persistent.has(s.id)){let a=n.oldById.get(s.id);if(a){pr(e,a,o),o=At(n,a,s).nextSibling;continue}}o=hr(n,e,s,o).nextSibling}for(;o&&o!==r;){let s=o.nextSibling;o.remove(),o=s}}function cr(n,e,t,r){let i=null,o=e.nextSibling,s=0,a=0,c=n.idSets.get(e)?.size??0,l=t;for(;l&&l!==r;){if(nn(n,l,e)){if(ur(n,l,e))return l;i===null&&!n.idSets.has(l)&&(i=l)}if(i===null&&o&&nn(n,l,o)&&(s++,o=o.nextSibling,s>=2&&(i=void 0)),n.active&&l.contains(n.active)||(a+=n.idSets.get(l)?.size??0,a>c))break;l=l.nextSibling}return i??null}function nn(n,e,t){return!(e.nodeType!==t.nodeType||e instanceof Element&&t instanceof Element&&(e.tagName!==t.tagName||e.id&&e.id!==t.id&&n.persistent.has(e.id)))}function ur(n,e,t){let r=n.idSets.get(e),i=n.idSets.get(t);if(!r||!i)return!1;for(let o of r)if(i.has(o))return!0;return!1}function dr(n,e){let t=n;for(;t&&t!==e;){let r=t.nextSibling;t.remove(),t=r}}function At(n,e,t){if(e instanceof Element&&t instanceof Element){if(e.tagName===t.tagName){let r=fr(n,e);return mr(e,t,r),n.options.preserveFormState&&e instanceof HTMLTextAreaElement||rn(n,e,e.firstChild,null,Array.from(t.childNodes)),gr(e,t,r),e}}else if(e.nodeType===t.nodeType)return e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e;return e.replaceWith(t),t}function hr(n,e,t,r){if(t instanceof Element&&n.idSets.has(t)){let o=(e.ownerDocument??document).createElementNS(t.namespaceURI,t.localName);return e.insertBefore(o,r),At(n,o,t)}return e.insertBefore(t,r),t}function pr(n,e,t){let r=n;if(r.moveBefore&&e.isConnected)try{r.moveBefore(e,t);return}catch{}n.insertBefore(e,t)}function fr(n,e){let t=new Set;if(e===n.active&&t.add("value"),!n.options.preserveFormState)return t;if(e instanceof HTMLInputElement)t.add("value"),t.add("checked");else if(e instanceof HTMLTextAreaElement)t.add("value");else if(e instanceof HTMLSelectElement)n.preservedSelects.add(e),t.add("value");else if(e instanceof HTMLOptionElement){let r=e.closest("select");r&&n.preservedSelects.has(r)&&t.add("selected")}return t}function mr(n,e,t){for(let r of Array.from(e.attributes))t.has(r.name)||(r.namespaceURI===null?n.getAttribute(r.name)!==r.value&&n.setAttribute(r.name,r.value):n.getAttributeNS(r.namespaceURI,r.localName)!==r.value&&n.setAttributeNS(r.namespaceURI,r.name,r.value));for(let r of Array.from(n.attributes))t.has(r.name)||(r.namespaceURI===null?e.hasAttribute(r.name)||n.removeAttribute(r.name):e.hasAttributeNS(r.namespaceURI,r.localName)||n.removeAttributeNS(r.namespaceURI,r.localName))}function gr(n,e,t){n instanceof HTMLInputElement&&e instanceof HTMLInputElement?(!t.has("checked")&&n.checked!==e.checked&&(n.checked=e.checked),!t.has("value")&&n.value!==e.value&&(n.value=e.value)):n instanceof HTMLTextAreaElement&&e instanceof HTMLTextAreaElement?!t.has("value")&&n.value!==e.value&&(n.value=e.value):n instanceof HTMLOptionElement&&e instanceof HTMLOptionElement?!t.has("selected")&&n.selected!==e.selected&&(n.selected=e.selected):n instanceof HTMLSelectElement&&e instanceof HTMLSelectElement&&!t.has("value")&&n.value!==e.value&&(n.value=e.value)}function Ye(n,e){let t=n instanceof Element?document.createElementNS(n.namespaceURI,n.localName):document.createElement("body");return t.innerHTML=e,Array.from(t.childNodes)}function L(n){if(n==null)return null;if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="object"){let e=n;if(typeof e.dehydrate=="function")return e.dehydrate()}throw new Error("Value cannot be serialized for the server")}var ge=null,Ae=new Set,Pt=!1,Xe=!1;function oe(n){let e=n,t=new Set,r=()=>(ge?.track(t),e);return r.set=i=>{let o=typeof i=="function"?i(e):i;if(e!==o){e=o;for(let s of t)s.schedule()}return e},r}function G(n){let e=ge;ge=null;try{return n()}finally{ge=e}}var Ge=class{constructor(e){this.callback=e}callback;dependencies=new Set;disposed=!1;running=!1;track(e){this.disposed||(e.add(this),this.dependencies.add(e))}schedule(){this.disposed||this.running||(Ae.add(this),!Pt&&!Xe&&(Pt=!0,queueMicrotask(()=>{Pt=!1,yr()})))}run(){if(this.disposed||this.running)return;Ae.delete(this),this.unsubscribe();let e=ge;ge=this,this.running=!0;try{this.callback()}finally{this.running=!1,ge=e}}dispose(){this.disposed=!0,Ae.delete(this),this.unsubscribe()}unsubscribe(){for(let e of this.dependencies)e.delete(this);this.dependencies.clear()}};function yr(){if(Xe)return;Xe=!0;let n=[],e=new Map;try{for(let t of Ae){Ae.delete(t);let r=(e.get(t)??0)+1;if(e.set(t,r),r>100){n.push(new Error("Reactive update cycle exceeded 100 runs"));continue}try{t.run()}catch(i){n.push(i)}}}finally{Xe=!1}if(n.length===1)throw n[0];if(n.length>1)throw new AggregateError(n,"Reactive updates failed")}var H=class{constructor(e,t,r=null,i=e?.render??null){this.parent=e;this.runtime=t;this.unit=r;this.render=i;e?.children.add(this)}parent;runtime;unit;render;children=new Set;signalIds=new Set;dependencies=new Set;requiresConnection=!1;regions=new Map;effects=new Set;listenerController=new AbortController;disposed=!1;ownContext=null;get context(){return this.ownContext??this.parent?.context??this.runtime.context}set context(e){this.ownContext=e}collectDependencies(e=new Set){for(let t of this.dependencies)e.add(t);for(let t of this.children)t.unit===this.unit&&t.collectDependencies(e);return e}contentRequiresConnection(){if(this.requiresConnection)return!0;for(let e of this.children)if(e.unit===this.unit&&e.contentRequiresConnection())return!0;return!1}effect(e){if(this.disposed)return null;let t=new Ge(e);this.effects.add(t);try{t.run()}catch(r){throw t.dispose(),this.effects.delete(t),r}return t}findRegion(e){let t=this.regions.get(e);if(t!==void 0)return t;for(let r of this.children){let i=r.findRegion(e);if(i!==void 0)return i}}get abortSignal(){return this.listenerController.signal}collectSignalValues(e={}){for(let t of this.signalIds)e[t]=L(this.runtime.registry.read(t));for(let t of this.children)t.collectSignalValues(e);return e}release(e=new Set){if(this.disposed)return e;this.disposed=!0;for(let t of this.children)t.release(e);this.children.clear(),this.regions.clear();for(let t of this.effects)t.dispose();this.effects.clear(),this.listenerController.abort();for(let t of this.signalIds)e.add(t);return this.signalIds.clear(),this.parent?.children.delete(this),e}dispose(){for(let e of this.release())this.runtime.registry.delete(e)}get isDisposed(){return this.disposed}};var xe=class{constructor(e,t){this.runtime=t;this.lifetime=new H(e,t,this),this.contentScope=new H(this.lifetime,t,this),this.requestController=new ze(this.lifetime.abortSignal,r=>t.reportError(r)),this.lifetime.abortSignal.addEventListener("abort",()=>t.connection.remove(this),{once:!0})}runtime;lifetime;contentScope;documentSnapshot=!1;requestController;watch=null;subscribing=!1;get isDisposed(){return this.lifetime.isDisposed}get requiresConnection(){return this.contentScope.contentRequiresConnection()}dispose(){this.lifetime.dispose()}request(e,t){let{url:r,headers:i,body:o}=this.rerunRequest();return fetch(r,{method:"POST",cache:"no-store",headers:{...i,Accept:t},body:o,signal:e})}reportError(e){this.runtime.reportError(e)}*ancestors(){for(let e=this.lifetime.parent;e;e=e.parent)e.unit!==null&&e.unit!==this&&(yield e.unit)}get coveredByAncestor(){for(let e of this.ancestors())if(e.requiresConnection)return!0;return!1}syncConnection(){if(this.isDisposed)return;let{connection:e}=this.runtime;if(!this.requiresConnection||this.coveredByAncestor){e.leave(this);return}this.runtime.whenLoaded(()=>this.syncConnection(),this.lifetime.abortSignal)&&e.join(this)}connectionOpened(){let{connection:e}=this.runtime;this.requiresConnection&&!this.coveredByAncestor?e.run(this):e.leave(this)}scheduleConnection(){this.syncConnection()}startWatching(){let{registry:e}=this.runtime,t=this.contentScope;this.subscribing=!0;try{this.watch=t.effect(()=>{this.readInputs();for(let r of t.collectDependencies())e.read(r);this.subscribing||this.requestController.schedule(()=>this.refresh())})}finally{this.subscribing=!1}this.scheduleConnection()}resubscribe(){this.subscribing=!0;try{this.watch?.run()}finally{this.subscribing=!1}this.scheduleConnection()}refresh(){let{connection:e}=this.runtime;if(this.requiresConnection&&e.run(this))return Promise.resolve();e.stop(this);let t=re();return this.requestController.run(r=>this.request(r,ne),r=>Ue(this,r,this.label,t),this.label,this.documentSnapshot)}replaceContent(e,t){if(this.isDisposed)return;let r=this.prepare(e);r!==null&&this.replace((i,o)=>this.insert(r,i,o),t)}applySwap(e,t,r){if(this.isDisposed)return;let i=this.contentScope.findRegion(e);if(i===void 0||i.end===null||i.scope.render!==r)return;let o=i.start.parentNode;if(o===null)return;let s=Ye(o,t),a=i.scope.release();i.scope=new H(i.scope.parent,this.runtime,i.scope.unit),me(o,i.start,i.end,s),this.runtime.hydrate(o,i.start,i.end,i.scope,a);for(let c of a)this.runtime.registry.delete(c);i.scope.unit?.resubscribe()}replace(e,t){if(this.isDisposed)return;this.requestController.cancel();let r=this.contentScope.release();this.contentScope=new H(this.lifetime,this.runtime,this,t),e(this.contentScope,r);for(let i of r)this.runtime.registry.delete(i);this.startWatching()}};var Qe=class extends xe{constructor(t,r,i,o,s,a){super(t,r);this.path=i;this.identity=o;this.startNode=a;this.computes=s.map((c,l)=>z(c,`shard ${i} argument ${l+1}`))}path;identity;startNode;label="Shard";endNode=null;computes;attachEnd(t){this.endNode=t}readInputs(){let{context:t}=this.runtime;for(let r of this.computes)r(t)}rerunRequest(){let{context:t}=this.runtime,r=G(()=>({args:this.computes.map(i=>L(i(t))),signals:this.contentScope.collectSignalValues()}));return{url:this.path,headers:{"Content-Type":"application/json","X-Hearth-Identity":this.identity},body:JSON.stringify(r)}}scheduleConnection(){queueMicrotask(()=>super.scheduleConnection())}prepare(t){let r=this.startNode.parentNode;return this.endNode===null||r===null?null:Ye(r,t)}insert(t,r,i){let o=this.startNode.parentNode,s=this.endNode;o===null||s===null||(me(o,this.startNode,s,t),this.runtime.hydrate(o,this.startNode,s,r,i))}};function ke(n){return n!==null&&typeof n=="object"&&typeof n.isAttributePresent=="function"&&typeof n.toAttributeValue=="function"}function Ze(n){return n!==null&&typeof n=="object"&&typeof n.toNodeText=="function"}var on="data-hearth-bind:",wr=new Set(["value","checked","selected","indeterminate"]);function sn(n,e,t){if(!e.name.startsWith(on))return;let r=e.name.substring(on.length),i=z(e.value,`binding :${r}`),{context:o}=t;t.effect(()=>{vr(n,r,i(o))})}function vr(n,e,t){if(wr.has(e)){let r=t;if(ke(t)){let i=t.isAttributePresent();r=e==="value"?i?t.toAttributeValue():"":i}n[e]=r}if(ke(t)){if(!t.isAttributePresent()){n.removeAttribute(e);return}n.setAttribute(e,t.toAttributeValue());return}if(t==null||t===!1){n.removeAttribute(e);return}if(t===!0){n.setAttribute(e,"");return}n.setAttribute(e,String(t))}var q=class extends Error{constructor(e){super(e),this.name="Panic"}};var Q=class n{constructor(e){for(let[t,r]of e)Object.defineProperty(this,t,{value:r,enumerable:!0})}clone(){return new n(Object.entries(this).map(([e,t])=>[e,j(t)]))}dehydrate(){return{t:"Record",v:Object.fromEntries(Object.entries(this).map(([e,t])=>[e,L(t)]))}}};var se=class n{constructor(e){this.items=e;Object.assign(this,e)}items;isIndex(e){return Number.isInteger(e)&&e>=0&&e<this.items.length}[Symbol.iterator](){return this.items[Symbol.iterator]()}clone(){return new n(this.items.map(j))}isAttributePresent(){return this.items.some(e=>ke(e)&&e.isAttributePresent())}toAttributeValue(){let e="";for(let t of this.items)ke(t)&&t.isAttributePresent()&&(e+=t.toAttributeValue());return e}toNodeText(){let e="";for(let t of this.items)Ze(t)&&(e+=t.toNodeText());return e}dehydrate(){return this.items.map(L)}toString(){let e=this.items.map(t=>globalThis.String(t));return e.length===1?`(${e[0]},)`:`(${e.join(", ")})`}};var J=class n{constructor(e,t){this.read=e;this.write=t;return new Proxy(this,{get(r,i,o){if(i==="deref"||i==="deref_mut"||i==="dehydrate")return r[i].bind(r);let s=r.read();if(s instanceof se&&typeof i=="string"){let c=Number(i);if(String(c)===i&&s.isIndex(c))return n.shared(()=>r.read()[c])}if(s instanceof Q&&typeof i=="string"&&Object.hasOwn(s,i))return n.shared(()=>r.read()[i]);if(i==="clone"&&s instanceof n)return()=>s;let a=Reflect.get(Object(s),i);return i==="clone"&&a===void 0?()=>o:typeof a=="function"?a.bind(s):a}})}read;write;static shared(e){return new n(e)}deref(){return this.read()}deref_mut(){if(!this.write)throw new Error("Cannot mutably dereference a shared Ref");this.write(this.read())}dehydrate(){throw new Error("Ref<T> cannot be dehydrated")}};function j(n){if(n instanceof J)return n;let e=n;return typeof e?.clone=="function"?e.clone():n}var T=class n{constructor(e){this.value=e}value;static some(e){return new n(e)}static none(){return new n(void 0)}is_some(){return new f(this.value!==void 0)}is_none(){return new f(this.value===void 0)}unwrap(){if(this.value===void 0)throw new q("called `Option.unwrap()` on a `None` value");return this.value}unwrap_or(e){return this.value===void 0?e:this.value}expect(e){if(this.value===void 0)throw new q(e.toString());return this.value}clone(){return this.value===void 0?n.none():n.some(j(this.value))}isAttributePresent(){return this.value===void 0?!1:this.value.isAttributePresent()}toAttributeValue(){return this.value.toAttributeValue()}toNodeText(){return this.value===void 0?"":this.value.toNodeText()}dehydrate(){return{t:"Option",v:L(this.value)}}};var f=class n{constructor(e){this.v=e}v;clone(){return new n(this.v)}not(){return new n(!this.v)}eq(e){return new n(this.v===e.v)}ne(e){return new n(this.v!==e.v)}then_(e){return this.v?T.some(e()):T.none()}then_some(e){return this.v?T.some(e):T.none()}isAttributePresent(){return this.v}toAttributeValue(){return"true"}toNodeText(){return this.v.toString()}dehydrate(){return this.v}toString(){return this.v.toString()}};var an=new DataView(new ArrayBuffer(8));function br(n){an.setFloat64(0,Math.abs(n));let e=an.getBigUint64(0),t=Number(e>>52n&0x7ffn),r=e&0xfffffffffffffn;return t===0?{mantissa:r,exponent:-1074}:{mantissa:r|0x10000000000000n,exponent:t-1075}}function Sr(n,e,t){if(Number(e[e.length-1])%2!==0)return!1;let{mantissa:r,exponent:i}=br(n),o=i<0?-i:0,s=t<0?-t:0,a=2n*r*2n**BigInt(i+o)*10n**BigInt(s),c=(2n*BigInt(e)+1n)*10n**BigInt(t+s)*2n**BigInt(o);return a===c}function Mt(n){if(Number.isNaN(n))return"NaN";if(n===Number.POSITIVE_INFINITY)return"inf";if(n===Number.NEGATIVE_INFINITY)return"-inf";if(n===0)return Object.is(n,-0)?"-0":"0";let e=n.toExponential(),t=e.indexOf("e"),r=e.slice(0,t),i=r.startsWith("-")?"-":"",o=(i===""?r:r.slice(1)).replace(".",""),s=Number(e.slice(t+1))-(o.length-1);Sr(n,o,s)&&(o=(BigInt(o)+1n).toString());let a=o.length+s;return a<=0?`${i}0.${"0".repeat(-a)}${o}`:a>=o.length?i+o+"0".repeat(a-o.length):`${i}${o.slice(0,a)}.${o.slice(a)}`}var W=class n{constructor(e){this.v=e}v;add(e){return new n(this.v+e.v)}sub(e){return new n(this.v-e.v)}mul(e){return new n(this.v*e.v)}div(e){return new n(this.v/e.v)}neg(){return new n(-this.v)}eq(e){return new f(this.v===e.v)}ne(e){return new f(this.v!==e.v)}gt(e){return new f(this.v>e.v)}lt(e){return new f(this.v<e.v)}ge(e){return new f(this.v>=e.v)}le(e){return new f(this.v<=e.v)}clone(){return new n(this.v)}isAttributePresent(){return!0}toAttributeValue(){return Mt(this.v)}toNodeText(){return Mt(this.v)}dehydrate(){return this.v}toString(){return Mt(this.v)}};function Ee(n,e){if(!/^[iu](8|16|32|64|128|size)$/.test(n))throw new Error("Unknown integer type");let t=n.endsWith("size");if(t&&![16,32,64].includes(e)||!t&&e!==Number(n.slice(1)))throw new Error("Invalid integer width");let r=n.startsWith("i"),i=1n<<BigInt(e-Number(r));return Object.freeze({kind:n,bits:e,signed:r,min:r?-i:0n,max:i-1n})}var Ot;function Tr(n){Ot=Ee("usize",n)}function ln(){if(Ot===void 0){let n=typeof document>"u"?void 0:document.querySelector("script[data-hearth-usize-bits]")?.dataset.hearthUsizeBits;if(n===void 0)throw new Error("The server's usize width is unknown; load the runtime with hearth::runtime::script()");Tr(Number(n))}return Ot}var V=class n{constructor(e,t){this.v=e;this.type=t;if(e<t.min||e>t.max)throw new q("integer overflow")}v;type;static hydrate(e){let t=Ee(e.t,e.bits);if(typeof e.v!="string"||e.v.length>40||!/^(0|-?[1-9][0-9]*)$/.test(e.v))throw new Error("Expected a canonical decimal integer");return new n(BigInt(e.v),t)}operand(e){if(this.type.kind!==e.type.kind||this.type.bits!==e.type.bits)throw new Error("Integer types do not match");return e.v}add(e){return new n(this.v+this.operand(e),this.type)}sub(e){return new n(this.v-this.operand(e),this.type)}mul(e){return new n(this.v*this.operand(e),this.type)}divisor(e){let t=this.operand(e);if(t===0n||this.v===this.type.min&&t===-1n)throw new q("invalid integer division or remainder");return t}div(e){return new n(this.v/this.divisor(e),this.type)}rem(e){return new n(this.v%this.divisor(e),this.type)}neg(){if(!this.type.signed)throw new Error("Cannot negate an unsigned integer");return new n(-this.v,this.type)}increment(){return new n(this.v+1n,this.type)}decrement(){return new n(this.v-1n,this.type)}eq(e){return new f(this.v===this.operand(e))}ne(e){return new f(this.v!==this.operand(e))}gt(e){return new f(this.v>this.operand(e))}lt(e){return new f(this.v<this.operand(e))}ge(e){return new f(this.v>=this.operand(e))}le(e){return new f(this.v<=this.operand(e))}clone(){return new n(this.v,this.type)}toIndex(e,t){if(this.type.kind!=="usize"||this.type.bits!==t)throw new Error("Index must be a usize with the collection's target width");return this.v<BigInt(e)?Number(this.v):void 0}isAttributePresent(){return!0}toAttributeValue(){return this.v.toString()}to_text(){return new P(this.v.toString())}toNodeText(){return this.v.toString()}toString(){return this.v.toString()}dehydrate(){return{t:this.type.kind,bits:this.type.bits,v:this.v.toString()}}};var xr=new TextEncoder,dn="\\t\\n\\v\\f\\r \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",cn=new RegExp(`^[${dn}]+`,"u"),un=new RegExp(`[${dn}]+$`,"u");function et(n,e){let t=n[Symbol.iterator](),r=e[Symbol.iterator]();for(;;){let i=t.next(),o=r.next();if(i.done||o.done)return Number(o.done)-Number(i.done);if(i.value!==o.value)return i.value.codePointAt(0)-o.value.codePointAt(0)}}var Re=class n{constructor(e){this.v=e}v;eq(e){return new f(this.v===e.v)}ne(e){return new f(this.v!==e.v)}gt(e){return new f(et(this.v,e.v)>0)}lt(e){return new f(et(this.v,e.v)<0)}ge(e){return new f(et(this.v,e.v)>=0)}le(e){return new f(et(this.v,e.v)<=0)}to_owned(){return new P(this.v)}add(e){return new P(this.v+e.v)}parse_i64(){let e=this.v;if(!/^[+-]?[0-9]+$/.test(e))return T.none();let t=BigInt(e);return t<-(2n**63n)||t>2n**63n-1n?T.none():T.some(new V(t,Ee("i64",64)))}is_empty(){return new f(this.v.length===0)}len(){return new V(BigInt(xr.encode(this.v).length),ln())}trim(){return new n(this.v.replace(cn,"").replace(un,""))}trim_start(){return new n(this.v.replace(cn,""))}trim_end(){return new n(this.v.replace(un,""))}starts_with(e){return new f(this.v.startsWith(e.v))}ends_with(e){return new f(this.v.endsWith(e.v))}contains(e){return new f(this.v.includes(e.v))}isAttributePresent(){return!0}toAttributeValue(){return this.v}toNodeText(){return this.v}dehydrate(){return this.v}toString(){return this.v.toString()}},P=class n extends Re{deref(){return new Re(this.v)}clone(){return new n(this.v)}dehydrate(){return this.v}};var tt=class{constructor(e){this.inner=e}inner;get alt_key(){return ye(this.inner,"altKey")}get bubbles(){return new f(this.inner.bubbles)}get button(){return $(this.inner,"button")}get buttons(){return $(this.inner,"buttons")}get cancelable(){return new f(this.inner.cancelable)}get client_x(){return $(this.inner,"clientX")}get client_y(){return $(this.inner,"clientY")}get code(){return ae(this.inner,"code")}get ctrl_key(){return ye(this.inner,"ctrlKey")}get current_target(){return new nt(this.inner.currentTarget)}get data(){return ae(this.inner,"data")}get default_prevented(){return new f(this.inner.defaultPrevented)}get delta_x(){return $(this.inner,"deltaX")}get delta_y(){return $(this.inner,"deltaY")}get delta_z(){return $(this.inner,"deltaZ")}get event_type(){return new P(this.inner.type)}get input_type(){return ae(this.inner,"inputType")}get is_composing(){return ye(this.inner,"isComposing")}get key(){return ae(this.inner,"key")}get meta_key(){return ye(this.inner,"metaKey")}get movement_x(){return $(this.inner,"movementX")}get movement_y(){return $(this.inner,"movementY")}get offset_x(){return $(this.inner,"offsetX")}get offset_y(){return $(this.inner,"offsetY")}get page_x(){return $(this.inner,"pageX")}get page_y(){return $(this.inner,"pageY")}get pointer_id(){return $(this.inner,"pointerId")}get pointer_type(){return ae(this.inner,"pointerType")}get repeat(){return ye(this.inner,"repeat")}get screen_x(){return $(this.inner,"screenX")}get screen_y(){return $(this.inner,"screenY")}get shift_key(){return ye(this.inner,"shiftKey")}get target(){return new nt(this.inner.target)}get time_stamp(){return new W(this.inner.timeStamp)}prevent_default(){this.inner.preventDefault()}stop_immediate_propagation(){this.inner.stopImmediatePropagation()}stop_propagation(){this.inner.stopPropagation()}},nt=class{constructor(e){this.inner=e}inner;get checked(){return ye(this.inner,"checked")}get id(){return ae(this.inner,"id")}get name(){return ae(this.inner,"name")}get text_content(){return new P(this.inner instanceof Node?this.inner.textContent??"":"")}get value(){return ae(this.inner,"value")}};function ye(n,e){return new f(typeof n=="object"&&n!==null&&e in n?!!n[e]:!1)}function $(n,e){let t=typeof n=="object"&&n!==null&&e in n?n[e]:0;return new W(typeof t=="number"&&Number.isFinite(t)?t:0)}function ae(n,e){let t=typeof n=="object"&&n!==null&&e in n?n[e]:"";return new P(t==null?"":globalThis.String(t))}var rt=class{constructor(e){this.v=e}v;then(e,t){let r=this.v();return this.v=()=>r,r.then(e,t)}};var it=class{constructor(e,t){this.cx=e;this.path=t}cx;path;call(...e){return new rt(async()=>{let t=await fetch(this.path,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.map(L))}).finally(Gt);if(!t.ok)throw new Error(`Procedure call failed: ${t.status} ${t.statusText}`);return this.cx.hydrate(await t.json())})}dehydrate(){return{t:"Procedure",path:this.path}}};var le=class n{constructor(e,t){this.kind=e;this.value=t}kind;value;static from_ok(e){return new n("ok",e)}static from_err(e){return new n("err",e)}is_ok(){return new f(this.kind==="ok")}is_err(){return new f(this.kind==="err")}ok(){return this.kind==="ok"?T.some(this.value):T.none()}err(){return this.kind==="err"?T.some(this.value):T.none()}unwrap(){if(this.kind==="err")throw new q(`called \`Result.unwrap()\` on an \`Err\` value: ${ot(this.value)}`);return this.value}expect(e){if(this.kind==="err")throw new q(`${e.toString()}: ${ot(this.value)}`);return this.value}unwrap_err(){if(this.kind==="ok")throw new q(`called \`Result.unwrap_err()\` on an \`Ok\` value: ${ot(this.value)}`);return this.value}expect_err(e){if(this.kind==="ok")throw new q(`${e.toString()}: ${ot(this.value)}`);return this.value}clone(){let e=j(this.value);return this.kind==="ok"?n.from_ok(e):n.from_err(e)}dehydrate(){let e=L(this.value);return this.kind==="ok"?{t:"Result",ok:e}:{t:"Result",err:e}}};function ot(n){if(typeof n=="string")return JSON.stringify(n);if(n!=null){let t=n.toString;if(typeof t=="function"&&t!==Object.prototype.toString)return t.call(n)}let e=JSON.stringify(n);return e===void 0?globalThis.String(n):e}var ce=class{constructor(e,t,r=0,i=e.length){this.items=e;this.usizeType=t;this.start=r;this.end=i;if(t.kind!=="usize"||!Number.isInteger(r)||!Number.isInteger(i)||r<0||i<r||i>e.length)throw new Error("Invalid slice");this.len()}items;usizeType;start;end;len(){return new V(BigInt(this.end-this.start),this.usizeType)}is_empty(){return new f(this.start===this.end)}get(e){let t=e.toIndex(this.end-this.start,this.usizeType.bits);return t===void 0?T.none():T.some(J.shared(()=>this.items[this.start+t]))}first(){return this.get(new V(0n,this.usizeType))}index(e){return this.get(e).unwrap()}last(){return this.start===this.end?T.none():this.get(new V(BigInt(this.end-this.start-1),this.usizeType))}to_vec(){return new Pe(this.items.slice(this.start,this.end).map(j),this.usizeType)}to_owned(){return this.to_vec()}},Pe=class extends ce{constructor(e,t){super(e,t)}as_slice(){let e=this.deref();return J.shared(()=>e)}deref(){return new ce(this.items,this.usizeType,this.start,this.end)}clone(){return this.to_vec()}dehydrate(){return{t:"Vec",bits:this.usizeType.bits,v:this.items.map(L)}}},st=class n extends ce{constructor(e,t){super(e,t)}as_slice(){let e=this.deref();return J.shared(()=>e)}deref(){return new ce(this.items,this.usizeType,this.start,this.end)}clone(){return new n(this.items.map(j),this.usizeType)}to_owned(){return this.clone()}dehydrate(){return{t:"Array",bits:this.usizeType.bits,v:this.items.map(L)}}};var at=class{constructor(e,t){this.id=e;this.inner=t}id;inner;read(){return new J(()=>this.inner(),e=>this.inner.set(e))}get(){return j(this.read().deref())}set(e){this.inner.set(e)}toggle(){this.inner.set(e=>e.not())}increment(){this.inner.set(e=>e instanceof V?e.increment():e.add(new W(1)))}decrement(){this.inner.set(e=>e instanceof V?e.decrement():e.sub(new W(1)))}push_str(e){this.inner.set(t=>new P(`${t}${e}`))}dehydrate(){return{t:"Signal",id:this.id,v:L(this.inner())}}};var hn="data-hearth-on:";function pn(n,e,t){if(!e.name.startsWith(hn))return;let r=e.name.substring(hn.length),o=z(e.value,`event @${r}`)(t.context);n.addEventListener(r,s=>o(new tt(s)),{signal:t.abortSignal})}function fn(n,e,t,r,i=!1){let o=z(t,"text expression"),{context:s}=r,a=!i;r.effect(()=>{let c=o(s);if(a){a=!1;return}kr(n,e,c)})}function kr(n,e,t){let r=n.parentNode;if(!r)return;let i=n.nextSibling;for(;i&&i!==e;){let s=i.nextSibling;r.removeChild(i),i=s}let o=Er(t);o.length>0&&r.insertBefore(document.createTextNode(o),e)}function Er(n){let e=n;for(;Rr(e);)e=e.deref();return e==null?"":Ze(e)?e.toNodeText():String(e)}function Rr(n){return n!==null&&typeof n=="object"&&typeof n.deref=="function"}var Lt=0,lt=class{constructor(e,t){this.name=e;this.keyField=t}name;keyField;rows=new Map;shadow=new Map;writes=new Map;listeners=new Set;ready=!1;readyCbs=[];sorted=new Map;hashes=new Map;get size(){return this.rows.size}get(e){return this.rows.get(e)}has(e){return this.rows.has(e)}values(){return this.rows.values()}get pendingCount(){return this.writes.size}isReady(){return this.ready}markReady(){if(this.ready)return;this.ready=!0;let e=this.readyCbs;this.readyCbs=[];for(let t of e)t()}onFirstReady(e){return this.ready?(e(),()=>{}):(this.readyCbs.push(e),()=>{this.readyCbs=this.readyCbs.filter(t=>t!==e)})}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}serverGet(e){return this.shadow.has(e)?this.shadow.get(e):this.rows.get(e)}serverKeys(){let e=[];for(let t of this.rows.keys())this.shadow.has(t)||e.push(t);for(let[t,r]of this.shadow)r!==void 0&&e.push(t);return e}applyServer(e,t=[],r=!0){let i=e.length>64,o=!1;for(let s of e){let a=String(s[this.keyField]);if(this.writes.has(a)){let l=this.shadow.get(a);if(l&&Me(l,s))continue;this.shadow.set(a,s),o=this.recompute(a,i)||o;continue}let c=this.rows.get(a);c&&Me(c,s)||(this.setVisible(a,c,s,i),o=!0)}for(let s of t){if(this.writes.has(s)){if(this.shadow.get(s)===void 0)continue;this.shadow.set(s,void 0),o=this.recompute(s,!1)||o;continue}let a=this.rows.get(s);a&&(this.setVisible(s,a,void 0,!1),o=!0)}return o&&r&&this.emit(),o}insert(e,t){let r=String(e[this.keyField]);if(r==="undefined"||r==="null")throw new Error(`[hearth] ${this.name}: row has no key`);if(this.rows.has(r))throw new Error(`[hearth] ${this.name}: duplicate key ${r}`);return this.write({id:++Lt,type:"insert",key:r,value:e},t)}update(e,t,r){if(!this.rows.has(e))throw new Error(`[hearth] ${this.name}: no row ${e}`);if(this.keyField in t&&String(t[this.keyField])!==e)throw new Error(`[hearth] ${this.name}: cannot change a row's key`);let i=this.rows.get(e),o={};for(let a in t)Object.is(i[a],t[a])||(o[a]=t[a]);if(Object.keys(o).length===0)return Promise.resolve();t=o;let s={...i,...t};return this.write({id:++Lt,type:"update",key:e,changes:t,value:s},r)}delete(e,t){if(!this.rows.has(e))throw new Error(`[hearth] ${this.name}: no row ${e}`);return this.write({id:++Lt,type:"delete",key:e},t)}write(e,t){let r=e.key,i=this.writes.get(r);i||(this.shadow.set(r,this.rows.get(r)),this.writes.set(r,i=[])),i.push(e),this.recompute(r,!1)&&this.emit();let o=s=>{let a=this.writes.get(r);if(!a)return;let c=s,l=!1;(c?.rows||c?.deleted)&&(l=this.applyServer(c.rows??[],c.deleted??[],!1));let u=a.indexOf(e);u>=0&&a.splice(u,1);let d;if(a.length===0){let m=this.shadow.get(r);this.writes.delete(r),this.shadow.delete(r),d=this.setVisible(r,this.rows.get(r),m,!1)}else d=this.recompute(r,!1);(d||l)&&this.emit()};return Promise.resolve().then(()=>t(e)).then(s=>o(s),s=>{throw o(),s})}recompute(e,t){let r=this.writes.get(e),i=r?.[r.length-1],o=i?i.type==="delete"?void 0:i.value:this.shadow.get(e);return this.setVisible(e,this.rows.get(e),o,t)}setVisible(e,t,r,i){return t===r||t&&r&&Me(t,r)?!1:(t&&this.unindex(t),r?(this.rows.set(e,r),this.index(r,i)):this.rows.delete(e),!0)}notify(){this.emit()}emit(){for(let e of this.listeners)e()}comparator(e){let t=this.keyField;return(r,i)=>{for(let{col:a,desc:c}of e){let l=Oe(r[a],i[a]);if(l!==0)return c?-l:l}let o=String(r[t]),s=String(i[t]);return o<s?-1:o>s?1:0}}sortedIndex(e,t){let r=this.sorted.get(e);return r||(r={spec:t,cmp:this.comparator(t),arr:null,pending:[]},this.sorted.set(e,r)),r.arr?r.pending.length&&wn(r):(r.arr=[...this.rows.values()].sort(r.cmp),r.pending=[]),r.arr}lookup(e,t){if(e===this.keyField){let r=this.rows.get(String(t));return r?[r]:mn}return this.hashIndex(e).get(t)??mn}hashIndex(e){let t=this.hashes.get(e);if(!t){t=new Map;for(let r of this.rows.values())gn(t,r[e],r);this.hashes.set(e,t)}return t}index(e,t){for(let[r,i]of this.hashes)i&&gn(i,e[r],e);for(let r of this.sorted.values())if(r.arr){if(t){r.pending.push(e);continue}wn(r),r.arr.splice(yn(r.arr,e,r.cmp),0,e)}}unindex(e){for(let[t,r]of this.hashes){let i=r?.get(e[t]);i&&(i.delete(e),i.size===0&&r.delete(e[t]))}for(let t of this.sorted.values()){if(!t.arr)continue;let r=t.pending.indexOf(e);if(r>=0){t.pending.splice(r,1);continue}let i=yn(t.arr,e,t.cmp);t.arr[i]!==e&&(i=t.arr.indexOf(e)),i>=0&&t.arr.splice(i,1)}}};function Oe(n,e){return n===e?0:n==null?e==null?0:-1:e==null?1:typeof n=="number"&&typeof e=="number"||typeof n=="string"&&typeof e=="string"?n<e?-1:n>e?1:0:typeof n=="boolean"&&typeof e=="boolean"?n===e?0:n?1:-1:0}function Me(n,e){for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}var mn=[];function gn(n,e,t){let r=n.get(e);r||n.set(e,r=new Set),r.add(t)}function yn(n,e,t){let r=0,i=n.length;for(;r<i;){let o=r+i>>>1;t(n[o],e)<0?r=o+1:i=o}return r}function wn(n){if(!n.arr||!n.pending.length)return;let e=n.pending.sort(n.cmp),t=n.arr,r=new Array(t.length+e.length),i=0,o=0,s=0;for(;i<t.length&&o<e.length;)r[s++]=n.cmp(t[i],e[o])<=0?t[i++]:e[o++];for(;i<t.length;)r[s++]=t[i++];for(;o<e.length;)r[s++]=e[o++];n.arr=r,n.pending=[]}function ue(n){return n==null?!1:typeof n=="boolean"?n:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:!0}function I(n,e){if("col"in n){let[t,r]=n.col;return i=>{let o=i[t]?.[r];return o===void 0?null:o}}if("lit"in n){let t=n.lit;return()=>t}if("param"in n){let t=_(e[n.param]);return()=>t}switch(n.op){case"eq":case"ne":{let t=I(n.l,e),r=I(n.r,e),i=n.op==="ne";return o=>{let s=t(o),a=r(o);return(Oe(s,a)===0&&Cr(s,a))!==i}}case"lt":case"lte":case"gt":case"gte":{let t=I(n.l,e),r=I(n.r,e),i=n.op;return o=>{let s=Oe(t(o),r(o));return i==="lt"?s<0:i==="lte"?s<=0:i==="gt"?s>0:s>=0}}case"contains":{let t=I(n.l,e),r=I(n.r,e),i="param"in n.r||"lit"in n.r,o=i?String(r({})??"").toLowerCase():"";return s=>{let a=t(s);if(typeof a!="string")return!1;let c=i?o:String(r(s)??"").toLowerCase();return Nr(a).includes(c)}}case"ilike":{let t=I(n.l,e),r=I(n.r,e);return i=>{let o=t(i),s=r(i);return typeof o=="string"&&typeof s=="string"&&Ir(s).test(o)}}case"in":{let t=I(n.l,e),r=I(n.r,e);return i=>{let o=r(i);return Array.isArray(o)&&o.includes(t(i))}}case"and":{let t=n.args.map(r=>I(r,e));return r=>t.every(i=>ue(i(r)))}case"or":{let t=n.args.map(r=>I(r,e));return r=>t.some(i=>ue(i(r)))}case"not":{let t=I(n.arg,e);return r=>!ue(t(r))}case"if":{let t=I(n.cond,e),r=I(n.then,e);return i=>ue(t(i))?r(i):!0}}}function Cr(n,e){return n==null||e==null?n==e:typeof n==typeof e}var ct=new Map;function Nr(n){let e=ct.get(n);return e===void 0&&(ct.size>2e5&&ct.clear(),e=n.toLowerCase(),ct.set(n,e)),e}var vn=new Map;function Ir(n){let e=vn.get(n);if(!e){let t=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");e=new RegExp(`^${t}$`,"is"),vn.set(n,e)}return e}function we(n,e=new Set){if(!n)return e;if("col"in n)e.add(n.col[0]);else{if("lit"in n||"param"in n)return e;"args"in n?n.args.forEach(t=>we(t,e)):"arg"in n?we(n.arg,e):"cond"in n?(we(n.cond,e),we(n.then,e)):(we(n.l,e),we(n.r,e))}return e}function _t(n,e,t){if(!n||"col"in n||"lit"in n||"param"in n)return[];if(n.op==="and")return n.args.flatMap(i=>_t(i,e,t));if(n.op!=="eq")return[];let r=(i,o)=>"col"in i&&i.col[0]===e&&("param"in o||"lit"in o)?[{col:i.col[1],v:"param"in o?_(t[o.param]):o.lit}]:[];return[...r(n.l,n.r),...r(n.r,n.l)]}function bn(n,e){let t=e(n.table);if(n.key!==t.keyField)throw new Error(`[hearth] key mismatch for ${n.table}: IR ${n.key}, store ${t.keyField}`);return t}function Ar(n,e,t){let r=bn(n.from,t),i=n.from.alias,o=dt(n.where,e),s=o?I(o,e):null,a=y=>[...we(y)].every(x=>x===i),c=n.joins.length===0||a(o)&&n.order.every(y=>a(y.expr)),l=n.order.map(y=>({f:I(y.expr,e),desc:y.desc})),u=r.keyField,d=y=>y.sort((x,v)=>{for(let{f:B,desc:A}of l){let R=Oe(B(x),B(v));if(R!==0)return A?-R:R}let C=String(x[i]?.[u]),D=String(v[i]?.[u]);return C<D?-1:C>D?1:0}),m=n.joins.map(y=>{let x=bn(y,t),[v,C]=y.on;"col"in C&&C.col[0]===y.alias||([v,C]=[C,v]);let D=I(v,e),B="col"in C&&C.col[0]===y.alias?C.col[1]:null,A=I({op:"eq",l:y.on[0],r:y.on[1]},e);return{j:y,m:x,probeFn:D,byCol:B,onFn:A}}),N=y=>{for(let{j:x,m:v,probeFn:C,byCol:D,onFn:B}of m){let A=[];for(let R of y){let M=!1;if(D!==null){let k=C(R);if(k!=null)for(let O of v.lookup(D,k))A.push({...R,[x.alias]:O}),M=!0}else for(let k of v.rows.values()){let O={...R,[x.alias]:k};ue(B(O))&&(A.push(O),M=!0)}!M&&x.kind!=="inner"&&A.push(R)}y=A}return y},b;if(c){let y={},x=R=>s?(y[i]=R,ue(s(y))):!0,v=n.limit,C=null,D=1/0;for(let{col:R,v:M}of _t(o,i,e)){let k=r.lookup(R,M),O=Array.isArray(k)?k.length:k.size;O<D&&(C=k,D=O)}let B=n.order.every(R=>"col"in R.expr&&R.expr.col[0]===i),A;if(n.order.length&&B&&v!=null&&D>v*8){let R=n.order.map(k=>({col:k.expr.col[1],desc:k.desc})),M=r.sortedIndex(JSON.stringify(R),R);A=[];for(let k=0;k<M.length&&A.length<v;k++){let O=M[k];x(O)&&A.push(O)}b=A.map(k=>({[i]:k}))}else{A=[];for(let R of C??r.rows.values())x(R)&&A.push(R);b=A.map(R=>({[i]:R})),n.order.length&&d(b),v!=null&&(b.length=Math.min(b.length,v))}b=N(b)}else{let y=o&&!("col"in o)&&!("lit"in o)&&!("param"in o)&&o.op==="and"?o.args:o?[o]:[],x=y.filter(M=>a(M)),v=y.filter(M=>!a(M)),C=x.length?I({op:"and",args:x},e):null,D=v.length?I({op:"and",args:v},e):null,B=r.rows.values(),A=1/0;for(let{col:M,v:k}of _t(x.length?{op:"and",args:x}:null,i,e)){let O=r.lookup(M,k),Se=Array.isArray(O)?O.length:O.size;Se<A&&(B=O,A=Se)}let R=[];for(let M of B){let k={[i]:M};(!C||ue(C(k)))&&R.push(k)}b=N(R),D&&(b=b.filter(M=>ue(D(M)))),n.order.length&&d(b),n.limit!=null&&(b.length=Math.min(b.length,n.limit))}let K=Object.entries(n.select).map(([y,x])=>[y,I(x,e)]);return b.map(y=>{let x={};for(let[v,C]of K)x[v]=C(y);return x})}var ut=class{constructor(e,t,r){this.query=e;this.params=t;this.tables=r;let i=new Set([e.from.table,...e.joins.map(o=>o.table)]);this.mirrors=[...i].map(o=>r(o));for(let o of this.mirrors)this.unlisten.push(o.listen(()=>this.changed()))}query;params;tables;planned=void 0;result=[];dirty=!0;scheduled=!1;subs=new Set;unlisten=[];mirrors;prevByKey=new Map;isReady(){return this.mirrors.every(e=>e.isReady())}onFirstReady(e){if(this.isReady()){e();return}let t=this.mirrors.filter(r=>!r.isReady()).length;for(let r of this.mirrors)r.isReady()||r.onFirstReady(()=>{--t===0&&(this.dirty=!0,e())})}get toArray(){return this.dirty&&this.recompute(),this.result}get size(){return this.toArray.length}subscribeChanges(e){return this.subs.add(e),{unsubscribe:()=>this.subs.delete(e)}}cleanup(){for(let e of this.unlisten)e();this.unlisten=[],this.subs.clear()}changed(){this.dirty=!0,!(this.subs.size===0||this.scheduled)&&(this.scheduled=!0,queueMicrotask(()=>{if(this.scheduled=!1,!!this.dirty&&this.recompute())for(let e of this.subs)e()}))}recompute(){this.dirty=!1;let e=performance.now(),t=Ar(this.query,this.params,this.tables);globalThis.__hearthRunMs=performance.now()-e;let r=this.query.key,i=this.prevByKey,o=new Map,s=t.length!==this.result.length;for(let a=0;a<t.length;a++){let c=t[a],l=String(c[r]),u=i.get(l);u&&Me(u,c)&&(t[a]=u),o.set(l,t[a]),t[a]!==this.result[a]&&(s=!0)}return this.prevByKey=o,this.result=t,s}};var Bt=class{tables=new Map;desc=new Map;version=oe(0);schema=null;seeds={};backfillScheduled=!1;init(e,t){this.schema=e;for(let[r,i]of Object.entries(t))this.seed(r,i)}seed(e,t){if(t.length!==0){if(this.tables.has(e)){this.apply(e,t,!1);return}(this.seeds[e]??=[]).push(...t)}}ensure(e){if(this.tables.has(e))return;let t=this.schema?.tables.find(i=>i.name===e);if(!t)throw new Error(`[hearth] unknown table ${e}`);let r=this.seeds[e];this.createTable(t,r),delete this.seeds[e],this.backfillStarted&&r&&this.syncTable(t).catch(i=>Ft(e,i)),this.backfillScheduled||(this.backfillScheduled=!0,setTimeout(()=>this.backfill().then(()=>window.__hearthBackfilled=performance.now()),0),this.watchFreshness())}createTable(e,t){this.desc.set(e.name,e);let r=new lt(e.name,e.key);this.tables.set(e.name,r),t&&t.length>0?(r.applyServer(t),r.markReady()):this.syncTable(e).catch(i=>Ft(e.name,i))}persistence=null;cache(){return this.persistence??=(async()=>{let e=document.querySelector("script[data-hearth-persistence]")?.dataset.hearthPersistence;if(!e||!this.schema||!globalThis.indexedDB)return null;let{Persistence:t}=await import(e);return t.open(JSON.stringify([this.schema.version,this.schema.scope]))})().catch(()=>null),this.persistence}cursors=new Map;restored=new Set;inflight=new Map;mutationEpoch=new Map;pending=new Map;syncTable(e){let t=this.inflight.get(e.name);return t||(t=this.sync(e).finally(()=>this.inflight.delete(e.name)),this.inflight.set(e.name,t)),t}async sync(e){let t=await this.cache();if(!this.restored.has(e.name)){this.restored.add(e.name);try{let r=this.mutationEpoch.get(e.name)??0,i=this.tables.get(e.name),o=new Set(i.serverKeys()),s=await t?.restore(e.name,a=>{r===(this.mutationEpoch.get(e.name)??0)&&i.applyServer(a.filter(c=>!o.has(String(c[e.key]))),[],!1)});this.tables.get(e.name).notify(),s&&r===(this.mutationEpoch.get(e.name)??0)&&(this.cursors.set(e.name,s),this.tables.get(e.name).markReady(),performance.mark(`hearth:restored:${e.name}`))}catch{t=null}}for(;;){await Promise.allSettled([...this.pending.get(e.name)??[]]);let r=this.mutationEpoch.get(e.name)??0,i=this.cursors.get(e.name),o=e.load+(e.load.includes("?")?"&":"?")+(i?"since="+encodeURIComponent(i):"sync=1"),s=await Or(o,this.schema?.on_unauthorized);if(r!==(this.mutationEpoch.get(e.name)??0)||this.pending.get(e.name)?.size)continue;let a=Array.isArray(s)?{rows:s,deleted:[],full:!0,cursor:""}:s;if(await this.applyChunked(e.name,a.rows,a.full,a.deleted,()=>r===(this.mutationEpoch.get(e.name)??0)),!(r!==(this.mutationEpoch.get(e.name)??0)||this.pending.get(e.name)?.size)){if(this.tables.get(e.name).markReady(),performance.mark(`hearth:synced:${e.name}`),a.cursor){this.cursors.set(e.name,a.cursor);try{await t?.save(e.name,e.key,a,i)}catch{this.persistence=Promise.resolve(null)}}return}}}apply(e,t,r,i=[]){let o=this.tables.get(e);if(!o)return;let s=i;if(r){let a=new Set(t.map(c=>String(c[o.keyField])));s=o.serverKeys().filter(c=>!a.has(c))}o.applyServer(t,s)&&this.version.set(a=>a+1)}watchFreshness(){let e=Date.now(),t=()=>{Date.now()-e<5e3||(e=Date.now(),this.backfill())};addEventListener("focus",t),addEventListener("online",t),document.addEventListener("visibilitychange",()=>document.visibilityState==="visible"&&t())}backfillStarted=!1;async backfill(){this.backfillStarted=!0;let e=[...this.desc.values()];await Promise.all(e.map(async t=>{try{await this.syncTable(t)}catch(r){Ft(t.name,r)}}))}async applyChunked(e,t,r=!0,i=[],o=()=>!0){if(t.length<=1e3){this.apply(e,t,r,i);return}let a=this.desc.get(e).key,c=new Set;for(let d=0;d<t.length;d+=1e3){if(!o())return;let m=t.slice(d,d+1e3);for(let N of m)c.add(String(N[a]));this.apply(e,m,!1),await _r()}if(!o())return;let l=this.tables.get(e),u=r&&l?l.serverKeys().filter(d=>!c.has(d)):i;u.length&&this.apply(e,[],!1,u)}table_=e=>(this.ensure(e),this.tables.get(e));live(e,t){return new ut(e,t,this.table_)}surrogate(e,t){return new Q(Object.entries(t).map(([r,i])=>[Mr(r),Tn(e[r],i)]))}update(e,t,r){this.ensure(e);let i=this.desc.get(e),o=String(_(t));this.track(e,this.tables.get(e).update(o,r,async s=>({rows:[await Dt(i.mutate,{op:"update",key:s.key,changes:s.changes},this.schema?.on_unauthorized)]})))}insert(e,t){this.ensure(e);let r=this.desc.get(e);(t[r.key]==null||t[r.key]==="")&&(t[r.key]=crypto.randomUUID()),this.track(e,this.tables.get(e).insert(t,async i=>({rows:[await Dt(r.mutate,{op:"insert",row:i.value},this.schema?.on_unauthorized)]})))}delete(e,t){this.ensure(e);let r=this.desc.get(e);this.track(e,this.tables.get(e).delete(String(_(t)),async i=>(await Dt(r.mutate,{op:"delete",key:i.key},this.schema?.on_unauthorized),{deleted:[i.key]})))}track(e,t){this.mutationEpoch.set(e,(this.mutationEpoch.get(e)??0)+1);let r=this.pending.get(e);r||this.pending.set(e,r=new Set),r.add(t),t.catch(i=>Lr(`Rolled back: ${i.message}`)).finally(()=>r.delete(t))}table(e){return{set:(t,r,i)=>this.update(e,t,{[String(_(r))]:_(i)}),insert:(...t)=>{let r={};for(let i=0;i+1<t.length;i+=2)r[String(_(t[i]))]=_(t[i+1]);this.insert(e,r)},remove:t=>this.delete(e,t),insert1:(...t)=>this.table(e).insert(...t),insert2:(...t)=>this.table(e).insert(...t),insert3:(...t)=>this.table(e).insert(...t),insert4:(...t)=>this.table(e).insert(...t),toggle2:(t,...r)=>this.table(e).toggle(t,...r),toggle3:(t,...r)=>this.table(e).toggle(t,...r),toggle:(t,...r)=>{let i=String(_(t));if(this.ensure(e),this.tables.get(e).has(i))this.delete(e,i);else{let o={};for(let s=0;s+1<r.length;s+=2)o[String(_(r[s]))]=_(r[s+1]);this.insert(e,o)}},dehydrate:()=>e}}get(e,t){return this.tables.get(e)?.get(String(_(t)))}},Sn=null;function ve(){return Sn??=new Bt,Sn}function Pr(n,e){if("param"in n)return e[n.param];if("lit"in n)return n.lit;throw new Error("[hearth] `if` conditions must be params or literals")}function _(n){let e=n;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(typeof r.deref=="function"&&!(r instanceof T)){e=r.deref();continue}if(r instanceof T)return r.is_some().dehydrate()?_(r.unwrap()):null;if(typeof r.dehydrate=="function"){let i=r.dehydrate();if(i&&typeof i=="object"&&"v"in i&&i.t!=="Record"){let o=i.v;return typeof o=="string"&&/^-?\d+$/.test(o)?Number(o):o}return i}return e}return e}function Tn(n,e){switch(e){case"string":return new P(String(n??""));case"bool":return new f(!!n);case"i64":return V.hydrate({t:"i64",bits:64,v:String(Math.trunc(Number(n??0)))});case"f64":return new W(Number(n??0));case"opt_string":return n==null?T.none():T.some(new P(String(n)));case"opt_i64":return n==null?T.none():T.some(Tn(n,"i64"))}}function Mr(n){return n.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function xn(n,e={redirect:"/login"}){let t=e==="error"?void 0:e.redirect,r=!1;if(t&&n.redirected){let i=new URL(t,location.href),o=new URL(n.url);r=o.origin===i.origin&&o.pathname===i.pathname}if(!(n.status!==401&&!r))throw t&&(location.href=t),new Error("unauthorized")}async function Or(n,e){let t=await fetch(n,{headers:{accept:"application/json"}});if(xn(t,e),!t.ok)throw new Error(`${t.status}`);return t.json()}async function Dt(n,e,t){let r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(e)});if(xn(r,t),!r.ok)throw new Error(`${r.status} ${(await r.text()).slice(0,120)}`);let i=await r.text();return i?JSON.parse(i):null}function Ft(n,e){(globalThis.__hearthErrors??=[]).push(`load ${n}: ${e?.message??e}`),console.error("[hearth] load",n,e)}function Lr(n){let e=Object.assign(document.createElement("div"),{className:"hearth-toast",textContent:n});document.body.append(e),setTimeout(()=>e.remove(),3500)}function dt(n,e){if(!n||"col"in n||"lit"in n||"param"in n)return n;if(n.op==="if")return _(Pr(n.cond,e))?dt(n.then,e):null;if(n.op==="and"){let t=[];for(let r of n.args){let i=dt(r,e);i&&(!("col"in i)&&!("lit"in i)&&!("param"in i)&&i.op==="and"?t.push(...i.args):t.push(i))}return t.length===0?null:t.length===1?t[0]:{...n,args:t}}return n}function _r(){let n=globalThis.scheduler;return n?.postTask?n.postTask(()=>{},{priority:"background"}):new Promise(e=>setTimeout(e,0))}var Le=new WeakMap,Vt=0;function ht(n){Vt++;try{return n()}finally{Vt--}}function Ce(n){if(!Vt)for(let e=n;e;e=e.parent){let t=Le.get(e);if(t)return t}}var _e=class{constructor(e,t=!0){this.scope=e;t&&Le.set(e,this),e.abortSignal.addEventListener("abort",()=>{this.jobs.length=0,Le.get(e)===this&&Le.delete(e)})}scope;jobs=[];scheduled=!1;draining=!1;failed=!1;add(e){if(!this.scope.isDisposed&&(this.jobs.push(e),!this.scheduled&&!this.draining)){this.scheduled=!0;let t=()=>{let r=globalThis.scheduler;r?.postTask?r.postTask(()=>this.slice(),{priority:"background"}):typeof globalThis.requestIdleCallback=="function"?requestIdleCallback(()=>this.slice()):setTimeout(()=>this.slice(),0)};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0,signal:this.scope.abortSignal})}}reportError(e){this.failed=!0,this.scope.runtime.reportError(e)}run(e){try{e()}catch(t){this.reportError(t)}}slice(){if(this.scheduled=!1,this.scope.isDisposed)return;let e=performance.now()+4;this.draining=!0;try{do{let t=this.jobs.shift();t&&this.run(t)}while(this.jobs.length&&performance.now()<e)}finally{this.draining=!1}this.jobs.length&&this.add(()=>{})}finish(){this.draining=!0;try{for(;this.jobs.length&&!this.scope.isDisposed;)this.run(this.jobs.shift())}finally{this.draining=!1,Le.delete(this.scope)}}};var kn=new WeakMap;function Cn(n,e,t,r){let i=ve();if(t.seed){let h=document.getElementById(t.seed);if(!h)throw new Error(`[hearth] missing seed ${t.seed}`);let g=JSON.parse(h.textContent??"{}");for(let[E,F]of Object.entries(g))i.seed(E,F)}let o=Mn(t.template);if(!o)throw new Error(`[hearth] missing template ${t.template}`);let s=t.params.map(h=>z(h,"list param")),a=new Map,c=new Map,l=[],u=256,d=()=>n.parentNode;for(let h=e.previousSibling;h&&h!==n;h=h.previousSibling){if(h.nodeType===Node.COMMENT_NODE&&h.data.startsWith("::hearth::js(")){let E=h.data.slice(13,-1).split("").map(En);kn.set(n,E),h.remove();break}if(h.nodeType===Node.COMMENT_NODE&&h.data.trim()==="::hearth::item-end")break}let m=n.nextSibling,N=[];for(;m&&m!==e;){if(m.nodeType===Node.COMMENT_NODE){let h=/^::hearth::item\((.*)\)$/.exec(m.data.trim());if(h){let g=m.nextSibling;for(;g&&!(g.nodeType===Node.COMMENT_NODE&&g.data.trim()==="::hearth::item-end");)g=g.nextSibling;if(!g)break;let E=En(h[1]);N.push({key:E.startsWith('"')?JSON.parse(E):E,start:m,end:g}),m=g.nextSibling;continue}}m=m.nextSibling}let b=null,K=null,y=null,x=!1,v=(h,g,E,F)=>{let U=oe(i.surrogate(g,t.query.types)),pe=new H(r,r.runtime,r.unit);pe.context=r.context.withRow(t.template,{read:()=>U()});let Z,ee;if(E)Z=E.start,ee=E.end;else{Z=document.createComment(`::hearth::item(${JSON.stringify(h)})`),ee=document.createComment("::hearth::item-end");let te=document.createDocumentFragment();te.append(Z,o.content.cloneNode(!0),ee),F?F.append(te):d().insertBefore(te,e)}let Be=kn.get(n),Ve=E&&Be?Te(Be):null;try{de(F??d(),Z,ee,pe,new Set,E===null)}finally{Ve&&Te(Ve)}return{key:h,start:Z,end:ee,scope:pe,row:U,raw:g}},C=h=>{let g=[];for(let E=h.start;E&&(g.push(E),E!==h.end);E=E.nextSibling);return g},D=0,B=()=>{let h=++D,g=Ce(r),E=A(),F=()=>{if(!(r.isDisposed||h!==D))try{if(g)G(()=>E.next()).done||g.add(F);else for(;!G(()=>E.next()).done;);}catch(U){g?g.reportError(U):In(U,t.template)}};g?g.add(F):F()};function*A(){if(!b||!b.isReady())return;let h=performance.now(),g=b.toArray;!x&&g.length>N.length&&N.length>0&&(g=g.slice(0,N.length),Rn(B));let E=t.query.key;if(!x){x=!0;let w=new Map(g.map(p=>[String(p[E]),p]));for(let p of N){yield;let S=w.get(p.key);if(S){let Y=v(p.key,S,p);a.set(p.key,Y),c.set(Y.start,Y)}}}let F=new Set,U=[],pe=new Set;for(let w of g){yield;let p=String(w[E]);if(F.has(p))continue;F.add(p);let S=a.get(p);S&&S.raw!==w&&(Dr(S.raw,w,t.query.types)||S.row.set(i.surrogate(w,t.query.types)),S.raw=w),S||(S={key:p,raw:w,start:null,end:null,scope:null,row:null},pe.add(S)),U.push(S)}let Z=[];for(let[w,p]of a)F.has(w)||Z.push(p);for(let w of Z){yield,a.delete(w.key);let p=C(w);if(l.length<u){let S=document.createDocumentFragment();S.append(...p),l.push({it:w,frag:S})}else{c.delete(w.start),w.scope.dispose();for(let S of p)S.remove()}}let ee=new Map;{let w=0;for(let p=n.nextSibling;p&&p!==e;p=p.nextSibling){if(p.nodeType!==8)continue;let S=c.get(p);S&&a.get(S.key)===S&&ee.set(S,w++)}}let Be=U.map(w=>pe.has(w)?-1:ee.get(w)??-1),Ve=Fr(Be),te=e;for(let w=U.length-1;w>=0;w--){yield;let p=U[w];if(pe.has(p)){let S=p.raw,Y=p.key,vt=l.pop();if(vt)p=vt.it,c.delete(p.start),p.key=Y,p.start.data=`::hearth::item(${JSON.stringify(Y)})`,p.raw=S,d().insertBefore(vt.frag,te),p.row.set(i.surrogate(S,t.query.types));else{p=v(Y,S,null);let Wt=document.createDocumentFragment();Wt.append(...C(p)),d().insertBefore(Wt,te)}c.set(p.start,p),a.set(Y,p),U[w]=p}else if(!Ve[w]){let S=document.createDocumentFragment();S.append(...C(p)),d().insertBefore(S,te)}te=p.start}{let w=n.nextSibling,p=0;for(;w&&w!==e;){yield;let S=U[p];if(S&&w===S.start){w=S.end.nextSibling,p++;continue}let Y=w.nextSibling;w.remove(),w=Y}}window.__hearthListMs=performance.now()-h}let R=Ce(r);R&&t.query.limit===1&&R.add(()=>{if(r.isDisposed||a.size||l.length)return;let h=document.createDocumentFragment(),g=v("",{},null,h);l.push({it:g,frag:h})});let M=4,k=new Map,O=null,Se=!1,Ut=!1,zt=!0,qt=()=>{if(Se=!1,r.isDisposed||!O)return;let h=O;O=null;let g=performance.now();G(()=>jt(h)),Ut=performance.now()-g>12};r.effect(()=>{let h=s.map(g=>_(g(r.context)));if(zt){zt=!1,G(()=>jt(h));return}O=h,Se||(Se=!0,Ut||performance.now()-An<50?Rn(qt):queueMicrotask(qt))});function jt(h){let g=JSON.stringify(h),E=k.get(g);E?k.delete(g):E=i.live(t.query,h),y?.(),b&&K!==null&&Vn(K,b),b=E,K=g;let F=b.subscribeChanges(()=>queueMicrotask(B)),U=performance.now();b.onFirstReady(()=>{B(),window.__hearthQueryMs=performance.now()-U}),y=()=>F.unsubscribe(),B()}function Vn(h,g){for(k.set(h,g);k.size>M;){let[E,F]=k.entries().next().value;k.delete(E),F.cleanup()}}r.abortSignal.addEventListener("abort",()=>{y?.(),b?.cleanup();for(let h of k.values())h.cleanup();for(let{it:h}of l)h.scope.dispose();l.length=0,k.clear()})}function Nn(n,e,t,r,i){let o=Mn(r);if(!o)throw new Error(`[hearth] missing template ${r}`);let s=o,a=z(t,"when condition"),c=n.parentNode,l=null,u=null,d=null;i.effect(()=>{let b=!!_(a(i.context));G(()=>N(b))}),!l&&i.context.rows.size===0&&new _e(i,!1).add(()=>{if(!(i.isDisposed||l))try{m()}catch(K){In(K,r)}});function m(){l=new H(i,i.runtime,i.unit),d=new _e(l),u.append(s.content.cloneNode(!0)),de(u,null,null,l,new Set,!0)}function N(b){if(!u)if(u=document.createElement("hearth-when"),u.style.display="contents",n.nextSibling!==e){for(;n.nextSibling&&n.nextSibling!==e;)u.append(n.nextSibling);c.insertBefore(u,e),l=new H(i,i.runtime,i.unit),de(u,null,null,l)}else c.insertBefore(u,e);b&&(l||(u.append(s.content.cloneNode(!0)),l=new H(i,i.runtime,i.unit),de(u,null,null,l,new Set,!0)),d?.finish(),d?.failed&&(l?.dispose(),u.replaceChildren(s.content.cloneNode(!0)),l=new H(i,i.runtime,i.unit),ht(()=>de(u,null,null,l,new Set,!0))),d=null),u.style.display=b?"contents":"none"}}function En(n){return n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function In(n,e){(window.__hearthErrors??=[]).push(`${e}: ${n?.stack??n}`),console.error("[hearth]",e,n)}var An=-1/0;typeof document<"u"&&document.addEventListener("input",n=>{let e=n.target;e&&(e.tagName==="TEXTAREA"||e.tagName==="INPUT"&&!/^(checkbox|radio|range|color|file)$/.test(e.type))&&(An=performance.now())},!0);function Rn(n){let e=globalThis.scheduler,t=()=>e?.postTask?e.postTask(n,{priority:"user-visible"}):setTimeout(n,0);document.visibilityState==="visible"?requestAnimationFrame(t):t()}function Dr(n,e,t){for(let r in t)if(n[r]!==e[r])return!1;return!0}var De=null;function Pn(n,e){for(let t of n.querySelectorAll("template"))t.id&&!e.has(t.id)&&e.set(t.id,t),Pn(t.content,e)}function Mn(n){return(!De||!De.has(n))&&(De=new Map,Pn(document,De)),De.get(n)??null}function Fr(n){let e=n.length,t=new Int32Array(e).fill(-1),r=[];for(let s=0;s<e;s++){let a=n[s];if(a<0)continue;let c=0,l=r.length;for(;c<l;){let u=c+l>>>1;n[r[u]]<a?c=u+1:l=u}c>0&&(t[s]=r[c-1]),r[c]=s}let i=new Array(e).fill(!1),o=r.length?r[r.length-1]:-1;for(;o>=0;)i[o]=!0,o=t[o];return i}var $t=/^\s*::hearth::list::start\(([\s\S]*)\)\s*$/,On=/^\s*::hearth::when::start\(([\s\S]*)\)\s*$/,Br=/^\s*::hearth::(list|when)::end\s*$/;function Vr(n){return n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function de(n,e,t,r,i=new Set,o=!1){let s=$r(n,e,t,r,i,o),a=Ce(r),c=Yt();if(a){let l=()=>{if(r.isDisposed)return;let u=Te(c);try{s.next().done||a.add(l)}finally{Te(u)}};a.add(l)}else for(;!s.next().done;);}function*$r(n,e,t,r,i,o){let s=document.createTreeWalker(n,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);e&&(s.currentNode=e);let a=[{scope:r,shard:null,region:null}],c=[],l=u=>{try{u()}catch(d){let m=Ce(r);if(!m)throw d;m.reportError(d)}};for(let u=s.nextNode();u&&!(t&&u===t);u=s.nextNode()){yield;let d=a[a.length-1]?.scope;if(d===void 0)throw new Error("Stack was empty");if(u.nodeType===Node.ELEMENT_NODE){l(()=>Hr(u,d));continue}let m=u.data,N=$t.exec(m)??On.exec(m);if(N){let K=u,y=0,x=null;for(let v=s.nextNode();v;v=s.nextNode()){if(v.nodeType!==Node.COMMENT_NODE)continue;let C=v.data;if($t.test(C)||On.test(C))y++;else if(Br.test(C)){if(y===0){x=v;break}y--}}if(!x)throw new Error("[hearth] unterminated region");l(()=>{let v=JSON.parse(Vr(N[1]));$t.test(m)?Cn(K,x,v,d):Nn(K,x,v.cond,v.template,d)});continue}let b=$e(u);b&&l(()=>Ur(b,u,a,c,i,o))}}function Hr(n,e){for(let t of Array.from(n.attributes))sn(n,t,e),pn(n,t,e);n instanceof HTMLAnchorElement&&n.getAttribute(Je)==="viewport"&&e.runtime.navigation.observe(n,e.abortSignal)}function Ur(n,e,t,r,i,o=!1){let s=t[t.length-1]?.scope;if(s===void 0)throw new Error("Stack was empty");switch(n.kind){case"signal":{let{context:a,registry:c}=s.runtime;(c.insert(n.id,a.hydrate(n.value))||i.delete(n.id))&&s.signalIds.add(n.id);break}case"dep":{s.dependencies.add(n.id);break}case"connect":{s.requiresConnection=!0;break}case"expr-start":{r.push({start:e,js:n.js,scope:s});break}case"expr-end":{let a=r.pop();if(!a)throw new Error("Unbalanced text expression: end marker has no start");fn(a.start,e,a.js,a.scope,o);break}case"region-start":{let a=new H(s,s.runtime,s.unit),c={id:n.id,start:e,end:null,scope:a};s.regions.set(n.id,c),t.push({scope:a,shard:null,region:c});break}case"region-end":{let a=t[t.length-1]?.region;if(!a)throw new Error(`Unbalanced region: end marker ${n.id} has no matching start`);if(a.id!==n.id)throw new Error(`Mismatched region: end ${n.id} does not match start ${a.id}`);a.end=e,t.pop();break}case"shard-start":{let a=new Qe(s,s.runtime,n.path,n.identity,n.exprs,e);t.push({scope:a.contentScope,shard:a,region:null});break}case"shard-end":{let a=t[t.length-1]?.shard;if(!a)throw new Error(`Unbalanced shard: end marker ${n.identity} has no matching start`);if(a.identity!==n.identity)throw new Error(`Mismatched shard: end ${n.identity} does not match start ${a.identity}`);a.attachEnd(e),t.pop(),a.startWatching();break}}}function he(n,e){if(n!==null)switch(typeof n){case"string":return new P(n);case"number":return new W(n);case"boolean":return new f(n);case"bigint":case"symbol":case"undefined":case"function":throw new Error(`Unknown surrogate type: ${typeof n}`);case"object":if(Array.isArray(n))return new se(n.map(t=>he(t,e)));switch(n.t){case"u8":case"u16":case"u32":case"u64":case"u128":case"usize":case"i8":case"i16":case"i32":case"i64":case"i128":case"isize":return V.hydrate(n);case"str":return new Re(n.v);case"Option":return n.v===null?T.none():T.some(he(n.v,e));case"Result":return"ok"in n?le.from_ok(he(n.ok,e)):le.from_err(he(n.err,e));case"Vec":case"Array":case"Slice":{if(!Array.isArray(n.v)||Object.keys(n).some(o=>!["t","bits","v"].includes(o)))throw new Error("Invalid collection payload");let t=Ee("usize",n.bits),r=n.v.map(o=>he(o,e));if(n.t==="Vec")return new Pe(r,t);if(n.t==="Array")return new st(r,t);let i=new ce(r,t);return J.shared(()=>i)}case"Record":{if(typeof n.v!="object"||n.v===null||Array.isArray(n.v)||Object.keys(n).some(t=>!["t","v"].includes(t)))throw new Error("Invalid record payload");return new Q(Object.entries(n.v).map(([t,r])=>[t,he(r,e)]))}case"Signal":return e.signal(n.id);case"Procedure":return new it(e,n.path);default:throw new Error(`Unknown surrogate type: ${n.t}`)}}}var pt=null;function Fe(){return pt||(pt=oe(location.pathname+location.search),document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;let e=n.target?.closest?.("a[data-hearth-link]");e&&(n.preventDefault(),be.navigate(e.href))}),addEventListener("popstate",()=>be.navigate(location.href,!1)),history.replaceState({hearth:!0},""),pt)}var be={init:Fe,path(){return new P(Fe()())},segment(n){let e=Fe()().split("?")[0].split("/").filter(Boolean);return new P(e[n]??"")},query(n){let e=Fe()().split("?")[1]??"";return new P(new URLSearchParams(e).get(n)??"")},navigate(n,e=!0){let t=new URL(n,location.href);if(t.origin!==location.origin){location.href=n;return}e&&history.pushState({hearth:!0},"",t);let r=performance.now();Fe().set(t.pathname+t.search),requestAnimationFrame(()=>window.__hearthNavMs=performance.now()-r),e&&scrollTo(0,0)}};var ft=class n{constructor(e,t=new Map){this.registry=e;this.rows=t}registry;rows;withRow(e,t){let r=new Map(this.rows);return r.set(e,t),new n(this.registry,r)}row(e){let t=this.rows.get(e);if(!t)throw new Error(`cx.row(${e}) outside its client list`);return t.read()}get route(){return be}get db(){return ve()}expression(e){return z(e,"captured expression")(this)}hydrate(e){return he(e,this)}signal(e){return new at(e,this.registry.handle(e))}some(e){return T.some(e)}none(){return T.none()}ok(e){return le.from_ok(e)}err(e){return le.from_err(e)}record(e){return new Q(Object.entries(e))}tuple(e){return new se(e)}};var zr="hearth-runtime",qr=(n,e)=>new WebSocket(n,e),jr=1,Wr=1e3,Kr=3e4,mt=class{constructor(e,t,r=qr){this.url=e;this.reportError=t;this.open=r}url;reportError;open;socket=null;retry=null;attempt=0;lastRun=0;members=new Set;runIds=new Map;runs=new Map;get isOpen(){return this.socket?.readyState===jr}join(e){if(this.members.has(e)){this.isOpen&&!this.runIds.has(e)&&this.run(e);return}this.members.add(e),this.isOpen?this.run(e):this.socket===null&&this.retry===null&&this.connect()}leave(e){!this.members.delete(e)||this.members.size>0||queueMicrotask(()=>{this.members.size===0&&this.disconnect()})}run(e){let t=this.socket;if(t===null||!this.isOpen)return!1;this.stop(e),this.lastRun+=1;let r=this.lastRun;this.runIds.set(e,r),this.runs.set(r,{target:e,render:re()});let{url:i,headers:o,body:s}=e.rerunRequest(),{pathname:a,search:c}=new URL(i,location.href),l=`${a}${c}`;return t.send(JSON.stringify({run:r,method:"POST",path:l,headers:o,body:s})),!0}stop(e){let t=this.runIds.get(e);t!==void 0&&(this.runIds.delete(e),this.runs.delete(t),this.isOpen&&this.socket?.send(JSON.stringify({stop:t})))}remove(e){this.stop(e),this.leave(e)}connect(){let e=new URL(this.url(),location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:";let t=this.open(e.href,zr);this.socket=t,t.addEventListener("open",()=>{if(this.socket===t){this.attempt=0;for(let r of[...this.members])r.connectionOpened()}}),t.addEventListener("message",r=>this.receive(r.data)),t.addEventListener("close",()=>{this.socket===t&&(this.socket=null,this.forgetRuns(),this.scheduleReconnect())})}scheduleReconnect(){if(this.members.size===0||this.retry!==null)return;let e=Math.min(Wr*2**this.attempt,Kr);this.attempt+=1,this.retry=setTimeout(()=>{this.retry=null,this.members.size>0&&this.connect()},e)}disconnect(){this.retry!==null&&(clearTimeout(this.retry),this.retry=null);let e=this.socket;this.socket=null,this.forgetRuns(),this.attempt=0,e?.close()}forgetRuns(){this.runIds.clear(),this.runs.clear()}receive(e){if(typeof e!="string")return;let t;try{t=JSON.parse(e)}catch(s){this.reportError(s);return}if(t.run===void 0){let s=t.frame.t==="error"?t.frame.status:"";this.reportError(new Error(`Connected request rejected: ${s}`));return}let r=this.runs.get(t.run);if(r===void 0)return;let i=()=>{if(this.runs.get(t.run)===r)try{Ue(r.target,t.frame,"Connected",r.render)}catch(s){r.target.reportError(s)}},o=t.frame;r.pending||(o.t==="snapshot"||o.t==="swap")&&/#[a-f0-9]{64}:/.test(o.html)?r.pending=(r.pending??Promise.resolve()).then(async()=>{(o.t==="snapshot"||o.t==="swap")&&await X(o.html,o.t==="snapshot"&&r.target.documentSnapshot===!0),i()}).catch(s=>r.target.reportError(s)):i()}};var Ln="hearth:dev-runtime:v2";function _n(n,e){let t=fe(n),r=new TextEncoder,i=new ReadableStream({async pull(o){try{let s=await t.next();if(e.aborted||s.done){o.close();return}let a=s.value;if((a.t==="snapshot"||a.t==="swap")&&await X(a.html,a.t==="snapshot"),e.aborted){o.close();return}o.enqueue(r.encode(JSON.stringify(a)+`
`))}catch(s){o.error(s)}},async cancel(){await t.return(void 0)}});return new Response(i,{status:n.status,statusText:n.statusText,headers:n.headers})}var gt=class extends xe{label="Page";documentSnapshot=!0;devRefresh=null;get pendingRefresh(){return this.devRefresh}constructor(e){super(null,e)}readInputs(){}rerunRequest(){return{url:Ht(),headers:{"Content-Type":"application/json",[qe]:"true"},body:this.signalBody()}}signalBody(){let e=G(()=>this.contentScope.collectSignalValues());return JSON.stringify({signals:e})}replaceDocument(e,t){if(this.isDisposed)return;this.runtime.connection.stop(this);let r=document.activeElement;r instanceof HTMLElement&&r.blur(),this.replace((i,o)=>{let s=document.documentElement,a=e.documentElement;for(let c of Array.from(s.attributes))a.hasAttribute(c.name)||s.removeAttribute(c.name);for(let c of Array.from(a.attributes))s.setAttribute(c.name,c.value);me(s,null,null,a.childNodes),this.runtime.hydrate(document,null,null,i,o)},t)}listenForDevRefresh(){window.addEventListener(Ln,e=>{let{detail:t}=e,r=re();t.runtime={request:async(i,o)=>{this.devRefresh=o,o.then(()=>{this.devRefresh===o&&(this.devRefresh=null)});let s=await this.request(i,ne);return s.ok&&!s.redirected?_n(s,i):s},replace:i=>{this.runtime.connection.stop(this),this.replace((o,s)=>{i(),this.runtime.hydrate(document,null,null,o,s)},r)},swap:(i,o)=>this.applySwap(i,o,r)}},{signal:this.lifetime.abortSignal})}prepare(e){let t=new DOMParser().parseFromString(e,"text/html");return Array.from(t.body.childNodes)}insert(e,t,r){me(document.body,null,null,e),this.runtime.hydrate(document,null,null,t,r)}};function Ht(){return`${location.origin}${location.pathname}${location.search}`}var yt=class{signals=new Map;has(e){return this.signals.has(e)}get(e){return this.signals.get(e)}insert(e,t){return this.signals.has(e)?!1:(this.signals.set(e,oe(t)),!0)}delete(e){this.signals.delete(e)}handle(e){let t=this.signals.get(e);if(!t)throw new Error(`Unknown signal id: ${e}`);return t}read(e){return this.handle(e)()}};var wt=class{registry=new yt;context=new ft(this.registry);connection=new mt(Ht,e=>this.reportError(e));page=new gt(this);navigation=new Ke(this);loaded=!1;start(e){this.hydrate(e,null,null,this.page.contentScope),this.page.startWatching(),this.navigation.start()}whenLoaded(e,t){if(!this.loaded&&document.readyState!=="complete"){let i=()=>{this.loaded=!0,e()};return window.addEventListener("load",i,{once:!0,signal:t}),!1}let r=this.page.pendingRefresh??this.navigation.pending;return r===null?!0:(r.then(()=>{t.aborted||e()}),!1)}reportError(e){console.error("[hearth]",e)}hydrate(e,t,r,i,o=new Set){ht(()=>de(e,t,r,i,o))}};async function Dn(n,e){let t=document.body,r=t.inert;t.inert=!0,t.setAttribute("aria-busy","true");try{await n(),e()}finally{t.inert=r,t.removeAttribute("aria-busy")}}var Fn=document.getElementById("hearth-boot");if(Fn){let n=JSON.parse(Fn.textContent??"{}");ve().init(n.schema,n.snapshot??{}),be.init(),window.__hearth={db:ve(),boot:n,route:be}}else document.querySelector("[data-hearth-clear]")&&setTimeout(()=>{try{globalThis.indexedDB?.deleteDatabase("hearth-sync-v1")}catch{}},0);var Bn=new wt,Jr=()=>{Bn.start(document),Bn.page.listenForDevRefresh(),performance.mark("hearth:ready")};await Dn(()=>X(document),Jr);
//# sourceMappingURL=index.js.map