@hashgraphonline/standards-sdk 0.0.34 → 0.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -44,5 +44,3 @@ export declare class HCS implements HCSSDK {
44
44
  pauseAudio(topicId: string): Promise<void>;
45
45
  loadAndPlayAudio(topicId: string, autoplay?: boolean, volume?: number): Promise<void>;
46
46
  }
47
- declare const _default: any;
48
- export default _default;
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsSDK={})}(this,(function(exports){"use strict";var __defProp2=Object.defineProperty,__typeError=e=>{throw TypeError(e)},__defNormalProp2=(e,t,r)=>t in e?__defProp2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__publicField2=(e,t,r)=>__defNormalProp2(e,"symbol"!=typeof t?t+"":t,r),__accessCheck=(e,t,r)=>t.has(e)||__typeError("Cannot "+r),__privateGet=(e,t,r)=>(__accessCheck(e,t,"read from private field"),r?r.call(e):t.get(e)),__privateAdd=(e,t,r)=>t.has(e)?__typeError("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),__privateSet=(e,t,r,o)=>(__accessCheck(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r),__privateMethod=(e,t,r)=>(__accessCheck(e,t,"access private method"),r),__privateWrapper=(e,t,r,o)=>({set _(o){__privateSet(e,t,o,r)},get _(){return __privateGet(e,t,o)}}),_names,_data,_dataLength,_Writer_instances,writeData_fn,_data2,_offset,_bytesRead,_parent,_maxInflation,_Reader_instances,incrementBytesRead_fn,peekBytes_fn,_options,_offset2,_tokens,_TokenString_instances,subTokenString_fn,_ParamType_instances,walkAsync_fn,_AbiCoder_instances,getCoder_fn,_errors,_events,_functions,_abiCoder,_Interface_instances,getFunction_fn,getEvent_fn;function _mergeNamespaces(e,t){for(var r=0;r<t.length;r++){const o=t[r];if("string"!=typeof o&&!Array.isArray(o))for(const t in o)if("default"!==t&&!(t in e)){const r=Object.getOwnPropertyDescriptor(o,t);r&&Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>o[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}let Logger$2=class e{constructor(e={}){this.level=e.level||"info",this.module=e.module||"",this.enableTimestamp=!1!==e.enableTimestamp,this.silent=e.silent||!1}static getInstance(t={}){return e.instance||(e.instance=new e(t)),e.instance}setLogLevel(e){this.level=e}setSilent(e){this.silent=e}setModule(e){this.module=e}shouldLog(e){if(this.silent)return!1;const t=["debug","info","warn","error"];return t.indexOf(e)>=t.indexOf(this.level)}formatMessage(e,t,r){const o={level:e,message:t,timestamp:(new Date).toISOString(),data:r};return this.module&&(o.module=this.module),o}log(e,t,r){if(!this.shouldLog(e))return;const o=this.formatMessage(e,t,r),n=this.formatOutputMessage(o);switch(e){case"debug":console.debug(n,r||"");break;case"info":console.info(n,r||"");break;case"warn":console.warn(n,r||"");break;case"error":console.error(n,r||"")}}formatOutputMessage(e){const t=[];return this.enableTimestamp&&t.push(`[${e.timestamp}]`),e.module&&t.push(`[${e.module}]`),t.push(`[${e.level.toUpperCase()}]`),t.push(e.message),t.join(" ")}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}};const sleep=e=>new Promise((t=>setTimeout(t,e)));class HCS{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=Logger$2.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach((t=>{if(e.dataset[t]){const r=this.configMapping[t];let o=e.dataset[t];"true"===o&&(o=!0),"false"===o&&(o=!1),isNaN(Number(o))||""===o||(o=Number(o)),this.config[r]=o}})),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(o){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw o}}sleep(e){return new Promise((t=>setTimeout(t,e)))}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const o=r.replace(/['"]+/g,""),n=await this.fetchWithRetry(t+e+"?network="+o);return await n.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),o=t?.split("/").pop(),n=e.getAttribute("type"),i=e.hasAttribute("data-required"),a="module"===e.getAttribute("type");if(!this.isDuplicate(o||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,s=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(o,t,s);if("wasm"===n){const t=await c.arrayBuffer(),o=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(o,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),a){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+n+": "+r,e),this.updateLoadingStatus(r,"failed"),i)throw e}}}catch(s){if(this.error("Failed to load "+n+": "+r,s),this.updateLoadingStatus(r,"failed"),i)throw s}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{return await import(r)}catch(o){throw this.error("Failed to import module",o),o}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),o=t?.split("/").pop(),n=e.hasAttribute("data-required");if(!this.isDuplicate(o||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(o,t,n),a=await i.text(),s=document.createElement("style");s.textContent=a,document.head.appendChild(s),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(i){if(this.error("Failed to load stylesheet: "+r,i),this.updateLoadingStatus(r,"failed"),n)throw i}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(r,t,o),i=URL.createObjectURL(n);e.src=i,this.LoadedImages[r]=i,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(o){this.error("Failed to load image: "+r,o),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),o=r?.split("/").pop();this.log("Loading "+t+": "+o),this.updateLoadingStatus(t+": "+o,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(o,r,n),a=URL.createObjectURL(i);e.src=a,"video"===t?this.LoadedVideos[o]=a:this.LoadedAudioUrls[o]=a,this.updateLoadingStatus(t+": "+o,"loaded"),this.log("Loaded "+t+": "+o)}catch(n){this.error("Failed to load "+t+": "+o,n),this.updateLoadingStatus(t+": "+o,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise((e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",(()=>{this.modelViewerLoaded=!0,e()}),{once:!0}),this.loadScript(t)})),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network;let n;"model-viewer"!==e.tagName.toLowerCase()?(n=document.createElement("model-viewer"),Array.from(e.attributes).forEach((e=>{n.setAttribute(e.name,e.value)})),n.setAttribute("camera-controls",""),n.setAttribute("auto-rotate",""),n.setAttribute("ar",""),e.parentNode?.replaceChild(n,e)):n=e;const i=await this.retrieveHCS1Data(r,t,o),a=URL.createObjectURL(i);n.setAttribute("src",a),this.LoadedGLBs[r]=a,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(o){this.error("Failed to load GLB: "+r,o),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise((o=>{this.loadQueue.push({element:e,type:t,order:r,resolve:o}),this.processQueue()}))}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const n=t.substring(r,e),i=n.split("/").pop();try{const o=this.config.cdnUrl,a=this.config.network,s=await this.retrieveHCS1Data(i,o,a),c=URL.createObjectURL(s);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[i]=c,this.log("Replaced CSS HCS URL: "+n+" with "+c)}catch(o){this.error("Failed to load CSS image: "+i,o)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise((e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),o=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),n=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),i=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),a=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach((e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))})),await this.processInlineStyles();const s=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:o,type:"video"},{elements:n,type:"audio"},{elements:i,type:"glb"},{elements:a,type:"css"}].forEach((({elements:e,type:t})=>{e.forEach((e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;s.push(this.loadResource(e,t,r))}))})),await Promise.all(s);const c=new MutationObserver((e=>{e.forEach((e=>{if(e.addedNodes.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach((e=>{const t=e,r=t.tagName.toLowerCase(),o=t.getAttribute("src");switch(o?.startsWith("hcs://")&&(t.setAttribute("data-src",o),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}}))}})),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}}))}));document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",(()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})})),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}))}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const o=new Audio(r);o.volume=t,this.LoadedAudios[e]=o,o.play().catch((e=>{console.error("Failed to play audio:",e)})),o.addEventListener("ended",(()=>{o.remove(),delete this.LoadedAudios[e]}))}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let o=document.querySelector('audio[data-topic-id="'+e+'"]');if(o)o.volume=r,await o.play();else{const n=document.createElement("audio");n.volume=r,t&&n.setAttribute("autoplay","autoplay"),n.setAttribute("data-topic-id",e),n.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(n),await this.loadMedia(n,"audio"),o=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await o.play()}}}window.HCS=new HCS,window.HCS.init().then((()=>{console.log("All HCS resources loaded"),"function"==typeof window.HCSReady&&(console.log("Running HCSReady..."),window.HCSReady())}));class WasmBridge{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=Logger$2.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),o=t(r.length,1);return this.getUint8Memory().set(r,o),this.WASM_VECTOR_LEN=r.length,o}let o=this.textEncoder.encode(e).length,n=t(o,1);const i=this.getUint8Memory();let a=0;for(;a<o;a++){const t=e.charCodeAt(a);if(t>127)break;i[n+a]=t}if(a!==o){0!==a&&(e=e.slice(a)),n=r(n,o,o=a+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(n+a,n+o);a+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=a,n}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let o=[0,0];try{const n=[r,...t.map((e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN])).flat()];e.apply(this.wasm,n);const i=this.getDataViewMemory().getInt32(r+0,!0),a=this.getDataViewMemory().getInt32(r+4,!0);return o=[i,a],this.getStringFromWasm(i,a)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(o[0],o[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const o=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${o}`),new Error(o)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const o=await WebAssembly.instantiate(t,r);return this.wasm=o.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(o){throw this.logger.error("Failed to initialize WASM module",o),o}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every((e=>e in t.latestRoundData))?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach((([e,o])=>{r.latestRoundData[e]=String(t.latestRoundData[e])}))):Object.entries(e.c.inputType.stateData).forEach((([e,o])=>{const n=t[e];n&&"object"==typeof n&&"values"in n&&n.values.length>0?r[e]=String(n.values[0]):r[e]=this.getDefaultValueForType(o)}))),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}}
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsSDK={})}(this,(function(exports){"use strict";var __defProp2=Object.defineProperty,__typeError=e=>{throw TypeError(e)},__defNormalProp2=(e,t,r)=>t in e?__defProp2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__publicField2=(e,t,r)=>__defNormalProp2(e,"symbol"!=typeof t?t+"":t,r),__accessCheck=(e,t,r)=>t.has(e)||__typeError("Cannot "+r),__privateGet=(e,t,r)=>(__accessCheck(e,t,"read from private field"),r?r.call(e):t.get(e)),__privateAdd=(e,t,r)=>t.has(e)?__typeError("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),__privateSet=(e,t,r,o)=>(__accessCheck(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r),__privateMethod=(e,t,r)=>(__accessCheck(e,t,"access private method"),r),__privateWrapper=(e,t,r,o)=>({set _(o){__privateSet(e,t,o,r)},get _(){return __privateGet(e,t,o)}}),_names,_data,_dataLength,_Writer_instances,writeData_fn,_data2,_offset,_bytesRead,_parent,_maxInflation,_Reader_instances,incrementBytesRead_fn,peekBytes_fn,_options,_offset2,_tokens,_TokenString_instances,subTokenString_fn,_ParamType_instances,walkAsync_fn,_AbiCoder_instances,getCoder_fn,_errors,_events,_functions,_abiCoder,_Interface_instances,getFunction_fn,getEvent_fn;function _mergeNamespaces(e,t){for(var r=0;r<t.length;r++){const o=t[r];if("string"!=typeof o&&!Array.isArray(o))for(const t in o)if("default"!==t&&!(t in e)){const r=Object.getOwnPropertyDescriptor(o,t);r&&Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>o[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}let Logger$2=class e{constructor(e={}){this.level=e.level||"info",this.module=e.module||"",this.enableTimestamp=!1!==e.enableTimestamp,this.silent=e.silent||!1}static getInstance(t={}){return e.instance||(e.instance=new e(t)),e.instance}setLogLevel(e){this.level=e}setSilent(e){this.silent=e}setModule(e){this.module=e}shouldLog(e){if(this.silent)return!1;const t=["debug","info","warn","error"];return t.indexOf(e)>=t.indexOf(this.level)}formatMessage(e,t,r){const o={level:e,message:t,timestamp:(new Date).toISOString(),data:r};return this.module&&(o.module=this.module),o}log(e,t,r){if(!this.shouldLog(e))return;const o=this.formatMessage(e,t,r),n=this.formatOutputMessage(o);switch(e){case"debug":console.debug(n,r||"");break;case"info":console.info(n,r||"");break;case"warn":console.warn(n,r||"");break;case"error":console.error(n,r||"")}}formatOutputMessage(e){const t=[];return this.enableTimestamp&&t.push(`[${e.timestamp}]`),e.module&&t.push(`[${e.module}]`),t.push(`[${e.level.toUpperCase()}]`),t.push(e.message),t.join(" ")}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}};const sleep=e=>new Promise((t=>setTimeout(t,e)));class HCS{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=Logger$2.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach((t=>{if(e.dataset[t]){const r=this.configMapping[t];let o=e.dataset[t];"true"===o&&(o=!0),"false"===o&&(o=!1),isNaN(Number(o))||""===o||(o=Number(o)),this.config[r]=o}})),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(o){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw o}}sleep(e){return new Promise((t=>setTimeout(t,e)))}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const o=r.replace(/['"]+/g,""),n=await this.fetchWithRetry(t+e+"?network="+o);return await n.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),o=t?.split("/").pop(),n=e.getAttribute("type"),i=e.hasAttribute("data-required"),a="module"===e.getAttribute("type");if(!this.isDuplicate(o||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,s=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(o,t,s);if("wasm"===n){const t=await c.arrayBuffer(),o=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(o,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),a){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+n+": "+r,e),this.updateLoadingStatus(r,"failed"),i)throw e}}}catch(s){if(this.error("Failed to load "+n+": "+r,s),this.updateLoadingStatus(r,"failed"),i)throw s}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{return await import(r)}catch(o){throw this.error("Failed to import module",o),o}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),o=t?.split("/").pop(),n=e.hasAttribute("data-required");if(!this.isDuplicate(o||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(o,t,n),a=await i.text(),s=document.createElement("style");s.textContent=a,document.head.appendChild(s),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(i){if(this.error("Failed to load stylesheet: "+r,i),this.updateLoadingStatus(r,"failed"),n)throw i}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(r,t,o),i=URL.createObjectURL(n);e.src=i,this.LoadedImages[r]=i,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(o){this.error("Failed to load image: "+r,o),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),o=r?.split("/").pop();this.log("Loading "+t+": "+o),this.updateLoadingStatus(t+": "+o,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(o,r,n),a=URL.createObjectURL(i);e.src=a,"video"===t?this.LoadedVideos[o]=a:this.LoadedAudioUrls[o]=a,this.updateLoadingStatus(t+": "+o,"loaded"),this.log("Loaded "+t+": "+o)}catch(n){this.error("Failed to load "+t+": "+o,n),this.updateLoadingStatus(t+": "+o,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise((e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",(()=>{this.modelViewerLoaded=!0,e()}),{once:!0}),this.loadScript(t)})),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network;let n;"model-viewer"!==e.tagName.toLowerCase()?(n=document.createElement("model-viewer"),Array.from(e.attributes).forEach((e=>{n.setAttribute(e.name,e.value)})),n.setAttribute("camera-controls",""),n.setAttribute("auto-rotate",""),n.setAttribute("ar",""),e.parentNode?.replaceChild(n,e)):n=e;const i=await this.retrieveHCS1Data(r,t,o),a=URL.createObjectURL(i);n.setAttribute("src",a),this.LoadedGLBs[r]=a,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(o){this.error("Failed to load GLB: "+r,o),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise((o=>{this.loadQueue.push({element:e,type:t,order:r,resolve:o}),this.processQueue()}))}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const n=t.substring(r,e),i=n.split("/").pop();try{const o=this.config.cdnUrl,a=this.config.network,s=await this.retrieveHCS1Data(i,o,a),c=URL.createObjectURL(s);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[i]=c,this.log("Replaced CSS HCS URL: "+n+" with "+c)}catch(o){this.error("Failed to load CSS image: "+i,o)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise((e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),o=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),n=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),i=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),a=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach((e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))})),await this.processInlineStyles();const s=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:o,type:"video"},{elements:n,type:"audio"},{elements:i,type:"glb"},{elements:a,type:"css"}].forEach((({elements:e,type:t})=>{e.forEach((e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;s.push(this.loadResource(e,t,r))}))})),await Promise.all(s);const c=new MutationObserver((e=>{e.forEach((e=>{if(e.addedNodes.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach((e=>{const t=e,r=t.tagName.toLowerCase(),o=t.getAttribute("src");switch(o?.startsWith("hcs://")&&(t.setAttribute("data-src",o),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}}))}})),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}}))}));document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",(()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})})),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}))}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const o=new Audio(r);o.volume=t,this.LoadedAudios[e]=o,o.play().catch((e=>{console.error("Failed to play audio:",e)})),o.addEventListener("ended",(()=>{o.remove(),delete this.LoadedAudios[e]}))}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let o=document.querySelector('audio[data-topic-id="'+e+'"]');if(o)o.volume=r,await o.play();else{const n=document.createElement("audio");n.volume=r,t&&n.setAttribute("autoplay","autoplay"),n.setAttribute("data-topic-id",e),n.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(n),await this.loadMedia(n,"audio"),o=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await o.play()}}}const isServer$1="undefined"==typeof window;isServer$1||(window.HCS=new HCS,window.HCS.init().then((()=>{console.log("All HCS resources loaded"),"function"==typeof window.HCSReady&&(console.log("Running HCSReady..."),window.HCSReady())})));class WasmBridge{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=Logger$2.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),o=t(r.length,1);return this.getUint8Memory().set(r,o),this.WASM_VECTOR_LEN=r.length,o}let o=this.textEncoder.encode(e).length,n=t(o,1);const i=this.getUint8Memory();let a=0;for(;a<o;a++){const t=e.charCodeAt(a);if(t>127)break;i[n+a]=t}if(a!==o){0!==a&&(e=e.slice(a)),n=r(n,o,o=a+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(n+a,n+o);a+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=a,n}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let o=[0,0];try{const n=[r,...t.map((e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN])).flat()];e.apply(this.wasm,n);const i=this.getDataViewMemory().getInt32(r+0,!0),a=this.getDataViewMemory().getInt32(r+4,!0);return o=[i,a],this.getStringFromWasm(i,a)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(o[0],o[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const o=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${o}`),new Error(o)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const o=await WebAssembly.instantiate(t,r);return this.wasm=o.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(o){throw this.logger.error("Failed to initialize WASM module",o),o}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every((e=>e in t.latestRoundData))?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach((([e,o])=>{r.latestRoundData[e]=String(t.latestRoundData[e])}))):Object.entries(e.c.inputType.stateData).forEach((([e,o])=>{const n=t[e];n&&"object"==typeof n&&"values"in n&&n.values.length>0?r[e]=String(n.values[0]):r[e]=this.getDefaultValueForType(o)}))),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}}
2
2
  /**
3
3
  * @license
4
4
  * Copyright 2009 The Closure Library Authors