const e=new TextDecoder("utf-8"),t=new TextEncoder;class n{constructor(e,t){this.getUint8Memory=e,this.pointer=0,this.ptr=Number(t>>32n),this.size=Number(t%2n**32n),this.dataView=new DataView(this.getUint8Memory().buffer,this.ptr,this.size)}getByte(){const e=this.dataView.getUint8(this.pointer);return this.pointer+=1,e}setByte(e){this.dataView.setUint8(this.pointer,e),this.pointer+=1}getU16(){const e=this.dataView.getUint16(this.pointer);return this.pointer+=2,e}setU16(e){this.dataView.setUint16(this.pointer,e),this.pointer+=2}getU32(){const e=this.dataView.getUint32(this.pointer);return this.pointer+=4,e}setU32(e){this.dataView.setUint32(this.pointer,e),this.pointer+=4}getF64(){const e=this.dataView.getFloat64(this.pointer);return this.pointer+=8,e}setF64(e){this.dataView.setFloat64(this.pointer,e),this.pointer+=8}getBuffer(){const e=this.getU32(),t=this.getUint8Memory().subarray(this.ptr+this.pointer,this.ptr+this.pointer+e);return this.pointer+=e,t}setBuffer(e){const t=e.length;this.setU32(t);this.getUint8Memory().subarray(this.ptr+this.pointer,this.ptr+this.pointer+t).set(e),this.pointer+=t}getString(){return e.decode(this.getBuffer())}setString(e){const n=t.encode(e);this.setBuffer(n)}}const o=1,r=2,s=3,i=4,a=5,c=6,l=7,d=8,h=9,u=e=>{if(!0===e||!1===e||null==e)return 1;if("string"==typeof e)return 5+t.encode(e).length;if("number"==typeof e)return 9;if(e instanceof Uint8Array)return 5+e.length;if(Array.isArray(e)){let t=5;for(const n of e)t+=u(n);return t}if("object"==typeof e&&null!==e){let n=3;for(const[o,r]of Object.entries(e))n+=4+t.encode(o).length,n+=u(r);return n}throw new Error("jsJsonGetSize: Unknown type "+typeof e)},m=e=>{const t=e.getByte();if(t===o)return!0;if(t===r)return!1;if(t===s)return null;if(t!==i){if(t===a)return e.getString();if(t===c)return e.getF64();if(t===l){const t=e.getU32(),n=[];for(let o=0;o<t;o++)n.push(m(e));return n}if(t===d){const t=e.getU16(),n={};for(let o=0;o<t;o++){const t=e.getString(),o=m(e);n[t]=o}return n}if(t===h)return e.getBuffer().slice();throw new Error(`jsJsonDecodeItem: Unknown type id ${t}`)}},f=(e,t)=>{if(!0!==e)if(!1!==e)if(null!==e)if(void 0!==e){if("string"==typeof e)return t.setByte(a),void t.setString(e);if("number"==typeof e)return t.setByte(c),void t.setF64(e);if(e instanceof Uint8Array)return t.setByte(h),void t.setBuffer(e);if(!Array.isArray(e)){if("object"==typeof e&&null!==e){const n=Object.entries(e);t.setByte(d),t.setU16(n.length);for(const[e,o]of n)t.setString(e),f(o,t);return}throw new Error("saveJsJsonToBufferItem: Unknown type "+typeof e)}t.setByte(l),t.setU32(e.length);for(const n of e)f(n,t)}else t.setByte(i);else t.setByte(s);else t.setByte(r);else t.setByte(o)},g=async(e,t)=>{const o=await(async(e,t)=>{if("function"==typeof WebAssembly.instantiateStreaming){const n=fetch(e);try{return await WebAssembly.instantiateStreaming(n,t)}catch(e){console.warn("`WebAssembly.instantiateStreaming` failed. This could happen if your server does not serve wasm with `application/wasm` MIME type, but check the original error too. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}}console.info("fetchModule by WebAssembly.instantiate");const n=await fetch(e),o=await n.arrayBuffer();return await WebAssembly.instantiate(o,t)})(e,t);let r=new Uint8Array(1);const s=()=>{if(o.instance.exports.memory instanceof WebAssembly.Memory)return r.buffer!==o.instance.exports.memory.buffer&&(r=new Uint8Array(o.instance.exports.memory.buffer)),r;throw Error("Missing memory")},i=o.instance.exports;return{exports:i,getUint8Memory:s,wasmCommand:e=>{const t=u(e),o=i.vertigo_export_alloc_block(t),r=new n(s,o);f(e,r);let a=i.vertigo_export_wasm_command(o);if(0n===a)return null;const c=new n(s,a),l=m(c);return i.vertigo_export_free_block(a),l}}};class p{constructor(){this.events=new Set}on(e){let t=!0;const n=n=>{t&&e(n)};return this.events.add(n),()=>{t=!1,this.events.delete(n)}}trigger(e){const t=Array.from(this.events.values());for(const n of t)try{n(e)}catch(e){console.error(e)}}}class v{constructor(){this.inner=null,this.resolve=e=>{const t=this.inner;this.inner=null,null!==t&&t.resolve(e)},this.isFulfilled=()=>null===this.inner;const[e,t]=(()=>{let e=null,t=null;const n=new Promise((n,o)=>{e=n,t=o});if(null===e)throw Error("createPromiseValue - resolve is null");if(null===t)throw Error("createPromiseValue - reject is null");return[{resolve:e,reject:t},n]})();this.inner=e,this.promise=t}}const w=async(e,t)=>{console.info(`${e} wait ${t}ms`),await(async e=>new Promise(t=>{setTimeout(t,e)}))(t),console.info(`${e} go forth`)};class y{constructor(e){this.host=e,this.formatLog=e=>`Socket ${this.host} ==> ${e}`}}class b{constructor(e,t){this.eventMessage=new p,this.close=e,this.send=t}static connect(e,t,n){const o=new v,r=new v,s=new WebSocket(t);let i=!1;console.info(e.formatLog("starting ..."));const a=()=>{i||(console.info(e.formatLog("close")),i=!0,o.resolve(null),r.resolve(),s.close())},c=new b(a,e=>{i||s.send(e)});setTimeout(()=>{!1===o.isFulfilled()&&(console.error(e.formatLog(`timeout (${n}ms)`)),a())},n);return s.addEventListener("open",()=>{console.info(e.formatLog("open")),o.resolve(c)}),s.addEventListener("error",t=>{console.error(e.formatLog("error"),t),a()}),s.addEventListener("close",a),s.addEventListener("message",t=>{if(i)return;const n=t.data;"string"!=typeof n?console.error(e.formatLog("onMessage - expected string"),n):c.eventMessage.trigger(n)}),{socket:o.promise,done:r.promise}}static startSocket(e,t,n,o){let r=!0,s=null;const i=new y(e);return(async()=>{for(;r;){const a=b.connect(i,e,t),c=await a.socket;if(null!==c){if(s=c,o({type:"socket",socket:c}),c.eventMessage.on(e=>{o({type:"message",message:e})}),await a.done,o({type:"close"}),!r)return void console.info(i.formatLog("disconnect (1)"));await w(i.formatLog("reconnect after close"),n)}else await w(i.formatLog("reconnect after error"),n)}console.info(i.formatLog("disconnect (2)"))})().catch(e=>{console.error(e)}),{send:e=>{null===s?console.error("send fail - missing connection",e):s.send(e)},dispose:()=>{r=!1,s?.close()}}}}const k=e=>{try{return JSON.parse(e)}catch{throw console.error("Failed to parse websocket message",e),Error(e)}},C=(e,t,n)=>{e.wasmCommand({Websocket:{callback:t,message:n}})};class E{constructor(e){this.websocket_register_callback=(e,t)=>{const n=this.getWasm();let o=b.startSocket(e,5e3,3e3,e=>{if(!1!==this.controllerList.has(t)){if("socket"===e.type)return this.socket.set(t,e.socket),void C(n,t,"Connected");if("message"!==e.type)return"close"===e.type?(this.socket.delete(t),void C(n,t,"Disconnected")):(e=>{throw console.error(e),Error("unknown message")})(e);C(n,t,{Message:{message:k(e.message)}})}});this.controllerList.set(t,o)},this.websocket_unregister_callback=e=>{const t=this.controllerList.get(e);void 0!==t?(t.dispose(),this.controllerList.delete(e)):console.error("Expected controller")},this.websocket_send_message=(e,t)=>{const n=this.socket.get(e);var o;void 0===n?console.error(`Missing socket connection for callback_id=${e}`):n.send((o=t,JSON.stringify(o)))},this.getWasm=e,this.controllerList=new Map,this.socket=new Map}}const x=e=>{const t={};for(const{k:n,v:o}of e)t[n]=o;return t},T=e=>{if("None"!==e)return JSON.stringify(e.Data.data)},N=e=>0===e.length?null:JSON.parse(e),A=(e,t)=>{if((e=>"text/plain"===e?.split(";")[0]?.trim().toLowerCase())(e))return{Text:t};try{return{Json:N(t)}}catch{return{Text:t}}},_=async(e,t,n)=>{const o=e(),r=e=>{o.wasmCommand({FetchExecResponse:{response:e,callback:t}})};try{const e=await fetch(n.url,{method:n.method,headers:x(n.headers),body:T(n.body)});r(await(async e=>{const t=e.status,n=e.headers.get("Content-Type");try{return{Ok:{status:t,response:A(n,await e.text())}}}catch(e){return{Err:{message:String(e)}}}})(e))}catch(e){console.error("fetch error (1)",e);r({Err:{message:new String(e).toString()}})}};class S{constructor(e){this.timerSet=(e,t,n)=>{switch(n){case"Interval":{const n=setInterval(()=>{this.getWasm().wasmCommand({TimerCall:{callback:e}})},t);this.data.set(e,{kind:"Interval",timerId:n});break}case"Timeout":{const n=setTimeout(()=>{this.getWasm().wasmCommand({TimerCall:{callback:e}})},t);this.data.set(e,{kind:"Timeout",timerId:n});break}}},this.timerClear=e=>{const t=this.data.get(e);if(void 0===t)throw Error("panic");switch(t.kind){case"Interval":clearInterval(t.timerId);break;case"Timeout":clearTimeout(t.timerId)}},this.getWasm=e,this.data=new Map}}class L{constructor(e,t,n,o,r){this.getWasm=e,this.get=n,this.pushValue=o,this.replaceValue=r,this.callback=new Map,this.trigger=()=>{for(const e of Array.from(this.callback.values()))e()},this.add=e=>{this.callback.set(e,()=>{this.getWasm().wasmCommand({LocationCall:{callback:e,value:this.get()}})})},this.remove=e=>{this.callback.delete(e)},this.push=e=>{this.get()!==e&&this.pushValue(e,this.trigger)},this.replace=e=>{this.get()!==e&&this.replaceValue(e,this.trigger)},window.addEventListener(t,this.trigger)}}class ${constructor(e,t){this.mountPoint=t,this.callback=(e,t,n)=>{switch(t){case"Add":return void this.locations[e].add(n);case"Remove":return void this.locations[e].remove(n)}},this.set=(e,t,n)=>{switch(t){case"Push":return void this.locations[e].push(n);case"Replace":return void this.locations[e].replace(n)}},this.get=e=>this.locations[e].get(),this.locations={Hash:new L(e,"hashchange",()=>decodeURIComponent(location.hash.substr(1)),(e,t)=>{location.hash=e,t()},e=>{history.replaceState(null,"",`#${e}`)}),History:new L(e,"popstate",()=>window.location.pathname+window.location.search+window.location.hash,(e,t)=>{window.history.pushState(null,"",e),t()},(e,t)=>{window.history.replaceState(null,"",e),t()})}}}class R{constructor(){this.get=e=>{for(const t of document.cookie.split(";")){if(""===t)continue;const n=t.trim().split("=");if(2!==n.length){console.warn(`Cookies.get: Incorrect number of cookieChunk => ${n.length} in ${t}`);continue}const o=n[0],r=n[1];if(void 0!==o&&void 0!==r){if(o===e)return decodeURIComponent(r)}else console.warn(`Cookies.get: Broken cookie part => ${t}`)}return""},this.getJson=e=>{let t=this.get(e);if(0!==t.length)try{return JSON.parse(t)}catch(e){console.error("Error deserializing cookie",e)}return null},this.set=(e,t,n)=>{const o=null==t?"":encodeURIComponent(t),r=new Date;r.setTime(r.getTime()+1e3*n);let s="expires="+r.toUTCString();document.cookie=`${e}=${o};${s};path=/; samesite=Strict`},this.setJson=(e,t,n)=>{let o=JSON.stringify(t);this.set(e,o,n)}}}const M=(e,t)=>{const n=t-e+1;return e+Math.floor(Math.random()*n)},I=e=>e.arrayBuffer().then(t=>({name:e.name,data:new Uint8Array(t)}));const U=(e,t,n)=>{Promise.all(e).then(e=>{const n=[];for(const t of e)n.push([t.name,Array.from(t.data)]);t([n])}).catch(e=>{console.error(n,e)})},B=(e,t)=>{t(void 0)},O=(e,t)=>{e.preventDefault(),t(void 0)},D=(e,t)=>{t(void 0)&&e.preventDefault()},W=e=>(t,n)=>{const o=t.target;o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement||e&&o instanceof HTMLSelectElement?n(o.value):console.warn("event input ignore",o)},F=(e,t)=>{if(e instanceof KeyboardEvent){return void(!0===t([e.key,e.code,e.altKey,e.ctrlKey,e.shiftKey,e.metaKey])&&(e.preventDefault(),e.stopPropagation()))}console.warn("keydown ignore",e)},H={click:(e,t)=>{const n=t(void 0);null===n||"object"!=typeof n||Array.isArray(n)||("stop_propagation"in n&&!0===n.stop_propagation&&e.stopPropagation(),"prevent_default"in n&&!0===n.prevent_default&&e.preventDefault())},submit:O,input:W(!1),change:W(!0),blur:B,mousedown:D,mouseup:D,mouseenter:B,mouseleave:B,keydown:F,hook_keydown:F,drop:(e,t)=>{if(e.preventDefault(),e instanceof DragEvent)if(null===e.dataTransfer)console.error("dom -> drop -> dataTransfer null");else{const n=function(e){const t=[];for(let n=0;n<e.length;n++){const o=e[n];if(void 0===o)console.error("dom -> drop -> item - undefined");else{const e=o.getAsFile();null===e?console.error(`dom -> drop -> index:${n} -> It's not a file`):t.push(I(e))}}return t}(e.dataTransfer.items);n.length?U(n,t,"callback_drop -> promise.all -> "):console.error("No files to send")}else console.warn("event drop ignore",e)},load:O,change_file:(e,t)=>{const n=e.target;if(n instanceof HTMLInputElement&&null!==n.files&&n.files.length>0){const e=[];for(let t=0;t<n.files.length;t++){const o=n.files[t];void 0!==o&&e.push(I(o))}return e.length>0&&U(e,t,"changeFile ->"),void(n.value="")}console.warn("changeFile: not a file input or no files",n)}};class V{constructor(e){this.getWasm=e,this.callbacks=new Map,this.observers=new Map}add(e,t,n,o){if("intersect"===n)return this.intersectAdd(e,t,o);const r=e=>this.wasmCallback(o,e),s=e=>{const t=H[n];void 0!==t?t(e,r):console.error(`No support for the event ${n}`)};if(this.callbacks.has(o))console.error(`There was already a callback added with the callback_id=${o}`);else if(this.callbacks.set(o,s),"hook_keydown"===n)document.addEventListener("keydown",s,!1);else{const o=e.get("callback_add",t),r="change_file"===n?"change":n;o.addEventListener(r,s,!1)}}remove(e,t,n,o){if("intersect"===n)return this.intersectRemove(o);const r=this.callbacks.get(o);if(this.callbacks.delete(o),void 0!==r)if("hook_keydown"===n)document.removeEventListener("keydown",r);else{const o="change_file"===n?"change":n;e.get("callback_remove",t).removeEventListener(o,r)}else console.error(`The callback is missing with the id=${o}`)}wasmCallback(e,t){return this.getWasm().wasmCommand({CallbackCall:{callback_id:e,value:t}})}intersectAdd(e,t,n){if(this.observers.has(n))return void console.error(`There was already an intersect observer added with the callback_id=${n}`);const o=e.getNode("callback_add",t),r=new IntersectionObserver(e=>{for(const t of e)this.wasmCallback(n,[t.isIntersecting,t.intersectionRatio,t.boundingClientRect.top,t.boundingClientRect.bottom,t.boundingClientRect.height])});r.observe(o),this.observers.set(n,r)}intersectRemove(e){const t=this.observers.get(e);this.observers.delete(e),void 0!==t?t.disconnect():console.error(`The intersect observer is missing with the id=${e}`)}}function J(e,t){e.addEventListener("click",n=>{const o=e.getAttribute("href");if(null===o||o.startsWith("#"))return;if(!((r=n)instanceof MouseEvent&&0===r.button)||r.ctrlKey||r.metaKey||r.shiftKey||r.altKey||e.hasAttribute("download")||!function(e){const t=e.getAttribute("target");return null===t||""===t||"_self"===t}(e))return;var r;const s=function(e,t,n){if(e.matches('[rel~="external" i]'))return null;let o;try{o=new URL(t,document.baseURI)}catch{return null}if(o.protocol!==window.location.protocol||o.host!==window.location.host)return null;const r=n.replace(/\/+$/,"");if(""!==r&&o.pathname!==r&&!o.pathname.startsWith(`${r}/`))return null;return o.pathname+o.search+o.hash}(e,o,t.mountPoint);null!==s&&(n.preventDefault(),t.set("History","Push",s),function(e){const t=e.indexOf("#"),n=-1===t?"":e.slice(t+1),o=G(n);if(j=null,null!==o)return void o.scrollIntoView();window.scrollTo(0,0),""!==n&&"top"!==K(n).toLowerCase()&&(j={path:e,fragment:n,until:Date.now()+P,scrollY:window.scrollY})}(s))})}const P=1e4;let j=null;function G(e){return""===e?null:z(e)??z(K(e))}function z(e){return document.getElementById(e)??Array.from(document.getElementsByName(e)).find(e=>"A"===e.tagName)??null}function K(e){try{return decodeURIComponent(e)}catch{return e}}const Y=new Set(["animate","animateMotion","animateTransform","circle","clipPath","defs","desc","discard","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","foreignObject","g","hatch","hatchpath","image","line","linearGradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tspan","use","view","svg:a","svg:title","svg:desc","svg:script","svg:style"]);class q{constructor(e,t,n){this.depth=-1,this.matched=0,this.discarded=0,this.nodes=t,this.appLocation=n,this.virtualNodes=this.createVirtualNodes(e)}hydrate(){const e=this.virtualNodes.get(3),t=this.virtualNodes.get(2);e&&(this.hydrateNode(3,document.body),t&&this.hydrateNode(2,document.head));const n={rootFound:void 0!==e,matched:this.matched,...this.countHydratable(),total:this.virtualNodes.size,discarded:this.discarded};if(!e)return console.error("Hydration skipped: the first DOM batch carries no <body> (node id 3), so the server-rendered markup cannot be matched and will be replaced. The app flushed DOM changes before the root element was built - see `mount` in exports.rs.",n),this.publish(n),n;const o=0===n.hydratable?"100.00":(100*n.matched/n.hydratable).toFixed(2),r=`Hydration complete: ${n.matched}/${n.hydratable} matched (${o}%), ${n.discarded} server nodes discarded, ${n.skipped} markers skipped, ${n.total} vnodes in batch.`;return n.matched<n.hydratable||n.discarded>0?console.warn(r):console.log(r),this.publish(n),n}publish(e){try{window.__vertigo_hydration=e}catch(e){}}countHydratable(){let e=0,t=0;const n=new Set,o=(r,s)=>{if(n.has(r))return;n.add(r);const i=this.virtualNodes.get(r);if(s||(void 0===i||void 0===i.name&&!(e=>void 0!==e.value&&""!==e.value)(i)?t++:e++),i)for(const e of i.children)o(e,!1)};return o(3,!0),o(2,!0),{hydratable:e,skipped:t}}hydrateNode(e,t){const n=this.virtualNodes.get(e);if(!n)return;const o=Array.from(t.childNodes);let r=0;this.depth++;let s=!1;for(const e of n.children){const t=this.virtualNodes.get(e);if(t&&""!==t.value)if(s&&void 0!==t.value)this.matched++;else{s=!1;for(let n=r;n<o.length;n++){const i=o[n];if(!i)continue;let a=!1;if(t.name?a=this.checkElementMatch(i,t):void 0!==t.value&&(i.nodeType===Node.TEXT_NODE?(this.checkTextMatch(i,t),a=!0,s=!0):console.error(`Hydration ${this.depth}: Text node mismatch`,t,i)),a){this.removeSkippedNodes(o,r,n),this.claimNode(i,e),this.matched++,t.name&&this.hydrateNode(e,i),r=n+1;break}}}}this.removeSkippedNodes(o,r,o.length),this.depth--}checkElementMatch(e,t){let n=!1;const o=void 0===t.name?void 0:(r=t.name,Y.has(r)?r.replace("svg:",""):r.toUpperCase());var r;if(e.nodeType===Node.ELEMENT_NODE&&e.tagName===o){n=!0;const o=e,r=t.attributes;for(const e of o.getAttributeNames())r&&r.has(e)||o.removeAttribute(e);if(r)for(const[e,t]of r)o.getAttribute(e)!==t&&o.setAttribute(e,t)}return n}checkTextMatch(e,t){e.textContent?.replace("\n"," ").trim()!==t.value?.replace("\n"," ").trim()&&(e.textContent=t.value||"")}claimNode(e,t){var n,o;(e instanceof Element||e instanceof Comment||e instanceof Text)&&(this.nodes.claimNode(t,e),e instanceof Element&&(n=e,o=this.appLocation,"a"===n.tagName.toLowerCase()&&J(n,o)))}place(){for(const e of[...this.virtualNodes.values()].reverse()){const t=this.nodes.getAnyOption(e.id);if(1===e.id||!t)continue;let n=t.firstChild;for(const o of e.children){const e=this.nodes.getAnyOption(o);e===n?n=e.nextSibling:e&&t.insertBefore(e,n)}}}removeSkippedNodes(e,t,n){for(let o=t;o<n;o++){const t=e[o];t&&(0!==this.depth&&t.nodeType!==Node.TEXT_NODE&&(console.warn(`Hydration ${this.depth}: Removing node`,t),this.discarded++),t.remove())}}createVirtualNodes(e){const t=new Map,n=e=>{let n=t.get(e);return n||(n={id:e,children:[]},t.set(e,n)),n},o=new Map,r=e=>{const t=o.get(e);t&&(t.children.splice(t.children.indexOf(e),1),o.delete(e))},s=e=>{r(e),t.delete(e)};for(const i of e)if("CreateNode"in i){n(i.CreateNode.id).name=i.CreateNode.name}else if("CreateText"in i){n(i.CreateText.id).value=i.CreateText.value}else if("UpdateText"in i){n(i.UpdateText.id).value=i.UpdateText.value}else if("InsertBefore"in i){const e=n(i.InsertBefore.parent),t=e.children,s=i.InsertBefore.child,a=i.InsertBefore.ref_id;if(r(s),o.set(s,e),null==a)t.push(s);else{const e=t.length-1,n=t[e]===a?e:t.indexOf(a);-1!==n?t.splice(n,0,s):(console.warn(`Hydration: ref_id ${a} not found in parent ${i.InsertBefore.parent}`),t.push(s))}}else if("SetAttr"in i){const e=n(i.SetAttr.id);e.attributes||(e.attributes=new Map),e.attributes.set(i.SetAttr.name,i.SetAttr.value)}else"RemoveAttr"in i?t.get(i.RemoveAttr.id)?.attributes?.delete(i.RemoveAttr.name):"RemoveNode"in i?s(i.RemoveNode.id):"RemoveText"in i?s(i.RemoveText.id):"RemoveComment"in i&&s(i.RemoveComment.id);return t}}const X=1,Q=2,Z=3,ee=4,te=5,ne=6,oe=7,re=8,se=9,ie=10,ae=11,ce=12,le=13;class de{constructor(e){this.bytes=e,this.at=0}isEmpty(){return this.at>=this.bytes.length}where(){return`offset ${this.at} of ${this.bytes.length}`}byte(){const e=this.bytes[this.at];if(void 0===e)throw new Error("dom command: buffer ended early");return this.at+=1,e}varint(){let e=0,t=1;for(;;){const n=this.byte();if(e+=(127&n)*t,!(128&n))return e;t*=128}}string(){const t=this.varint(),n=this.at+t;if(n>this.bytes.length)throw new Error("dom command: string runs past the end of the buffer");const o=e.decode(this.bytes.subarray(this.at,n));return this.at=n,o}name(e){const t=this.varint(),n=e[t];if(void 0===n)throw new Error(`dom command: name index ${t} is not in the dictionary`);return n}optionalId(){const e=this.varint();return 0===e?null:e}}const he=e=>{const t=e.varint(),n=[];for(let o=0;o<t;o++)n.push(e.string());return n},ue=e=>e.varint(),me=e=>e.string(),fe=(e,t)=>e.name(t),ge={[X]:["CreateNode",[["id",ue],["name",fe]]],[Q]:["CreateText",[["id",ue],["value",me]]],[Z]:["UpdateText",[["id",ue],["value",me]]],[ee]:["SetAttr",[["id",ue],["name",fe],["value",me]]],[te]:["RemoveAttr",[["id",ue],["name",fe]]],[ne]:["RemoveNode",[["id",ue]]],[oe]:["RemoveText",[["id",ue]]],[re]:["InsertBefore",[["parent",ue],["child",ue],["ref_id",e=>e.optionalId()]]],[se]:["InsertCss",[["selector",e=>0===e.byte()?null:e.string()],["value",me]]],[ie]:["CreateComment",[["id",ue],["value",me]]],[ae]:["RemoveComment",[["id",ue]]],[ce]:["CallbackAdd",[["id",ue],["event_name",me],["callback_id",ue]]],[le]:["CallbackRemove",[["id",ue],["event_name",me],["callback_id",ue]]]};class pe{constructor(){this.data=new Map,this.initNodes=[...this.getRootHead().childNodes,...this.getRootBody().childNodes],this.style=document.createElement("style")}getRootHtml(){return document.documentElement}getRootHead(){return document.head}getRootBody(){return document.body}set(e,t){1===e||2===e||3===e||this.data.set(e,t)}getAnyOption(e){return 1===e?this.getRootHtml():2===e?this.getRootHead():3===e?this.getRootBody():this.data.get(e)}getAny(e,t){const n=this.getAnyOption(t);if(void 0===n)throw Error(`${e} -> item not found=${t}`);return n}get(e,t){const n=this.getAnyOption(t);if(void 0===n)throw new Error(`${e}->get: Item id not found = ${t}`);return n}expect(e,t,n,o){const r=this.get(e,t);if(r instanceof n)return r;throw Error(`Expected id=${t} as ${o}`)}getNode(e,t){return this.expect(e,t,Element,"Element")}getText(e,t){return this.expect(e,t,Text,"Text")}delete(e,t){const n=this.getAnyOption(t);if(this.data.delete(t),void 0===n)throw new Error(`${e}->delete: Item id not found = ${t}`);return n}insertCss(e,t){if(null!==e){const n=document.createTextNode(`\n${e} { ${t} }`);this.style.appendChild(n)}else{const e=document.createTextNode(`\n${t}`);this.style.appendChild(e)}}removeInitNodes(){const e=this.initNodes;if(this.initNodes=null,null!==e)for(const t of e)t.remove()}insertBefore(e,t,n){const o=this.get("insert_before",e),r=this.getAny("insert_before child",t);if(null==n)o.insertBefore(r,null);else{const e=this.getAny("insert_before ref",n);o.insertBefore(r,e)}}addStyles(){this.getRootHead().appendChild(this.style)}hasInitNodes(){return null!==this.initNodes}claimNode(e,t){if(this.data.set(e,t),this.initNodes){const e=this.initNodes.indexOf(t);e>-1&&this.initNodes.splice(e,1)}}has(e){return 1===e||2===e||3===e||this.data.has(e)}}const ve=(e,t)=>{console.error("bulk_update - item",t,e)},we=(e,t)=>e.findIndex(e=>e.toLowerCase()===t);class ye{constructor(e,t,n){this.metadata=e,this.update=e=>{const t=this.nodes.hasInitNodes()&&this.metadata.getEnabledHydration()?((e,t,n)=>{const o=new q(e,t,n);return{report:o.hydrate(),place:()=>o.place()}})((e=>{const t=new de(e),n=he(t),o=[];for(;!t.isEmpty();){const e=t.byte(),r=ge[e];if(void 0===r)throw new Error(`dom command: unknown tag ${e}`);const[s,i]=r,a={};for(const[e,o]of i)a[e]=o(t,n);o.push({[s]:a})}return o})(e),this.nodes,this.appLocation):null,n=t?.report.rootFound?t:null,o=new de(e),r=he(o),s=we(r,"autofocus"),i=we(r,"a"),a=new Set;try{for(;!o.isEmpty();){const e=o.byte();switch(e){case X:{const e=o.varint(),t=o.varint();try{this.createNode(e,r[t]??"",t===i)}catch(e){ve(e,"CreateNode")}break}case Q:{const e=o.varint(),t=o.string();try{this.createText(e,t)}catch(e){ve(e,"CreateText")}break}case Z:{const e=o.varint(),t=o.string();try{this.updateText(e,t)}catch(e){ve(e,"UpdateText")}break}case ee:{const e=o.varint(),t=o.varint(),n=o.string();t===s&&a.add(e);try{this.writeAttr("set_attribute",e,r[t]??"",n)}catch(e){ve(e,"SetAttr")}break}case te:{const e=o.varint(),t=o.varint();try{this.writeAttr("remove_attribute",e,r[t]??"",null)}catch(e){ve(e,"RemoveAttr")}break}case ne:{const e=o.varint();try{this.removeNode(e)}catch(e){ve(e,"RemoveNode")}break}case oe:{const e=o.varint();try{this.removeText(e)}catch(e){ve(e,"RemoveText")}break}case re:{const e=o.varint(),t=o.varint(),r=o.optionalId();if(null===n)try{this.nodes.insertBefore(e,t,r)}catch(e){ve(e,"InsertBefore")}break}case se:{const e=0===o.byte()?null:o.string(),t=o.string();try{this.nodes.insertCss(e,t)}catch(e){ve(e,"InsertCss")}break}case ie:{const e=o.varint(),t=o.string();try{this.nodes.set(e,document.createComment(t))}catch(e){ve(e,"CreateComment")}break}case ae:{const e=o.varint();try{this.nodes.delete("remove_comment",e).remove()}catch(e){ve(e,"RemoveComment")}break}case ce:{const e=o.varint(),t=o.string(),n=o.varint();try{this.callbacks.add(this.nodes,e,t,n)}catch(e){ve(e,"CallbackAdd")}break}case le:{const e=o.varint(),t=o.string(),n=o.varint();try{this.callbacks.remove(this.nodes,e,t,n)}catch(e){ve(e,"CallbackRemove")}break}default:throw new Error(`bulk_update: unknown command tag ${e}`)}}}catch(e){console.error(`bulk_update - stream is unreadable at ${o.where()}, dropping the rest of the batch`,e)}n?.place(),a.size>0&&setTimeout(()=>{for(const e of a){const t=this.nodes.getAnyOption(e);t instanceof HTMLElement&&t.focus()}},0),this.nodes.removeInitNodes(),this.nodes.addStyles(),function(){if(null===j)return;if(window.location.pathname+window.location.search+window.location.hash!==j.path||window.scrollY>j.scrollY||Date.now()>j.until)return void(j=null);j.scrollY=window.scrollY;const e=G(j.fragment);null!==e&&(j=null,e.scrollIntoView())}()},this.appLocation=t,this.nodes=new pe,this.callbacks=new V(n),document.addEventListener("dragover",e=>{e.preventDefault()})}createNode(e,t,n){if(1===e||2===e||3===e)return;if(this.nodes.has(e))return;const o=(e=>Y.has(e)?document.createElementNS("http://www.w3.org/2000/svg",e.replace("svg:","")):document.createElement(e))(t);this.nodes.set(e,o),n&&J(o,this.appLocation)}writeAttr(e,t,n,o){const r=this.nodes.getNode(e,t);if(null===o?r.removeAttribute(n):r.getAttribute(n)!==o&&r.setAttribute(n,o),"value"==n){const e=o??"";if(r instanceof HTMLInputElement)return void(r.value=e);if(r instanceof HTMLTextAreaElement)return r.value=e,void(r.defaultValue=e)}}removeNode(e){if(1===e||2===e||3===e)return;this.nodes.delete("remove_node",e).remove()}createText(e,t){if(this.nodes.has(e))return;const n=document.createTextNode(t);this.nodes.set(e,n)}removeText(e){this.nodes.delete("remove_node",e).remove()}updateText(e,t){this.nodes.getText("set_attribute",e).textContent=t}}const be={Debug:"debug",Info:"info",Log:"log",Warn:"warn",Error:"error"};class ke{constructor(e,t){this.metadata=e,this.getWasm=t;const n=new $(t,e.getEnv("vertigo-mount-point")??"/");this.dom=new ye(e,n,t),this.websocket=new E(t),this.interval=new S(t),this.location=n,this.cookie=new R}exec(e){const t=e;if("FetchCacheGet"===t)return{data:this.metadata.getFetchCache()};if("IsBrowser"===t)return{value:!0};if("GetDateNow"===t)return{value:Date.now()};if("TimezoneOffset"===t)return{value:(new Date).getTimezoneOffset()};if("HistoryBack"===t)return window.history.back(),null;const n=t,[o,r]=Object.entries(n)[0]??[];switch(o){case"FetchExec":return _(this.getWasm,r.callback,r.request),null;case"WebsocketRegister":return this.websocket.websocket_register_callback(r.host,r.callback),null;case"WebsocketSendMessage":return this.websocket.websocket_send_message(r.callback,r.message),null;case"WebsocketUnregister":return this.websocket.websocket_unregister_callback(r.callback),null;case"TimerSet":return this.interval.timerSet(r.callback,r.duration,r.kind),null;case"TimerClear":return this.interval.timerClear(r.callback),null;case"LocationGet":return{value:this.location.get(r.target)};case"LocationCallback":return this.location.callback(r.target,r.mode,r.callback),null;case"LocationSet":return this.location.set(r.target,r.mode,r.value),null;case"CookieGet":return{value:this.cookie.get(r.name)};case"CookieSet":return this.cookie.set(r.name,r.value,r.expires_in),null;case"CookieJsonGet":return{value:this.cookie.getJson(r.name)};case"CookieJsonSet":return this.cookie.setJson(r.name,r.value,r.expires_in),null;case"GetEnv":return{value:this.metadata.getEnv(r.name)};case"Log":return console[be[r.kind]](r.message,r.arg2,r.arg3,r.arg4),null;case"GetRandom":return{value:M(r.min,r.max)};case"JsApiCall":return this.executeJsApiCall(r.commands);case"DomBulkUpdate":return this.dom.update(r.commands),null;default:return console.info("exec_command: Arg",t),(()=>{throw Error("assert never")})()}}executeJsApiCall(e){let t=null;for(const n of e)if("Root"in n)if("window"===n.Root.name)t=window;else{if("document"!==n.Root.name)return console.error(`Unknown root: ${n.Root.name}`),null;t=document}else if("RootElement"in n){const e=n.RootElement.dom_id,o=this.dom.nodes.getAnyOption(e);if(void 0===o)return console.error(`Element not found: ${e}`),null;t=o}else if("Get"in n){if(null===t)return console.error("Get called on null"),null;t=t[n.Get.property]}else if("Set"in n){if(null===t)return console.error("Set called on null"),null;t[n.Set.property]=n.Set.value,t=void 0}else if("Call"in n){if(null===t)return console.error("Call called on null"),null;t=t[n.Call.method](...n.Call.args)}const n=e=>{if(null==e)return null;if("boolean"==typeof e)return e;if("string"==typeof e)return e;if("number"==typeof e)return e;if(e instanceof Uint8Array)return e;if(Array.isArray(e))return e.map(e=>n(e));if((e=>{if(null===e)return!1;if("object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t})(e)){const t={};for(const o of Object.keys(e))t[o]=n(e[o]);return t}return null};return n(t)}}class Ce{constructor(){this.get=e=>this.metadata.getAttribute(e),this.getEnabledHydration=()=>"true"!==this.get("data-env-disable-hydration");const e=document.getElementById("v-metadata");if(null===e)throw Error("Expected v-metadata");this.metadata=e,e.remove()}getEnv(e){return this.get(`data-env-${e}`)}getFetchCache(){return this.get("data-fetch-cache")}}class Ee{constructor(e){this.wasm=e}vertigoEntryFunction(e,t){this.wasm.exports.vertigo_entry_function(e,t)}static async create(t){let o=null;const r=()=>{if(null===o)throw Error("Wasm is no initialized");return o},s=new Ce,i=new ke(s,r);return window.$vertigoApi=i,o=await g(t,{mod:{panic_message:t=>{const n=Number(t%2n**32n),o=Number(t>>32n),s=r().getUint8Memory().subarray(o,o+n),i=e.decode(s);console.error("PANIC",i)},dom_access:e=>{if(0n===e)return console.error("dom_access - null pointer"),0n;const t=new n(()=>r().getUint8Memory(),e),o=m(t);r().exports.vertigo_export_free_block(e);const s=i.exec(o),a=u(s),c=r().exports.vertigo_export_alloc_block(a),l=new n(()=>r().getUint8Memory(),c);return f(s,l),c}}}),new Ee(o)}}const xe=new Set,Te=async()=>{document.querySelectorAll("*[data-vertigo-run-wasm]").forEach(e=>{const t=e.getAttribute("data-vertigo-run-wasm");"string"==typeof t?(async e=>{if(xe.has(e))return;if(xe.size>0)return void console.error("Only one wasm module can be run",{moduleRun:xe,wasm:e});xe.add(e),console.info(`Wasm module: "${e}" -> start`);const t=await Ee.create(e);console.info(`Wasm module: "${e}" -> initialized`),t.vertigoEntryFunction(0,13),console.info(`Wasm module: "${e}" -> launched vertigoEntryFunction with version 0.13`)})(t):console.error("Run error",e)})};window.addEventListener("load",Te),setTimeout(Te,3e3);
//# sourceMappingURL=wasm_run.js.map