vertigo 0.11.4

Reactive Real-DOM library with SSR for Rust
Documentation
1
2
"use strict";const e=new TextDecoder("utf-8"),t=new TextEncoder;class o{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}getI32(){const e=this.dataView.getInt32(this.pointer);return this.pointer+=4,e}setI32(e){this.dataView.setInt32(this.pointer,e),this.pointer+=4}getU64(){const e=this.dataView.getBigUint64(this.pointer);return this.pointer+=8,e}setU64(e){this.dataView.setBigUint64(this.pointer,e),this.pointer+=8}getI64(){const e=this.dataView.getBigInt64(this.pointer);return this.pointer+=8,e}setI64(e){this.dataView.setBigInt64(this.pointer,e),this.pointer+=8}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 o=t.encode(e);this.setBuffer(o)}getSavedSize(){return this.pointer}}const n=1,s=2,r=3,i=4,a=5,l=6,c=7,d=8,h=9,u=e=>{if(!0===e||!1===e||null==e)return 1;if("string"==typeof e)return 5+(new TextEncoder).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 o of e)t+=u(o);return t}if("object"==typeof e&&null!==e){let t=3;for(const[o,n]of Object.entries(e))t+=4+(new TextEncoder).encode(o).length,t+=u(n);return t}throw new Error("jsJsonGetSize: Unknown type "+typeof e)},m=e=>{const t=e.getByte();if(t===n)return!0;if(t===s)return!1;if(t===r)return null;if(t!==i){if(t===a)return e.getString();if(t===l)return e.getF64();if(t===c){const t=e.getU32(),o=[];for(let n=0;n<t;n++)o.push(m(e));return o}if(t===d){const t=e.getU16(),o={};for(let n=0;n<t;n++){const t=e.getString(),n=m(e);o[t]=n}return o}if(t===h)return e.getBuffer();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(l),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 o=Object.entries(e);t.setByte(d),t.setU16(o.length);for(const[e,n]of o)t.setString(e),f(n,t);return}throw new Error("saveJsJsonToBufferItem: Unknown type "+typeof e)}t.setByte(c),t.setU32(e.length);for(const o of e)f(o,t)}else t.setByte(i);else t.setByte(r);else t.setByte(s);else t.setByte(n)},g=async(e,t)=>{const n=await(async(e,t)=>{if("function"==typeof WebAssembly.instantiateStreaming){const o=fetch(e);try{return await WebAssembly.instantiateStreaming(o,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 o=await fetch(e),n=await o.arrayBuffer();return await WebAssembly.instantiate(n,t)})(e,t);let s=new Uint8Array(1);const r=()=>{if(n.instance.exports.memory instanceof WebAssembly.Memory)return s.buffer!==n.instance.exports.memory.buffer&&(s=new Uint8Array(n.instance.exports.memory.buffer)),s;throw Error("Missing memory")},i=n.instance.exports;return{exports:i,getUint8Memory:r,wasmCommand:e=>{const t=u(e),n=i.vertigo_export_alloc_block(t),s=new o(r,n);f(e,s);let a=i.vertigo_export_wasm_command(n);if(0n===a)return null;const l=new o(r,a),c=m(l);return i.vertigo_export_free_block(a),c}}};class p{constructor(){this.events=new Set}on(e){let t=!0;const o=o=>{t&&e(o)};return this.events.add(o),()=>{t=!1,this.events.delete(o)}}trigger(e){const t=Array.from(this.events.values());for(const o of t)try{o(e)}catch(e){console.error(e)}}get size(){return this.events.size}}class w{constructor(){this.inner=null,this.resolve=e=>{const t=this.inner;this.inner=null,null!==t&&t.resolve(e)},this.reject=e=>{const t=this.inner;this.inner=null,null!==t&&t.reject(e)},this.isFulfilled=()=>null===this.inner;const[e,t]=(()=>{let e=null,t=null;const o=new Promise((o,n)=>{e=o,t=n});if(null===e)throw Error("createPromiseValue - resolve is null");if(null===t)throw Error("createPromiseValue - reject is null");return[{resolve:e,reject:t},o]})();this.inner=e,this.promise=t}}const v=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 k{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,o){const n=new w,s=new w,r=new WebSocket(t);let i=!1;console.info(e.formatLog("starting ..."));const a=()=>{i||(console.info(e.formatLog("close")),i=!0,n.resolve(null),s.resolve(),r.close())},l=new b(a,e=>{i||r.send(e)});setTimeout(()=>{!1===n.isFulfilled()&&(console.error(e.formatLog(`timeout (${o}ms)`)),a())},o);return r.addEventListener("open",()=>{console.info(e.formatLog("open")),n.resolve(l)}),r.addEventListener("error",t=>{console.error(e.formatLog("error"),t),a()}),r.addEventListener("close",a),r.addEventListener("message",t=>{if(i)return;const o=t.data;"string"!=typeof o?console.error(e.formatLog("onMessage - expected string"),o):l.eventMessage.trigger(o)}),{socket:n.promise,done:s.promise}}static startSocket(e,t,o,n){let s=!0,r=null;const i=new k(e);return(async()=>{for(;s;){const a=b.connect(i,e,t),l=await a.socket;if(null!==l){if(r=l,n({type:"socket",socket:l}),l.eventMessage.on(e=>{n({type:"message",message:e})}),await a.done,n({type:"close"}),!s)return void console.info(i.formatLog("disconnect (1)"));await v(i.formatLog("reconnect after close"),o)}else await v(i.formatLog("reconnect after error"),o)}console.info(i.formatLog("disconnect (2)"))})().catch(e=>{console.error(e)}),{send:e=>{null===r?console.error("send fail - missing connection",e):r.send(e)},dispose:()=>{s=!1,r?.close()}}}}const y=e=>{try{return JSON.parse(e)}catch{throw console.error("Failed to parse websocket message",e),Error(e)}},C=(e,t,o)=>{e.wasmCommand({Websocket:{callback:t,message:o}})};class E{constructor(e){this.websocket_register_callback=(e,t)=>{const o=this.getWasm();let n=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(o,t,"Connected");if("message"!==e.type)return"close"===e.type?(this.socket.delete(t),void C(o,t,"Disconnected")):(e=>{throw console.error(e),Error("unknown message")})(e);C(o,t,{Message:{message:y(e.message)}})}});this.controllerList.set(t,n)},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 o=this.socket.get(e);var n;void 0===o?console.error(`Missing socket connection for callback_id=${e}`):o.send((n=t,JSON.stringify(n)))},this.getWasm=e,this.controllerList=new Map,this.socket=new Map}}const T=e=>{const t={};for(const{k:o,v:n}of e)t[o]=n;return t},L=e=>{if("None"!==e)return JSON.stringify(e.Data.data)},x=async(e,t,o)=>{const n=e();try{const e=await fetch(o.url,{method:o.method,headers:T(o.headers),body:L(o.body)}),s=await(async e=>{const t=e.status,o=e.headers.get("Content-Type");try{return o?.startsWith("text/plain;")?{Ok:{status:t,response:{Text:await e.text()}}}:{Ok:{status:t,response:{Json:await e.json()}}}}catch(e){return{Err:{message:String(e)}}}})(e);n.wasmCommand({FetchExecResponse:{response:s,callback:t}})}catch(e){console.error("fetch error (1)",e);const o={Err:{message:new String(e).toString()}};n.wasmCommand({FetchExecResponse:{response:o,callback:t}})}};class A{constructor(e){this.timerSet=(e,t,o)=>{switch(o){case"Interval":{const o=setInterval(()=>{this.getWasm().wasmCommand({TimerCall:{callback:e}})},t);this.data.set(e,{kind:"Interval",timerId:o});break}case"Timeout":{const o=setTimeout(()=>{this.getWasm().wasmCommand({TimerCall:{callback:e}})},t);this.data.set(e,{kind:"Timeout",timerId:o});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 N{constructor(e){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&&(location.hash=e,this.trigger())},this.replace=e=>{this.get()!==e&&history.replaceState(null,"",`#${e}`)},this.getWasm=e,this.callback=new Map,window.addEventListener("hashchange",this.trigger)}get(){return decodeURIComponent(location.hash.substr(1))}}class S{constructor(e){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&&(window.history.pushState(null,"",e),this.trigger())},this.replace=e=>{this.get()!==e&&(window.history.replaceState(null,"",e),this.trigger())},this.getWasm=e,this.callback=new Map,window.addEventListener("popstate",this.trigger)}get(){return window.location.pathname+window.location.search+window.location.hash}}class _{constructor(e){this.callback=(e,t,o)=>{switch(t){case"Add":return void this.locations[e].add(o);case"Remove":return void this.locations[e].remove(o)}},this.set=(e,t,o)=>{switch(t){case"Push":return void this.locations[e].push(o);case"Replace":return void this.locations[e].replace(o)}},this.get=e=>this.locations[e].get(),this.locations={Hash:new N(e),History:new S(e)}}}class I{constructor(){this.get=e=>{for(const t of document.cookie.split(";")){if(""===t)continue;const o=t.trim().split("=");if(2!==o.length){console.warn(`Cookies.get: Incorrect number of cookieChunk => ${o.length} in ${t}`);continue}const n=o[0],s=o[1];if(void 0!==n&&void 0!==s){if(n===e)return decodeURIComponent(s)}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,o)=>{const n=null==t?"":encodeURIComponent(t),s=new Date;s.setTime(s.getTime()+1e3*o);let r="expires="+s.toUTCString();document.cookie=`${e}=${n};${r};path=/; samesite=Strict`},this.setJson=(e,t,o)=>{let n=JSON.stringify(t);this.set(e,n,o)}}}const U=(e,t)=>{const o=t-e+1;return e+Math.floor(Math.random()*o)};class M{constructor(e){this.getWasm=e,this.callbacks=new Map}add(e,t,o,n){const s=e=>"click"===o?this.click(e,n):"submit"===o?this.submit(e,n):"input"===o?this.input(e,n):"change"===o?this.change(e,n):"blur"===o?this.blur(e,n):"mousedown"===o?this.mousedown(e,n):"mouseup"===o?this.mouseup(e,n):"mouseenter"===o?this.mouseenter(e,n):"mouseleave"===o?this.mouseleave(e,n):"keydown"===o||"hook_keydown"===o?this.keydown(e,n):"drop"===o?this.drop(e,n):"load"===o?this.load(e,n):void console.error(`No support for the event ${o}`);if(this.callbacks.has(n))console.error(`There was already a callback added with the callback_id=${n}`);else if(this.callbacks.set(n,s),"hook_keydown"===o)document.addEventListener("keydown",s,!1);else{e.get("callback_add",t).addEventListener(o,s,!1)}}remove(e,t,o,n){const s=this.callbacks.get(n);if(this.callbacks.delete(n),void 0!==s)if("hook_keydown"===o)document.removeEventListener("keydown",s);else{e.get("callback_remove",t).removeEventListener(o,s)}else console.error(`The callback is missing with the id=${n}`)}wasmCallback(e,t){return this.getWasm().wasmCommand({CallbackCall:{callback_id:e,value:t}})}click(e,t){e.preventDefault();let o=this.wasmCallback(t,void 0);null===o||"object"!=typeof o||Array.isArray(o)||("stop_propagation"in o&&!0===o.stop_propagation&&e.stopPropagation(),"prevent_default"in o&&!0===o.prevent_default&&e.preventDefault())}submit(e,t){e.preventDefault(),this.wasmCallback(t,void 0)}input(e,t){const o=e.target;o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement?this.wasmCallback(t,o.value):console.warn("event input ignore",o)}change(e,t){const o=e.target;o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement?this.wasmCallback(t,o.value):console.warn("event input ignore",o)}blur(e,t){this.wasmCallback(t,void 0)}mousedown(e,t){this.wasmCallback(t,void 0)&&e.preventDefault()}mouseup(e,t){this.wasmCallback(t,void 0)&&e.preventDefault()}mouseenter(e,t){this.wasmCallback(t,void 0)}mouseleave(e,t){this.wasmCallback(t,void 0)}drop(e,t){if(e.preventDefault(),e instanceof DragEvent)if(null===e.dataTransfer)console.error("dom -> drop -> dataTransfer null");else{const o=function(e){const t=[];for(let o=0;o<e.length;o++){const n=e[o];if(void 0===n)console.error("dom -> drop -> item - undefined");else{const e=n.getAsFile();null===e?console.error(`dom -> drop -> index:${o} -> It's not a file`):t.push(e.arrayBuffer().then(t=>({name:e.name,data:new Uint8Array(t)})))}}return t}(e.dataTransfer.items);o.length?Promise.all(o).then(e=>{const o=[];for(const t of e){const e=Array.from(t.data);o.push([t.name,e])}this.wasmCallback(t,[o])}).catch(e=>{console.error("callback_drop -> promise.all -> ",e)}):console.error("No files to send")}else console.warn("event drop ignore",e)}keydown(e,t){if(e instanceof KeyboardEvent){return void(!0===this.wasmCallback(t,[e.key,e.code,e.altKey,e.ctrlKey,e.shiftKey,e.metaKey])&&(e.preventDefault(),e.stopPropagation()))}console.warn("keydown ignore",e)}load(e,t){e.preventDefault(),this.wasmCallback(t,void 0)}}function B(e,t){"a"===e.tagName.toLocaleLowerCase()&&function(e,t){e.addEventListener("click",o=>{let n=e.getAttribute("href");null!==n&&(n.startsWith("#")||n.startsWith("http://")||n.startsWith("https://")||n.startsWith("//")||(o.preventDefault(),t.set("History","Push",n),window.scrollTo(0,0)))})}(e,t)}class R{constructor(e,t,o){this.depth=-1,this.matched=0,this.nodes=t,this.appLocation=o,this.virtualNodes=this.createVirtualNodes(e)}hydrate(){this.virtualNodes.get(3)&&this.hydrateNode(3,document.body);this.virtualNodes.get(2)&&this.hydrateNode(2,document.head),console.log("Hydration complete,",(100*this.matched/this.virtualNodes.size).toFixed(2)," % vnodes matched.")}hydrateNode(e,t){const o=this.virtualNodes.get(e);if(!o)return;const n=Array.from(t.childNodes);let s=0;this.depth++;let r=!1;for(const e of o.children){const t=this.virtualNodes.get(e);if(t)if(r&&void 0!==t.value)this.matched++;else{r=!1;for(let o=s;o<n.length;o++){const i=n[o];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,r=!0):console.error(`Hydration ${this.depth}: Text node mismatch`,t,i)),a){this.removeSkippedNodes(n,s,o),this.claimNode(i,e),this.matched++,t.name&&this.hydrateNode(e,i),s=o+1;break}}}}this.removeSkippedNodes(n,s,n.length),this.depth--}checkElementMatch(e,t){let o=!1;if(e.nodeType===Node.ELEMENT_NODE&&e.tagName===t.name&&(o=!0,t.attributes)){const o=e;for(const[e,n]of t.attributes)o.getAttribute(e)!==n&&o.setAttribute(e,n)}return o}checkTextMatch(e,t){e.textContent?.replace("\n"," ").trim()!==t.value?.replace("\n"," ").trim()&&(e.textContent=t.value||"")}claimNode(e,t){(e instanceof Element||e instanceof Comment||e instanceof Text)&&(this.nodes.claimNode(t,e),e instanceof Element&&B(e,this.appLocation))}removeSkippedNodes(e,t,o){for(let n=t;n<o;n++){const t=e[n];t&&(0!==this.depth&&t.nodeType!==Node.TEXT_NODE&&console.warn(`Hydration ${this.depth}: Removing node`,t),t.remove())}}createVirtualNodes(e){const t=new Map,o=e=>{let o=t.get(e);return o||(o={id:e,children:[]},t.set(e,o)),o};for(const t of e)if("CreateNode"in t){o(t.CreateNode.id).name=t.CreateNode.name.toUpperCase()}else if("CreateText"in t){o(t.CreateText.id).value=t.CreateText.value}else if("InsertBefore"in t){const e=o(t.InsertBefore.parent),n=t.InsertBefore.child,s=t.InsertBefore.ref_id;if(null==s)e.children.push(n);else{const o=e.children.indexOf(s);-1!==o?e.children.splice(o,0,n):(console.warn(`Hydration: ref_id ${s} not found in parent ${t.InsertBefore.parent}`),e.children.push(n))}}else if("SetAttr"in t){const e=o(t.SetAttr.id);e.attributes||(e.attributes=new Map),e.attributes.set(t.SetAttr.name,t.SetAttr.value)}return t}}class ${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 o=this.getAnyOption(t);if(void 0===o)throw Error(`${e} -> item not found=${t}`);return o}get(e,t){const o=this.getAnyOption(t);if(void 0===o)throw new Error(`${e}->get: Item id not found = ${t}`);return o}getNodeElement(e,t){const o=this.get(e,t);if(o instanceof HTMLElement)return o;throw Error(`Expected id=${t} as HTMLElement`)}getNode(e,t){const o=this.get(e,t);if(o instanceof Element)return o;throw Error(`Expected id=${t} as Element`)}getText(e,t){const o=this.get(e,t);if(o instanceof Text)return o;throw Error(`Expected id=${t} as Text`)}getComment(e,t){const o=this.get(e,t);if(o instanceof Comment)return o;throw Error(`Expected id=${t} as Comment`)}delete(e,t){const o=this.getAnyOption(t);if(this.data.delete(t),void 0===o)throw new Error(`${e}->delete: Item id not found = ${t}`);return o}insertCss(e,t){if(null!==e){const o=document.createTextNode(`\n${e} { ${t} }`);this.style.appendChild(o)}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,o){const n=this.get("insert_before",e),s=this.getAny("insert_before child",t);if(null==o)n.insertBefore(s,null);else{const e=this.getAny("insert_before ref",o);n.insertBefore(s,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)}}class W{constructor(e,t,o){this.metadata=e,this.update=e=>{this.nodes.hasInitNodes()&&this.metadata.getEnabledHydration()&&((e,t,o)=>{new R(e,t,o).hydrate()})(e,this.nodes,this.appLocation);const t=new Set;for(const o of e){try{this.runCommand(o)}catch(e){console.error("bulk_update - item",e,o)}"SetAttr"in o&&"autofocus"===o.SetAttr.name.toLocaleLowerCase()&&t.add(o.SetAttr.id)}t.size>0&&setTimeout(()=>{for(const e of t){this.nodes.getNodeElement(`set focus ${e}`,e).focus()}},0),this.nodes.removeInitNodes(),this.nodes.addStyles()},this.appLocation=t,this.nodes=new $,this.callbacks=new M(o),document.addEventListener("dragover",e=>{e.preventDefault()})}createNode(e,t){if(1===e||2===e||3===e)return;if(this.nodes.has(e))return;const o=(e=>"path"==e||"svg"==e?document.createElementNS("http://www.w3.org/2000/svg",e):document.createElement(e))(t);this.nodes.set(e,o),B(o,this.appLocation)}setAttr(e,t,o){const n=this.nodes.getNode("set_attribute",e);if(n.setAttribute(t,o),"value"==t){if(n instanceof HTMLInputElement)return void(n.value=o);if(n instanceof HTMLTextAreaElement)return n.value=o,void(n.defaultValue=o)}}removeAttr(e,t){const o=this.nodes.getNode("remove_attribute",e);if(o.removeAttribute(t),"value"==t){if(o instanceof HTMLInputElement)return void(o.value="");if(o instanceof HTMLTextAreaElement)return o.value="",void(o.defaultValue="")}}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 o=document.createTextNode(t);this.nodes.set(e,o)}removeText(e){this.nodes.delete("remove_node",e).remove()}updateText(e,t){this.nodes.getText("set_attribute",e).textContent=t}runCommand(e){if("RemoveNode"in e)this.removeNode(e.RemoveNode.id);else if("InsertBefore"in e)this.nodes.insertBefore(e.InsertBefore.parent,e.InsertBefore.child,null===e.InsertBefore.ref_id?null:e.InsertBefore.ref_id);else if("CreateNode"in e)this.createNode(e.CreateNode.id,e.CreateNode.name);else if("CreateText"in e)this.createText(e.CreateText.id,e.CreateText.value);else if("UpdateText"in e)this.updateText(e.UpdateText.id,e.UpdateText.value);else if("SetAttr"in e)this.setAttr(e.SetAttr.id,e.SetAttr.name,e.SetAttr.value);else if("RemoveAttr"in e)this.removeAttr(e.RemoveAttr.id,e.RemoveAttr.name);else if("RemoveText"in e)this.removeText(e.RemoveText.id);else if("InsertCss"in e)this.nodes.insertCss(e.InsertCss.selector,e.InsertCss.value);else{if("CreateComment"in e){const t=document.createComment(e.CreateComment.value);return void this.nodes.set(e.CreateComment.id,t)}if("RemoveComment"in e){return void this.nodes.delete("remove_comment",e.RemoveComment.id).remove()}if("CallbackAdd"in e)this.callbacks.add(this.nodes,e.CallbackAdd.id,e.CallbackAdd.event_name,e.CallbackAdd.callback_id);else{if(!("CallbackRemove"in e))return(e=>{throw console.error(e),Error("unknown command")})(e);this.callbacks.remove(this.nodes,e.CallbackRemove.id,e.CallbackRemove.event_name,e.CallbackRemove.callback_id)}}}}class D{constructor(e,t){this.metadata=e,this.getWasm=t;const o=new _(t);this.dom=new W(e,o,t),this.websocket=new E(t),this.interval=new A(t),this.location=o,this.cookie=new I}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;if("FetchExec"in t)return x(this.getWasm,t.FetchExec.callback,t.FetchExec.request),null;if("WebsocketRegister"in t)return this.websocket.websocket_register_callback(t.WebsocketRegister.host,t.WebsocketRegister.callback),null;if("WebsocketSendMessage"in t)return this.websocket.websocket_send_message(t.WebsocketSendMessage.callback,t.WebsocketSendMessage.message),null;if("WebsocketUnregister"in t)return this.websocket.websocket_unregister_callback(t.WebsocketUnregister.callback),null;if("TimerSet"in t)return this.interval.timerSet(t.TimerSet.callback,t.TimerSet.duration,t.TimerSet.kind),null;if("TimerClear"in t)return this.interval.timerClear(t.TimerClear.callback),null;if("LocationGet"in t)return{value:this.location.get(t.LocationGet.target)};if("LocationCallback"in t)return this.location.callback(t.LocationCallback.target,t.LocationCallback.mode,t.LocationCallback.callback),null;if("LocationSet"in t)return this.location.set(t.LocationSet.target,t.LocationSet.mode,t.LocationSet.value),null;if("CookieGet"in t)return{value:this.cookie.get(t.CookieGet.name)};if("CookieSet"in t)return this.cookie.set(t.CookieSet.name,t.CookieSet.value,t.CookieSet.expires_in),null;if("CookieJsonGet"in t)return{value:this.cookie.getJson(t.CookieJsonGet.name)};if("CookieJsonSet"in t)return this.cookie.setJson(t.CookieJsonSet.name,t.CookieJsonSet.value,t.CookieJsonSet.expires_in),null;if("GetEnv"in t){const e=t.GetEnv.name;return{value:this.metadata.getEnv(e)}}if("Log"in t)switch(t.Log.kind){case"Info":return console.info(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null;case"Debug":return console.debug(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null;case"Error":return console.error(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null;case"Log":return console.log(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null;case"Warn":return console.warn(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null}return"GetRandom"in t?{value:U(t.GetRandom.min,t.GetRandom.max)}:"JsApiCall"in t?this.executeJsApiCall(t.JsApiCall.commands):"DomBulkUpdate"in t?(this.dom.update(t.DomBulkUpdate.list),null):(console.info("exec_command: Arg",t),(()=>{throw Error("assert never")})())}executeJsApiCall(e){let t=null;for(const o of e)if("Root"in o)if("window"===o.Root.name)t=window;else{if("document"!==o.Root.name)return console.error(`Unknown root: ${o.Root.name}`),null;t=document}else if("RootElement"in o){const e=o.RootElement.dom_id,n=this.dom.nodes.getAnyOption(e);if(void 0===n)return console.error(`Element not found: ${e}`),null;t=n}else if("Get"in o){if(null===t)return console.error("Get called on null"),null;t=t[o.Get.property]}else if("Set"in o){if(null===t)return console.error("Set called on null"),null;t[o.Set.property]=o.Set.value,t=void 0}else if("Call"in o){if(null===t)return console.error("Call called on null"),null;t=t[o.Call.method](...o.Call.args)}const o=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=>o(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 n of Object.keys(e))t[n]=o(e[n]);return t}return null};return o(t)}}class H{constructor(){this.get=e=>this.metadata.getAttribute(e)??null,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")??null}}class O{constructor(e){this.wasm=e}vertigoEntryFunction(e,t){this.wasm.exports.vertigo_entry_function(e,t)}static async create(e){let t=null;const n=()=>{if(null===t)throw Error("Wasm is no initialized");return t},s=new H,r=new D(s,n);return window.$vertigoApi=r,t=await g(e,{mod:{panic_message:e=>{const t=Number(e%2n**32n),o=Number(e>>32n),s=new TextDecoder("utf-8"),r=n().getUint8Memory().subarray(o,o+t),i=s.decode(r);console.error("PANIC",i)},dom_access:e=>{if(0n===e)return console.error("dom_access - null pointer"),0n;const t=new o(()=>n().getUint8Memory(),e),s=m(t);n().exports.vertigo_export_free_block(e);const i=r.exec(s),a=u(i),l=n().exports.vertigo_export_alloc_block(a),c=new o(()=>n().getUint8Memory(),l);return f(i,c),l}}}),new O(t)}}const J=new Set,F=async()=>{document.querySelectorAll("*[data-vertigo-run-wasm]").forEach(e=>{const t=e.getAttribute("data-vertigo-run-wasm");"string"==typeof t?(async e=>{if(J.has(e))return;if(J.size>0)return void console.error("Only one wasm module can be run",{moduleRun:J,wasm:e});J.add(e),console.info(`Wasm module: "${e}" -> start`);const t=await O.create(e);console.info(`Wasm module: "${e}" -> initialized`),t.vertigoEntryFunction(0,11),console.info(`Wasm module: "${e}" -> launched vertigoEntryFunction with version 0.11`)})(t):console.error("Run error",e)})};window.addEventListener("load",F),setTimeout(F,3e3);
//# sourceMappingURL=wasm_run.js.map