@subwallet/web-runner 1.3.8-0 → 1.3.10-0

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.
@@ -1 +1 @@
1
- "use strict";(("undefined"!=typeof self?self:this).webpackChunk_subwallet_web_runner=("undefined"!=typeof self?self:this).webpackChunk_subwallet_web_runner||[]).push([[911],{40911:(e,n,t)=>{t.r(n),t.d(n,{AddChainError:()=>s.dK,AlreadyDestroyedError:()=>s.m2,CrashError:()=>s.id,JsonRpcDisabledError:()=>s.Ut,QueueFullError:()=>s.Zm,startWithBytecode:()=>p});var s=t(94830);function o(e,n,t){return c(e,n,t),(new TextDecoder).decode(e.slice(n,n+t))}function r(e,n){return c(e,n,2),e[n]<<8|e[n+1]}function a(e,n){return c(e,n,4),(e[n]|e[n+1]<<8|e[n+2]<<16)+16777216*e[n+3]}function c(e,n,t){if(!Number.isInteger(n)||n<0)throw new RangeError;if(n+t>e.length)throw new RangeError}var i=function(e,n,t,s){return new(t||(t=Promise))((function(o,r){function a(e){try{i(s.next(e))}catch(e){r(e)}}function c(e){try{i(s.throw(e))}catch(e){r(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}i((s=s.apply(e,n||[])).next())}))};var d=function(e,n,t,s){return new(t||(t=Promise))((function(o,r){function a(e){try{i(s.next(e))}catch(e){r(e)}}function c(e){try{i(s.throw(e))}catch(e){r(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}i((s=s.apply(e,n||[])).next())}))};function l(e){return d(this,void 0,void 0,(function*(){const{port1:n,port2:t}=new MessageChannel,s=e.portToServer,o={wasmModule:yield e.wasmModule,serverToClient:t,maxLogLevel:e.maxLogLevel,cpuRateLimit:e.cpuRateLimit,forbidWs:e.forbidWs,forbidWss:e.forbidWss,forbidNonLocalWs:e.forbidNonLocalWs,forbidTcp:e.forbidTcp,forbidWebRtc:e.forbidWebRtc};s.postMessage(o,[t]);const r={jsonRpcResponses:new Map,connections:new Map};return n.onmessage=t=>{const o=t.data;switch(o.ty){case"wasm-panic":case"executor-shutdown":n.close(),s.close();break;case"add-chain-result":if(o.success){r.jsonRpcResponses.set(o.chainId,new Array);const e={ty:"accept-more-json-rpc-answers",chainId:o.chainId};for(let t=0;t<10;++t)n.postMessage(e)}break;case"new-connection":r.connections.set(o.connectionId,new Set);break;case"connection-reset":if(!r.connections.has(o.connectionId))return;r.connections.delete(o.connectionId);break;case"connection-stream-open":if(!r.connections.has(o.connectionId))return;break;case"connection-stream-reset":if(!r.connections.has(o.connectionId))return;if(!r.connections.get(o.connectionId).has(o.streamId))return;break;case"stream-send":case"stream-send-close":if(!r.connections.has(o.connectionId))return;if(o.streamId&&!r.connections.get(o.connectionId).has(o.streamId))return;break;case"json-rpc-response":{const n=r.jsonRpcResponses.get(o.chainId);return void(n&&(n.push(o.response),e.eventCallback({ty:"json-rpc-responses-non-empty",chainId:o.chainId})))}}e.eventCallback(o)},{addChain(e,t,s,o,r,a){return d(this,void 0,void 0,(function*(){const c={ty:"add-chain",chainSpec:e,databaseContent:t,potentialRelayChains:s,disableJsonRpc:o,jsonRpcMaxPendingRequests:r,jsonRpcMaxSubscriptions:a};n.postMessage(c)}))},removeChain(e){r.jsonRpcResponses.delete(e);const t={ty:"remove-chain",chainId:e};n.postMessage(t)},request(e,t){const s={ty:"request",chainId:t,request:e};return n.postMessage(s),0},peekJsonRpcResponse(e){const t=r.jsonRpcResponses.get(e).shift();if(!t)return null;const s={ty:"accept-more-json-rpc-answers",chainId:e};return n.postMessage(s),t},shutdownExecutor(){n.postMessage({ty:"shutdown"})},connectionReset(e,t){r.connections.delete(e);const s={ty:"connection-reset",connectionId:e,message:t};n.postMessage(s)},connectionMultiStreamSetHandshakeInfo(e,t){const s={ty:"connection-multistream-set-info",connectionId:e,info:t};n.postMessage(s)},streamMessage(e,t,s){const o={ty:"stream-message",connectionId:e,message:t,streamId:s};n.postMessage(o)},streamOpened(e,t,s){r.connections.get(e).add(t);const o={ty:"stream-opened",connectionId:e,streamId:t,direction:s};n.postMessage(o)},streamWritableBytes(e,t,s){const o={ty:"stream-writable-bytes",connectionId:e,numExtra:t,streamId:s};n.postMessage(o)},streamReset(e,t,s){r.connections.get(e).delete(t);const o={ty:"stream-reset",connectionId:e,streamId:t,message:s};n.postMessage(o)}}}))}var u=function(e,n,t,s){return new(t||(t=Promise))((function(o,r){function a(e){try{i(s.next(e))}catch(e){r(e)}}function c(e){try{i(s.throw(e))}catch(e){r(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}i((s=s.apply(e,n||[])).next())}))},f=function(e,n,t,s){return new(t||(t=Promise))((function(o,r){function a(e){try{i(s.next(e))}catch(e){r(e)}}function c(e){try{i(s.throw(e))}catch(e){r(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}i((s=s.apply(e,n||[])).next())}))};function p(e){if(e.forbidTcp=!0,"boolean"==typeof isSecureContext&&isSecureContext&&void 0!==typeof location){const n=location.toString();-1!==n.indexOf("localhost")&&-1!==n.indexOf("127.0.0.1")&&-1!==n.indexOf("::1")&&(e.forbidNonLocalWs=!0)}return function(e,n,t){const d=e.logCallback||((e,n,t)=>{e<=1?console.error("[%s] %s",n,t):2==e?console.warn("[%s] %s",n,t):3==e?console.info("[%s] %s",n,t):4==e?console.debug("[%s] %s",n,t):console.trace("[%s] %s",n,t)});n instanceof Promise||(n=Promise.resolve(n));let f=e.cpuRateLimit||1;isNaN(f)&&(f=1),f>1&&(f=1),f<0&&(f=0);const p={instance:{status:"not-created"},chainIds:new WeakMap,connections:new Map,addChainIdAllocations:[],addChainResults:new Map,onExecutorShutdownOrWasmPanic:()=>{},chains:new Map},h=e=>{switch(e.ty){case"wasm-panic":{console.error("Smoldot has panicked"+(e.currentTask?" while executing task `"+e.currentTask+"`":"")+". This is a bug in smoldot. Please open an issue at https://github.com/smol-dot/smoldot/issues with the following message:\n"+e.message),p.instance={status:"destroyed",error:new s.id(e.message)},p.connections.forEach((e=>e.reset())),p.connections.clear();for(const e of p.addChainIdAllocations)e({success:!1,error:"Smoldot has crashed"});p.addChainIdAllocations=[],p.addChainResults.forEach((e=>{e({success:!1,error:"Smoldot has crashed"})})),p.addChainResults.clear();for(const e of Array.from(p.chains.values())){for(const n of e.jsonRpcResponsesPromises)n();e.jsonRpcResponsesPromises=[]}p.chains.clear();const n=p.onExecutorShutdownOrWasmPanic;p.onExecutorShutdownOrWasmPanic=()=>{},n();break}case"executor-shutdown":{const e=p.onExecutorShutdownOrWasmPanic;p.onExecutorShutdownOrWasmPanic=()=>{},e();break}case"log":d(e.level,e.target,e.message);break;case"add-chain-id-allocated":{const n=p.addChainIdAllocations.shift();p.addChainResults.set(e.chainId,n);break}case"add-chain-result":p.addChainResults.get(e.chainId)(e),p.addChainResults.delete(e.chainId);break;case"json-rpc-responses-non-empty":{const n=p.chains.get(e.chainId).jsonRpcResponsesPromises;for(;0!==n.length;)n.shift()();break}case"new-connection":{const n=e.connectionId;p.connections.set(n,t.connect({address:e.address,onConnectionReset(e){if("ready"!==p.instance.status)throw new Error;p.connections.delete(n),p.instance.instance.connectionReset(n,e)},onMessage(e,t){if("ready"!==p.instance.status)throw new Error;p.instance.instance.streamMessage(n,e,t)},onStreamOpened(e,t){if("ready"!==p.instance.status)throw new Error;p.instance.instance.streamOpened(n,e,t)},onMultistreamHandshakeInfo(e){if("ready"!==p.instance.status)throw new Error;p.instance.instance.connectionMultiStreamSetHandshakeInfo(n,e)},onWritableBytes(e,t){if("ready"!==p.instance.status)throw new Error;p.instance.instance.streamWritableBytes(n,e,t)},onStreamReset(e,t){if("ready"!==p.instance.status)throw new Error;p.instance.instance.streamReset(n,e,t)}}));break}case"connection-reset":p.connections.get(e.connectionId).reset(),p.connections.delete(e.connectionId);break;case"connection-stream-open":p.connections.get(e.connectionId).openOutSubstream();break;case"connection-stream-reset":p.connections.get(e.connectionId).reset(e.streamId);break;case"stream-send":p.connections.get(e.connectionId).send(e.data,e.streamId);break;case"stream-send-close":p.connections.get(e.connectionId).closeSend(e.streamId)}},m=e.portToWorker;return p.instance=m?{status:"not-ready",whenReady:l({wasmModule:n.then((e=>e.wasm)),forbidTcp:e.forbidTcp||!1,forbidWs:e.forbidWs||!1,forbidNonLocalWs:e.forbidNonLocalWs||!1,forbidWss:e.forbidWss||!1,forbidWebRtc:e.forbidWebRtc||!1,maxLogLevel:e.maxLogLevel||3,cpuRateLimit:f,portToServer:m,eventCallback:h}).then((e=>{"destroyed"!==p.instance.status&&(p.instance={status:"ready",instance:e})}))}:{status:"not-ready",whenReady:n.then((n=>function(e,n,t){return i(this,void 0,void 0,(function*(){const s={instance:null,currentTask:null,bufferIndices:new Array,advanceExecutionPromise:null,onShutdownExecutorOrWasmPanic:()=>{}},d={panic:(e,n)=>{const r=s.instance;s.instance=null,e>>>=0,n>>>=0;const a=o(new Uint8Array(r.exports.memory.buffer),e,n);throw t({ty:"wasm-panic",message:a,currentTask:s.currentTask}),s.onShutdownExecutorOrWasmPanic(),s.onShutdownExecutorOrWasmPanic=()=>{},new Error},chain_initialized:(e,n,r)=>{const a=s.instance,c=new Uint8Array(a.exports.memory.buffer);if(r>>>=0,0==(n>>>=0))t({ty:"add-chain-result",chainId:e,success:!0});else{const s=o(c,n,r);t({ty:"add-chain-result",chainId:e,success:!1,error:s})}},random_get:(n,t)=>{const o=s.instance;n>>>=0,t>>>=0;const r=new Uint8Array(o.exports.memory.buffer).subarray(n,n+t);for(let n=0;n<t;n+=65536)e.getRandomValues(r.subarray(n,n+65536))},unix_timestamp_us:()=>{const e=Math.floor(Date.now());if(e<0)throw new Error("UNIX timestamp inferior to 0");return BigInt(e)*BigInt(1e3)},monotonic_clock_us:()=>{const n=e.performanceNow(),t=Math.floor(n);return BigInt(t)*BigInt(1e3)+BigInt(Math.floor(1e3*(n-t)))},buffer_size:e=>s.bufferIndices[e].byteLength,buffer_copy:(e,n)=>{const t=s.instance;n>>>=0;const o=s.bufferIndices[e];new Uint8Array(t.exports.memory.buffer).set(o,n)},advance_execution_ready:()=>{s.advanceExecutionPromise&&s.advanceExecutionPromise(),s.advanceExecutionPromise=null},json_rpc_responses_non_empty:e=>{t({ty:"json-rpc-responses-non-empty",chainId:e})},log:(e,n,r,a,c)=>{const i=s.instance;n>>>=0,r>>>=0,a>>>=0,c>>>=0;const d=new Uint8Array(i.exports.memory.buffer);let l=o(d,n,r),u=o(d,a,c);t({ty:"log",level:e,message:u,target:l})},start_timer:e=>{const n=s.instance;e>2147483647&&(e=2147483647),e<1&&"function"==typeof setImmediate?setImmediate((()=>{if(s.instance)try{n.exports.timer_finished()}catch(e){}})):setTimeout((()=>{if(s.instance)try{n.exports.timer_finished()}catch(e){}}),e)},connection_type_supported:n=>{switch(n){case 0:case 1:case 2:return e.forbidTcp?0:1;case 4:case 5:case 6:return e.forbidNonLocalWs?0:1;case 7:return e.forbidWs?0:1;case 14:return e.forbidWss?0:1;case 16:case 17:return e.forbidWebRtc?0:1;default:throw new Error("Invalid connection type passed to `connection_type_supported`")}},connection_new:(e,n,a)=>{const i=s.instance,d=new Uint8Array(i.exports.memory.buffer);let l;switch(a>>>=0,c(u=d,f=n>>>=0,1),u[f]){case 0:case 1:case 2:l={ty:"tcp",port:r(d,n+1),hostname:o(d,n+3,a-3)};break;case 4:case 6:{const e=r(d,n+1);l={ty:"websocket",url:"ws://"+o(d,n+3,a-3)+":"+e};break}case 5:{const e=r(d,n+1);l={ty:"websocket",url:"ws://["+o(d,n+3,a-3)+"]:"+e};break}case 14:{const e=r(d,n+1);l={ty:"websocket",url:"wss://"+o(d,n+3,a-3)+":"+e};break}case 16:{const e=r(d,n+1);l={ty:"webrtc",ipVersion:"4",remoteTlsCertificateSha256:d.slice(n+3,n+35),targetIp:o(d,n+35,a-35),targetPort:e};break}case 17:{const e=r(d,n+1);l={ty:"webrtc",ipVersion:"6",remoteTlsCertificateSha256:d.slice(n+3,n+35),targetIp:o(d,n+35,a-35),targetPort:e};break}default:throw new Error("Invalid encoded address passed to `connection_new`")}var u,f;t({ty:"new-connection",connectionId:e,address:l})},reset_connection:e=>{t({ty:"connection-reset",connectionId:e})},connection_stream_open:e=>{t({ty:"connection-stream-open",connectionId:e})},connection_stream_reset:(e,n)=>{t({ty:"connection-stream-reset",connectionId:e,streamId:n})},stream_send:(e,n,o,r)=>{const c=s.instance,i=new Uint8Array(c.exports.memory.buffer);o>>>=0,r>>>=0;const d=new Array;for(let e=0;e<r;++e){const n=a(i,o+8*e),t=a(i,o+8*e+4);d.push(i.slice(n,n+t))}t({ty:"stream-send",connectionId:e,streamId:n,data:d})},stream_send_close:(e,n)=>{t({ty:"stream-send-close",connectionId:e,streamId:n})},current_task_entered:(e,n)=>{e>>>=0,n>>>=0;const t=o(new Uint8Array(s.instance.exports.memory.buffer),e,n);s.currentTask=t},current_task_exit:()=>{s.currentTask=null}},l=yield WebAssembly.instantiate(n,{smoldot:d});s.instance=l,s.instance.exports.init(e.maxLogLevel);const u=new Promise((e=>s.onShutdownExecutorOrWasmPanic=()=>e("stop")));return(()=>{i(this,void 0,void 0,(function*(){const n=e.cpuRateLimit;let o=0,r=e.performanceNow();for(;;){const t=new Promise((e=>s.advanceExecutionPromise=()=>e("ready")));if(!s.instance)break;s.instance.exports.advance_execution();const a=e.performanceNow(),c=a-r;if(r=a,o+=c*(1/n-1),o>5){o>2147483646&&(o=2147483646);const e=new Promise((e=>setTimeout((()=>e("timeout")),o)));if("stop"===(yield Promise.race([e,u])))break}if("stop"===(yield Promise.race([t,u])))break;const i=e.performanceNow();o-=i-r,o<-1e4&&(o=-1e4),r=i}s.instance&&t({ty:"executor-shutdown"})}))})(),{request:(e,n)=>s.instance?(s.bufferIndices[0]=(new TextEncoder).encode(e),s.instance.exports.json_rpc_send(0,n)>>>0):1,peekJsonRpcResponse:e=>{if(!s.instance)return null;const n=new Uint8Array(s.instance.exports.memory.buffer),t=s.instance.exports.json_rpc_responses_peek(e)>>>0,r=a(n,t)>>>0,c=a(n,t+4)>>>0;if(0!==c){const t=o(n,r,c);return s.instance.exports.json_rpc_responses_pop(e),t}return null},addChain:(e,n,o,r,a,i)=>{if(!s.instance)return t({ty:"add-chain-id-allocated",chainId:0}),void t({ty:"add-chain-result",chainId:0,success:!1,error:"Smoldot has crashed"});console.assert(r||0!=a,"invalid jsonRpcMaxPendingRequests value passed to local-instance::addChain"),s.bufferIndices[0]=(new TextEncoder).encode(e),s.bufferIndices[1]=(new TextEncoder).encode(n);const d=new Uint8Array(4*o.length);for(let e=0;e<o.length;++e)l=d,u=4*e,f=o[e],c(l,u,4),l[u+3]=f>>>24&255,l[u+2]=f>>>16&255,l[u+1]=f>>>8&255,l[u]=255&f;var l,u,f;s.bufferIndices[2]=d;const p=s.instance.exports.add_chain(0,1,r?0:a,i,2);delete s.bufferIndices[0],delete s.bufferIndices[1],delete s.bufferIndices[2],t({ty:"add-chain-id-allocated",chainId:p})},removeChain:e=>{s.instance&&s.instance.exports.remove_chain(e)},shutdownExecutor:()=>{if(!s.instance)return;const e=s.onShutdownExecutorOrWasmPanic;s.onShutdownExecutorOrWasmPanic=()=>{},e()},connectionMultiStreamSetHandshakeInfo:(e,n)=>{if(!s.instance)return;const t=new Uint8Array(1+n.localTlsCertificateSha256.length);var o;c(o=t,0,1),o[0]=0,t.set(n.localTlsCertificateSha256,1),s.bufferIndices[0]=t,s.instance.exports.connection_multi_stream_set_handshake_info(e,0),delete s.bufferIndices[0]},connectionReset:(e,n)=>{s.instance&&(s.bufferIndices[0]=(new TextEncoder).encode(n),s.instance.exports.connection_reset(e,0),delete s.bufferIndices[0])},streamWritableBytes:(e,n,t)=>{s.instance&&s.instance.exports.stream_writable_bytes(e,t||0,n)},streamMessage:(e,n,t)=>{s.instance&&(s.bufferIndices[0]=n,s.instance.exports.stream_message(e,t||0,0),delete s.bufferIndices[0])},streamOpened:(e,n,t)=>{s.instance&&s.instance.exports.connection_stream_opened(e,n,"outbound"===t?1:0)},streamReset:(e,n,t)=>{s.instance&&(s.bufferIndices[0]=(new TextEncoder).encode(t),s.instance.exports.stream_reset(e,n,0),delete s.bufferIndices[0])}}}))}({forbidTcp:e.forbidTcp||!1,forbidWs:e.forbidWs||!1,forbidNonLocalWs:e.forbidNonLocalWs||!1,forbidWss:e.forbidWss||!1,forbidWebRtc:e.forbidWebRtc||!1,maxLogLevel:e.maxLogLevel||3,cpuRateLimit:f,envVars:[],performanceNow:t.performanceNow,getRandomValues:t.getRandomValues},n.wasm,h))).then((e=>{"destroyed"!==p.instance.status&&(p.instance={status:"ready",instance:e})}))},{addChain:e=>u(this,void 0,void 0,(function*(){if("not-ready"===p.instance.status&&(yield p.instance.whenReady),"destroyed"===p.instance.status)throw p.instance.error;if("not-created"===p.instance.status||"not-ready"===p.instance.status)throw new Error;if("string"!=typeof e.chainSpec)throw new Error("Chain specification must be a string");let n=[];if(e.potentialRelayChains)for(const t of e.potentialRelayChains){const e=p.chainIds.get(t);void 0!==e&&n.push(e)}let t=void 0===e.jsonRpcMaxPendingRequests?1/0:e.jsonRpcMaxPendingRequests;if(t=Math.floor(t),t<=0||isNaN(t))throw new s.dK("Invalid value for `jsonRpcMaxPendingRequests`");t>4294967295&&(t=4294967295);let o=void 0===e.jsonRpcMaxSubscriptions?1/0:e.jsonRpcMaxSubscriptions;if(o=Math.floor(o),o<0||isNaN(o))throw new s.dK("Invalid value for `jsonRpcMaxSubscriptions`");if(o>4294967295&&(o=4294967295),void 0!==e.databaseContent&&"string"!=typeof e.databaseContent)throw new s.dK("`databaseContent` is not a string");const r=new Promise((e=>p.addChainIdAllocations.push(e)));p.instance.instance.addChain(e.chainSpec,e.databaseContent||"",n,!!e.disableJsonRpc,t,o);const a=yield r;if(!a.success)throw new s.dK(a.error);const c=a.chainId;p.chains.set(c,{jsonRpcResponsesPromises:new Array});const i={sendJsonRpc:n=>{if("destroyed"===p.instance.status)throw p.instance.error;if("ready"!==p.instance.status)throw new Error;if(!p.chains.has(c))throw new s.m2;if(e.disableJsonRpc)throw new s.Ut;const t=p.instance.instance.request(n,c);switch(t){case 0:break;case 1:throw new s.Zm;default:throw new Error("Internal error: unknown json_rpc_send error code: "+t)}},nextJsonRpcResponse:()=>u(this,void 0,void 0,(function*(){for(;;){if(!p.chains.has(c))throw new s.m2;if(e.disableJsonRpc)return Promise.reject(new s.Ut);if("destroyed"===p.instance.status)throw p.instance.error;if("ready"!==p.instance.status)throw new Error;const n=p.instance.instance.peekJsonRpcResponse(c);if(n)return n;yield new Promise((e=>{p.chains.get(c).jsonRpcResponsesPromises.push(e)}))}})),remove:()=>{if("destroyed"===p.instance.status)throw p.instance.error;if("ready"!==p.instance.status)throw new Error;if(!p.chains.has(c))throw new s.m2;console.assert(p.chainIds.has(i)),p.chainIds.delete(i);for(const e of p.chains.get(c).jsonRpcResponsesPromises)e();p.chains.delete(c),p.instance.instance.removeChain(c)}};return p.chainIds.set(i,c),i})),terminate:()=>u(this,void 0,void 0,(function*(){if("not-ready"===p.instance.status&&(yield p.instance.whenReady),"destroyed"===p.instance.status)throw p.instance.error;if("ready"!==p.instance.status)throw new Error;p.instance.instance.shutdownExecutor(),yield new Promise((e=>p.onExecutorShutdownOrWasmPanic=e)),"ready"===p.instance.status&&(p.instance={status:"destroyed",error:new s.m2}),p.connections.forEach((e=>e.reset())),p.connections.clear();for(const e of p.addChainIdAllocations)e({success:!1,error:"Client.terminate() has been called"});p.addChainIdAllocations=[],p.addChainResults.forEach((e=>{e({success:!1,error:"Client.terminate() has been called"})})),p.addChainResults.clear();for(const e of Array.from(p.chains.values())){for(const n of e.jsonRpcResponsesPromises)n();e.jsonRpcResponsesPromises=[]}p.chains.clear()}))}}(e,e.bytecode,{performanceNow:()=>performance.now(),getRandomValues:e=>{const n=globalThis.crypto;if(!n)throw new Error("randomness not available");if(e.buffer instanceof ArrayBuffer)n.getRandomValues(e);else{const t=new Uint8Array(e.length);n.getRandomValues(t),e.set(t)}},connect:e=>function(e){if("websocket"===e.address.ty){let n;try{n=new WebSocket(e.address.url)}catch(e){n=e instanceof Error?e.toString():"Exception thrown by new WebSocket"}const t={quenedUnreportedBytes:0,nextTimeout:10},s=()=>{if(!(n instanceof WebSocket))return;if(1!=n.readyState)return;const o=n.bufferedAmount;let r=t.quenedUnreportedBytes-o;r<0&&(r=0),t.quenedUnreportedBytes-=r,0!=t.quenedUnreportedBytes&&(setTimeout(s,t.nextTimeout),t.nextTimeout*=2,t.nextTimeout>500&&(t.nextTimeout=500)),0!=r&&e.onWritableBytes(r)};return n instanceof WebSocket?(n.binaryType="arraybuffer",n.onopen=()=>{e.onWritableBytes(1048576)},n.onclose=n=>{const t="Error code "+n.code+(n.reason?": "+n.reason:"");e.onConnectionReset(t)},n.onmessage=n=>{e.onMessage(new Uint8Array(n.data))}):setTimeout((()=>{!n||n instanceof WebSocket||(e.onConnectionReset(n),n=null)}),1),{reset:()=>{n instanceof WebSocket&&(n.onopen=null,n.onclose=null,n.onmessage=null,n.onerror=null,n.readyState==WebSocket.OPEN&&n.close()),n=null},send:e=>{0==t.quenedUnreportedBytes&&(t.nextTimeout=10,setTimeout(s,10));for(const n of e)t.quenedUnreportedBytes+=n.length;n.send(new Blob(e))},closeSend:()=>{throw new Error("Wrong connection type")},openOutSubstream:()=>{throw new Error("Wrong connection type")}}}if("webrtc"===e.address.ty){const{targetPort:n,ipVersion:t,targetIp:s,remoteTlsCertificateSha256:o}=e.address,r={pc:void 0,dataChannels:new Map,nextStreamId:0,isFirstOutSubstream:!0},a=()=>{if(!r.pc)return console.assert(0===r.dataChannels.size,"substreams exist while pc is undef"),void(r.pc=null);r.pc.onconnectionstatechange=null,r.pc.onnegotiationneeded=null,r.pc.ondatachannel=null;for(const e of Array.from(r.dataChannels.values()))e.channel.onopen=null,e.channel.onerror=null,e.channel.onclose=null,e.channel.onbufferedamountlow=null,e.channel.onmessage=null;r.dataChannels.clear(),r.pc.close()},c=(n,t)=>{const s=r.nextStreamId;r.nextStreamId+=1,n.binaryType="arraybuffer";let o={value:!1};n.onopen=()=>{console.assert(!o.value,"substream opened twice"),o.value=!0,e.onStreamOpened(s,t),e.onWritableBytes(65536,s)},n.onerror=n.onclose=t=>{const c=t instanceof RTCErrorEvent?t.error.toString():"RTCDataChannel closed";o.value?(n.onopen=null,n.onerror=null,n.onclose=null,n.onbufferedamountlow=null,n.onmessage=null,r.dataChannels.delete(s),e.onStreamReset(s,c)):(a(),e.onConnectionReset("data channel failed to open: "+c))},n.onbufferedamountlow=()=>{const n=r.dataChannels.get(s),t=n.bufferedBytes;n.bufferedBytes=0,e.onWritableBytes(t,s)},n.onmessage=n=>{e.onMessage(new Uint8Array(n.data),s)},r.dataChannels.set(s,{channel:n,bufferedBytes:0})};return RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"}).then((i=>f(this,void 0,void 0,(function*(){if(null===r.pc)return;if(("localhost"==s||"127.0.0.1"==s||"::1"==s)&&-1!==navigator.userAgent.indexOf("Firefox"))return a(),void e.onConnectionReset("Firefox can't connect to a localhost WebRTC server");let d;if(r.pc=new RTCPeerConnection({certificates:[i]}),i.getFingerprints){for(const{algorithm:e,value:n}of i.getFingerprints())if("sha-256"===e){d=n;break}}else{const e=(yield r.pc.createOffer()).sdp.match(/a(\s*)=(\s*)fingerprint:(\s*)(sha|SHA)-256(\s*)(([a-fA-F0-9]{2}(:)*){32})/);e&&(d=e[6])}if(void 0===d)return void e.onConnectionReset("Failed to obtain the browser certificate fingerprint");let l=new Uint8Array(32);l.set(d.split(":").map((e=>parseInt(e,16))),0),r.pc.onconnectionstatechange=n=>{"closed"!=r.pc.connectionState&&"disconnected"!=r.pc.connectionState&&"failed"!=r.pc.connectionState||(a(),e.onConnectionReset("WebRTC state transitioned to "+r.pc.connectionState))},r.pc.onnegotiationneeded=e=>f(this,void 0,void 0,(function*(){var e;let a=(yield r.pc.createOffer()).sdp;null===a.match(/^m=application(\s+)(\d+)(\s+)UDP\/DTLS\/SCTP(\s+)webrtc-datachannel$/m)&&console.error("Local offer doesn't contain UDP data channel. WebRTC connections will likely fail. Please report this issue.");const c=null===(e=a.match(/^a=ice-pwd:(.+)$/m))||void 0===e?void 0:e.at(1);void 0===c&&console.error("Failed to set ufrag to pwd. WebRTC connections will likely fail. Please report this issue.");const i="libp2p+webrtc+v1/"+c;a=a.replace(/^a=ice-ufrag.*$/m,"a=ice-ufrag:"+i),a=a.replace(/^a=ice-pwd.*$/m,"a=ice-pwd:"+i),yield r.pc.setLocalDescription({type:"offer",sdp:a});const d=Array.from(o).map((e=>("0"+e.toString(16)).slice(-2).toUpperCase())).join(":"),l="v=0\no=- 0 0 IN IP"+t+" "+s+"\ns=-\nt=0 0\na=ice-lite\nm=application "+String(n)+" UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP"+t+" "+s+"\na=mid:0\na=ice-options:ice2\na=ice-ufrag:"+i+"\na=ice-pwd:"+i+"\na=fingerprint:sha-256 "+d+"\na=setup:passive\na=sctp-port:5000\na=max-message-size:16384\na=candidate:1 1 UDP 1 "+s+" "+String(n)+" typ host\n";yield r.pc.setRemoteDescription({type:"answer",sdp:l})})),r.pc.ondatachannel=({channel:e})=>{c(e,"inbound")},e.onMultistreamHandshakeInfo({handshake:"webrtc",localTlsCertificateSha256:l})})))),{reset:e=>{if(void 0===e)a();else{const n=r.dataChannels.get(e);n.channel.onopen=null,n.channel.onerror=null,n.channel.onclose=null,n.channel.onbufferedamountlow=null,n.channel.onmessage=null,n.channel.close(),r.dataChannels.delete(e)}},send:(e,n)=>{const t=r.dataChannels.get(n);for(const n of e)t.bufferedBytes+=n.length;t.channel.send(new Blob(e))},closeSend:()=>{throw new Error("Wrong connection type")},openOutSubstream:()=>{const e=r.isFirstOutSubstream?{negotiated:!0,id:0}:{};r.isFirstOutSubstream=!1,c(r.pc.createDataChannel("",e),"outbound")}}}throw new Error}(e)})}},94830:(e,n,t)=>{t.d(n,{Ut:()=>r,Zm:()=>c,dK:()=>s,id:()=>a,m2:()=>o});class s extends Error{constructor(e){super(e),this.name="AddChainError"}}class o extends Error{constructor(){super(),this.name="AlreadyDestroyedError"}}class r extends Error{constructor(){super(),this.name="JsonRpcDisabledError"}}class a extends Error{constructor(e){super(e)}}class c extends Error{constructor(){super("JSON-RPC requests queue is full")}}}}]);
1
+ "use strict";(("undefined"!=typeof self?self:this).webpackChunk_subwallet_web_runner=("undefined"!=typeof self?self:this).webpackChunk_subwallet_web_runner||[]).push([[337],{21337:(e,n,t)=>{t.r(n),t.d(n,{AddChainError:()=>s.dK,AlreadyDestroyedError:()=>s.m2,CrashError:()=>s.id,JsonRpcDisabledError:()=>s.Ut,QueueFullError:()=>s.Zm,startWithBytecode:()=>p});var s=t(51416);function o(e,n,t){return c(e,n,t),(new TextDecoder).decode(e.slice(n,n+t))}function r(e,n){return c(e,n,2),e[n]<<8|e[n+1]}function a(e,n){return c(e,n,4),(e[n]|e[n+1]<<8|e[n+2]<<16)+16777216*e[n+3]}function c(e,n,t){if(!Number.isInteger(n)||n<0)throw new RangeError;if(n+t>e.length)throw new RangeError}var i=function(e,n,t,s){return new(t||(t=Promise))((function(o,r){function a(e){try{i(s.next(e))}catch(e){r(e)}}function c(e){try{i(s.throw(e))}catch(e){r(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}i((s=s.apply(e,n||[])).next())}))};var d=function(e,n,t,s){return new(t||(t=Promise))((function(o,r){function a(e){try{i(s.next(e))}catch(e){r(e)}}function c(e){try{i(s.throw(e))}catch(e){r(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}i((s=s.apply(e,n||[])).next())}))};function l(e){return d(this,void 0,void 0,(function*(){const{port1:n,port2:t}=new MessageChannel,s=e.portToServer,o={wasmModule:yield e.wasmModule,serverToClient:t,maxLogLevel:e.maxLogLevel,cpuRateLimit:e.cpuRateLimit,forbidWs:e.forbidWs,forbidWss:e.forbidWss,forbidNonLocalWs:e.forbidNonLocalWs,forbidTcp:e.forbidTcp,forbidWebRtc:e.forbidWebRtc};s.postMessage(o,[t]);const r={jsonRpcResponses:new Map,connections:new Map};return n.onmessage=t=>{const o=t.data;switch(o.ty){case"wasm-panic":case"executor-shutdown":n.close(),s.close();break;case"add-chain-result":if(o.success){r.jsonRpcResponses.set(o.chainId,new Array);const e={ty:"accept-more-json-rpc-answers",chainId:o.chainId};for(let t=0;t<10;++t)n.postMessage(e)}break;case"new-connection":r.connections.set(o.connectionId,new Set);break;case"connection-reset":if(!r.connections.has(o.connectionId))return;r.connections.delete(o.connectionId);break;case"connection-stream-open":if(!r.connections.has(o.connectionId))return;break;case"connection-stream-reset":if(!r.connections.has(o.connectionId))return;if(!r.connections.get(o.connectionId).has(o.streamId))return;break;case"stream-send":case"stream-send-close":if(!r.connections.has(o.connectionId))return;if(o.streamId&&!r.connections.get(o.connectionId).has(o.streamId))return;break;case"json-rpc-response":{const n=r.jsonRpcResponses.get(o.chainId);return void(n&&(n.push(o.response),e.eventCallback({ty:"json-rpc-responses-non-empty",chainId:o.chainId})))}}e.eventCallback(o)},{addChain(e,t,s,o,r,a){return d(this,void 0,void 0,(function*(){const c={ty:"add-chain",chainSpec:e,databaseContent:t,potentialRelayChains:s,disableJsonRpc:o,jsonRpcMaxPendingRequests:r,jsonRpcMaxSubscriptions:a};n.postMessage(c)}))},removeChain(e){r.jsonRpcResponses.delete(e);const t={ty:"remove-chain",chainId:e};n.postMessage(t)},request(e,t){const s={ty:"request",chainId:t,request:e};return n.postMessage(s),0},peekJsonRpcResponse(e){const t=r.jsonRpcResponses.get(e).shift();if(!t)return null;const s={ty:"accept-more-json-rpc-answers",chainId:e};return n.postMessage(s),t},shutdownExecutor(){n.postMessage({ty:"shutdown"})},connectionReset(e,t){r.connections.delete(e);const s={ty:"connection-reset",connectionId:e,message:t};n.postMessage(s)},connectionMultiStreamSetHandshakeInfo(e,t){const s={ty:"connection-multistream-set-info",connectionId:e,info:t};n.postMessage(s)},streamMessage(e,t,s){const o={ty:"stream-message",connectionId:e,message:t,streamId:s};n.postMessage(o)},streamOpened(e,t,s){r.connections.get(e).add(t);const o={ty:"stream-opened",connectionId:e,streamId:t,direction:s};n.postMessage(o)},streamWritableBytes(e,t,s){const o={ty:"stream-writable-bytes",connectionId:e,numExtra:t,streamId:s};n.postMessage(o)},streamReset(e,t,s){r.connections.get(e).delete(t);const o={ty:"stream-reset",connectionId:e,streamId:t,message:s};n.postMessage(o)}}}))}var u=function(e,n,t,s){return new(t||(t=Promise))((function(o,r){function a(e){try{i(s.next(e))}catch(e){r(e)}}function c(e){try{i(s.throw(e))}catch(e){r(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}i((s=s.apply(e,n||[])).next())}))},f=function(e,n,t,s){return new(t||(t=Promise))((function(o,r){function a(e){try{i(s.next(e))}catch(e){r(e)}}function c(e){try{i(s.throw(e))}catch(e){r(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}i((s=s.apply(e,n||[])).next())}))};function p(e){if(e.forbidTcp=!0,"boolean"==typeof isSecureContext&&isSecureContext&&void 0!==typeof location){const n=location.toString();-1!==n.indexOf("localhost")&&-1!==n.indexOf("127.0.0.1")&&-1!==n.indexOf("::1")&&(e.forbidNonLocalWs=!0)}return function(e,n,t){const d=e.logCallback||((e,n,t)=>{e<=1?console.error("[%s] %s",n,t):2==e?console.warn("[%s] %s",n,t):3==e?console.info("[%s] %s",n,t):4==e?console.debug("[%s] %s",n,t):console.trace("[%s] %s",n,t)});n instanceof Promise||(n=Promise.resolve(n));let f=e.cpuRateLimit||1;isNaN(f)&&(f=1),f>1&&(f=1),f<0&&(f=0);const p={instance:{status:"not-created"},chainIds:new WeakMap,connections:new Map,addChainIdAllocations:[],addChainResults:new Map,onExecutorShutdownOrWasmPanic:()=>{},chains:new Map},h=e=>{switch(e.ty){case"wasm-panic":{console.error("Smoldot has panicked"+(e.currentTask?" while executing task `"+e.currentTask+"`":"")+". This is a bug in smoldot. Please open an issue at https://github.com/smol-dot/smoldot/issues with the following message:\n"+e.message),p.instance={status:"destroyed",error:new s.id(e.message)},p.connections.forEach((e=>e.reset())),p.connections.clear();for(const e of p.addChainIdAllocations)e({success:!1,error:"Smoldot has crashed"});p.addChainIdAllocations=[],p.addChainResults.forEach((e=>{e({success:!1,error:"Smoldot has crashed"})})),p.addChainResults.clear();for(const e of Array.from(p.chains.values())){for(const n of e.jsonRpcResponsesPromises)n();e.jsonRpcResponsesPromises=[]}p.chains.clear();const n=p.onExecutorShutdownOrWasmPanic;p.onExecutorShutdownOrWasmPanic=()=>{},n();break}case"executor-shutdown":{const e=p.onExecutorShutdownOrWasmPanic;p.onExecutorShutdownOrWasmPanic=()=>{},e();break}case"log":d(e.level,e.target,e.message);break;case"add-chain-id-allocated":{const n=p.addChainIdAllocations.shift();p.addChainResults.set(e.chainId,n);break}case"add-chain-result":p.addChainResults.get(e.chainId)(e),p.addChainResults.delete(e.chainId);break;case"json-rpc-responses-non-empty":{const n=p.chains.get(e.chainId).jsonRpcResponsesPromises;for(;0!==n.length;)n.shift()();break}case"new-connection":{const n=e.connectionId;p.connections.set(n,t.connect({address:e.address,onConnectionReset(e){if("ready"!==p.instance.status)throw new Error;p.connections.delete(n),p.instance.instance.connectionReset(n,e)},onMessage(e,t){if("ready"!==p.instance.status)throw new Error;p.instance.instance.streamMessage(n,e,t)},onStreamOpened(e,t){if("ready"!==p.instance.status)throw new Error;p.instance.instance.streamOpened(n,e,t)},onMultistreamHandshakeInfo(e){if("ready"!==p.instance.status)throw new Error;p.instance.instance.connectionMultiStreamSetHandshakeInfo(n,e)},onWritableBytes(e,t){if("ready"!==p.instance.status)throw new Error;p.instance.instance.streamWritableBytes(n,e,t)},onStreamReset(e,t){if("ready"!==p.instance.status)throw new Error;p.instance.instance.streamReset(n,e,t)}}));break}case"connection-reset":p.connections.get(e.connectionId).reset(),p.connections.delete(e.connectionId);break;case"connection-stream-open":p.connections.get(e.connectionId).openOutSubstream();break;case"connection-stream-reset":p.connections.get(e.connectionId).reset(e.streamId);break;case"stream-send":p.connections.get(e.connectionId).send(e.data,e.streamId);break;case"stream-send-close":p.connections.get(e.connectionId).closeSend(e.streamId)}},m=e.portToWorker;return p.instance=m?{status:"not-ready",whenReady:l({wasmModule:n.then((e=>e.wasm)),forbidTcp:e.forbidTcp||!1,forbidWs:e.forbidWs||!1,forbidNonLocalWs:e.forbidNonLocalWs||!1,forbidWss:e.forbidWss||!1,forbidWebRtc:e.forbidWebRtc||!1,maxLogLevel:e.maxLogLevel||3,cpuRateLimit:f,portToServer:m,eventCallback:h}).then((e=>{"destroyed"!==p.instance.status&&(p.instance={status:"ready",instance:e})}))}:{status:"not-ready",whenReady:n.then((n=>function(e,n,t){return i(this,void 0,void 0,(function*(){const s={instance:null,currentTask:null,bufferIndices:new Array,advanceExecutionPromise:null,onShutdownExecutorOrWasmPanic:()=>{}},d={panic:(e,n)=>{const r=s.instance;s.instance=null,e>>>=0,n>>>=0;const a=o(new Uint8Array(r.exports.memory.buffer),e,n);throw t({ty:"wasm-panic",message:a,currentTask:s.currentTask}),s.onShutdownExecutorOrWasmPanic(),s.onShutdownExecutorOrWasmPanic=()=>{},new Error},chain_initialized:(e,n,r)=>{const a=s.instance,c=new Uint8Array(a.exports.memory.buffer);if(r>>>=0,0==(n>>>=0))t({ty:"add-chain-result",chainId:e,success:!0});else{const s=o(c,n,r);t({ty:"add-chain-result",chainId:e,success:!1,error:s})}},random_get:(n,t)=>{const o=s.instance;n>>>=0,t>>>=0;const r=new Uint8Array(o.exports.memory.buffer).subarray(n,n+t);for(let n=0;n<t;n+=65536)e.getRandomValues(r.subarray(n,n+65536))},unix_timestamp_us:()=>{const e=Math.floor(Date.now());if(e<0)throw new Error("UNIX timestamp inferior to 0");return BigInt(e)*BigInt(1e3)},monotonic_clock_us:()=>{const n=e.performanceNow(),t=Math.floor(n);return BigInt(t)*BigInt(1e3)+BigInt(Math.floor(1e3*(n-t)))},buffer_size:e=>s.bufferIndices[e].byteLength,buffer_copy:(e,n)=>{const t=s.instance;n>>>=0;const o=s.bufferIndices[e];new Uint8Array(t.exports.memory.buffer).set(o,n)},advance_execution_ready:()=>{s.advanceExecutionPromise&&s.advanceExecutionPromise(),s.advanceExecutionPromise=null},json_rpc_responses_non_empty:e=>{t({ty:"json-rpc-responses-non-empty",chainId:e})},log:(e,n,r,a,c)=>{const i=s.instance;n>>>=0,r>>>=0,a>>>=0,c>>>=0;const d=new Uint8Array(i.exports.memory.buffer);let l=o(d,n,r),u=o(d,a,c);t({ty:"log",level:e,message:u,target:l})},start_timer:e=>{const n=s.instance;e>2147483647&&(e=2147483647),e<1&&"function"==typeof setImmediate?setImmediate((()=>{if(s.instance)try{n.exports.timer_finished()}catch(e){}})):setTimeout((()=>{if(s.instance)try{n.exports.timer_finished()}catch(e){}}),e)},connection_type_supported:n=>{switch(n){case 0:case 1:case 2:return e.forbidTcp?0:1;case 4:case 5:case 6:return e.forbidNonLocalWs?0:1;case 7:return e.forbidWs?0:1;case 14:return e.forbidWss?0:1;case 16:case 17:return e.forbidWebRtc?0:1;default:throw new Error("Invalid connection type passed to `connection_type_supported`")}},connection_new:(e,n,a)=>{const i=s.instance,d=new Uint8Array(i.exports.memory.buffer);let l;switch(a>>>=0,c(u=d,f=n>>>=0,1),u[f]){case 0:case 1:case 2:l={ty:"tcp",port:r(d,n+1),hostname:o(d,n+3,a-3)};break;case 4:case 6:{const e=r(d,n+1);l={ty:"websocket",url:"ws://"+o(d,n+3,a-3)+":"+e};break}case 5:{const e=r(d,n+1);l={ty:"websocket",url:"ws://["+o(d,n+3,a-3)+"]:"+e};break}case 14:{const e=r(d,n+1);l={ty:"websocket",url:"wss://"+o(d,n+3,a-3)+":"+e};break}case 16:{const e=r(d,n+1);l={ty:"webrtc",ipVersion:"4",remoteTlsCertificateSha256:d.slice(n+3,n+35),targetIp:o(d,n+35,a-35),targetPort:e};break}case 17:{const e=r(d,n+1);l={ty:"webrtc",ipVersion:"6",remoteTlsCertificateSha256:d.slice(n+3,n+35),targetIp:o(d,n+35,a-35),targetPort:e};break}default:throw new Error("Invalid encoded address passed to `connection_new`")}var u,f;t({ty:"new-connection",connectionId:e,address:l})},reset_connection:e=>{t({ty:"connection-reset",connectionId:e})},connection_stream_open:e=>{t({ty:"connection-stream-open",connectionId:e})},connection_stream_reset:(e,n)=>{t({ty:"connection-stream-reset",connectionId:e,streamId:n})},stream_send:(e,n,o,r)=>{const c=s.instance,i=new Uint8Array(c.exports.memory.buffer);o>>>=0,r>>>=0;const d=new Array;for(let e=0;e<r;++e){const n=a(i,o+8*e),t=a(i,o+8*e+4);d.push(i.slice(n,n+t))}t({ty:"stream-send",connectionId:e,streamId:n,data:d})},stream_send_close:(e,n)=>{t({ty:"stream-send-close",connectionId:e,streamId:n})},current_task_entered:(e,n)=>{e>>>=0,n>>>=0;const t=o(new Uint8Array(s.instance.exports.memory.buffer),e,n);s.currentTask=t},current_task_exit:()=>{s.currentTask=null}},l=yield WebAssembly.instantiate(n,{smoldot:d});s.instance=l,s.instance.exports.init(e.maxLogLevel);const u=new Promise((e=>s.onShutdownExecutorOrWasmPanic=()=>e("stop")));return(()=>{i(this,void 0,void 0,(function*(){const n=e.cpuRateLimit;let o=0,r=e.performanceNow();for(;;){const t=new Promise((e=>s.advanceExecutionPromise=()=>e("ready")));if(!s.instance)break;s.instance.exports.advance_execution();const a=e.performanceNow(),c=a-r;if(r=a,o+=c*(1/n-1),o>5){o>2147483646&&(o=2147483646);const e=new Promise((e=>setTimeout((()=>e("timeout")),o)));if("stop"===(yield Promise.race([e,u])))break}if("stop"===(yield Promise.race([t,u])))break;const i=e.performanceNow();o-=i-r,o<-1e4&&(o=-1e4),r=i}s.instance&&t({ty:"executor-shutdown"})}))})(),{request:(e,n)=>s.instance?(s.bufferIndices[0]=(new TextEncoder).encode(e),s.instance.exports.json_rpc_send(0,n)>>>0):1,peekJsonRpcResponse:e=>{if(!s.instance)return null;const n=new Uint8Array(s.instance.exports.memory.buffer),t=s.instance.exports.json_rpc_responses_peek(e)>>>0,r=a(n,t)>>>0,c=a(n,t+4)>>>0;if(0!==c){const t=o(n,r,c);return s.instance.exports.json_rpc_responses_pop(e),t}return null},addChain:(e,n,o,r,a,i)=>{if(!s.instance)return t({ty:"add-chain-id-allocated",chainId:0}),void t({ty:"add-chain-result",chainId:0,success:!1,error:"Smoldot has crashed"});console.assert(r||0!=a,"invalid jsonRpcMaxPendingRequests value passed to local-instance::addChain"),s.bufferIndices[0]=(new TextEncoder).encode(e),s.bufferIndices[1]=(new TextEncoder).encode(n);const d=new Uint8Array(4*o.length);for(let e=0;e<o.length;++e)l=d,u=4*e,f=o[e],c(l,u,4),l[u+3]=f>>>24&255,l[u+2]=f>>>16&255,l[u+1]=f>>>8&255,l[u]=255&f;var l,u,f;s.bufferIndices[2]=d;const p=s.instance.exports.add_chain(0,1,r?0:a,i,2);delete s.bufferIndices[0],delete s.bufferIndices[1],delete s.bufferIndices[2],t({ty:"add-chain-id-allocated",chainId:p})},removeChain:e=>{s.instance&&s.instance.exports.remove_chain(e)},shutdownExecutor:()=>{if(!s.instance)return;const e=s.onShutdownExecutorOrWasmPanic;s.onShutdownExecutorOrWasmPanic=()=>{},e()},connectionMultiStreamSetHandshakeInfo:(e,n)=>{if(!s.instance)return;const t=new Uint8Array(1+n.localTlsCertificateSha256.length);var o;c(o=t,0,1),o[0]=0,t.set(n.localTlsCertificateSha256,1),s.bufferIndices[0]=t,s.instance.exports.connection_multi_stream_set_handshake_info(e,0),delete s.bufferIndices[0]},connectionReset:(e,n)=>{s.instance&&(s.bufferIndices[0]=(new TextEncoder).encode(n),s.instance.exports.connection_reset(e,0),delete s.bufferIndices[0])},streamWritableBytes:(e,n,t)=>{s.instance&&s.instance.exports.stream_writable_bytes(e,t||0,n)},streamMessage:(e,n,t)=>{s.instance&&(s.bufferIndices[0]=n,s.instance.exports.stream_message(e,t||0,0),delete s.bufferIndices[0])},streamOpened:(e,n,t)=>{s.instance&&s.instance.exports.connection_stream_opened(e,n,"outbound"===t?1:0)},streamReset:(e,n,t)=>{s.instance&&(s.bufferIndices[0]=(new TextEncoder).encode(t),s.instance.exports.stream_reset(e,n,0),delete s.bufferIndices[0])}}}))}({forbidTcp:e.forbidTcp||!1,forbidWs:e.forbidWs||!1,forbidNonLocalWs:e.forbidNonLocalWs||!1,forbidWss:e.forbidWss||!1,forbidWebRtc:e.forbidWebRtc||!1,maxLogLevel:e.maxLogLevel||3,cpuRateLimit:f,envVars:[],performanceNow:t.performanceNow,getRandomValues:t.getRandomValues},n.wasm,h))).then((e=>{"destroyed"!==p.instance.status&&(p.instance={status:"ready",instance:e})}))},{addChain:e=>u(this,void 0,void 0,(function*(){if("not-ready"===p.instance.status&&(yield p.instance.whenReady),"destroyed"===p.instance.status)throw p.instance.error;if("not-created"===p.instance.status||"not-ready"===p.instance.status)throw new Error;if("string"!=typeof e.chainSpec)throw new Error("Chain specification must be a string");let n=[];if(e.potentialRelayChains)for(const t of e.potentialRelayChains){const e=p.chainIds.get(t);void 0!==e&&n.push(e)}let t=void 0===e.jsonRpcMaxPendingRequests?1/0:e.jsonRpcMaxPendingRequests;if(t=Math.floor(t),t<=0||isNaN(t))throw new s.dK("Invalid value for `jsonRpcMaxPendingRequests`");t>4294967295&&(t=4294967295);let o=void 0===e.jsonRpcMaxSubscriptions?1/0:e.jsonRpcMaxSubscriptions;if(o=Math.floor(o),o<0||isNaN(o))throw new s.dK("Invalid value for `jsonRpcMaxSubscriptions`");if(o>4294967295&&(o=4294967295),void 0!==e.databaseContent&&"string"!=typeof e.databaseContent)throw new s.dK("`databaseContent` is not a string");const r=new Promise((e=>p.addChainIdAllocations.push(e)));p.instance.instance.addChain(e.chainSpec,e.databaseContent||"",n,!!e.disableJsonRpc,t,o);const a=yield r;if(!a.success)throw new s.dK(a.error);const c=a.chainId;p.chains.set(c,{jsonRpcResponsesPromises:new Array});const i={sendJsonRpc:n=>{if("destroyed"===p.instance.status)throw p.instance.error;if("ready"!==p.instance.status)throw new Error;if(!p.chains.has(c))throw new s.m2;if(e.disableJsonRpc)throw new s.Ut;const t=p.instance.instance.request(n,c);switch(t){case 0:break;case 1:throw new s.Zm;default:throw new Error("Internal error: unknown json_rpc_send error code: "+t)}},nextJsonRpcResponse:()=>u(this,void 0,void 0,(function*(){for(;;){if(!p.chains.has(c))throw new s.m2;if(e.disableJsonRpc)return Promise.reject(new s.Ut);if("destroyed"===p.instance.status)throw p.instance.error;if("ready"!==p.instance.status)throw new Error;const n=p.instance.instance.peekJsonRpcResponse(c);if(n)return n;yield new Promise((e=>{p.chains.get(c).jsonRpcResponsesPromises.push(e)}))}})),remove:()=>{if("destroyed"===p.instance.status)throw p.instance.error;if("ready"!==p.instance.status)throw new Error;if(!p.chains.has(c))throw new s.m2;console.assert(p.chainIds.has(i)),p.chainIds.delete(i);for(const e of p.chains.get(c).jsonRpcResponsesPromises)e();p.chains.delete(c),p.instance.instance.removeChain(c)}};return p.chainIds.set(i,c),i})),terminate:()=>u(this,void 0,void 0,(function*(){if("not-ready"===p.instance.status&&(yield p.instance.whenReady),"destroyed"===p.instance.status)throw p.instance.error;if("ready"!==p.instance.status)throw new Error;p.instance.instance.shutdownExecutor(),yield new Promise((e=>p.onExecutorShutdownOrWasmPanic=e)),"ready"===p.instance.status&&(p.instance={status:"destroyed",error:new s.m2}),p.connections.forEach((e=>e.reset())),p.connections.clear();for(const e of p.addChainIdAllocations)e({success:!1,error:"Client.terminate() has been called"});p.addChainIdAllocations=[],p.addChainResults.forEach((e=>{e({success:!1,error:"Client.terminate() has been called"})})),p.addChainResults.clear();for(const e of Array.from(p.chains.values())){for(const n of e.jsonRpcResponsesPromises)n();e.jsonRpcResponsesPromises=[]}p.chains.clear()}))}}(e,e.bytecode,{performanceNow:()=>performance.now(),getRandomValues:e=>{const n=globalThis.crypto;if(!n)throw new Error("randomness not available");if(e.buffer instanceof ArrayBuffer)n.getRandomValues(e);else{const t=new Uint8Array(e.length);n.getRandomValues(t),e.set(t)}},connect:e=>function(e){if("websocket"===e.address.ty){let n;try{n=new WebSocket(e.address.url)}catch(e){n=e instanceof Error?e.toString():"Exception thrown by new WebSocket"}const t={quenedUnreportedBytes:0,nextTimeout:10},s=()=>{if(!(n instanceof WebSocket))return;if(1!=n.readyState)return;const o=n.bufferedAmount;let r=t.quenedUnreportedBytes-o;r<0&&(r=0),t.quenedUnreportedBytes-=r,0!=t.quenedUnreportedBytes&&(setTimeout(s,t.nextTimeout),t.nextTimeout*=2,t.nextTimeout>500&&(t.nextTimeout=500)),0!=r&&e.onWritableBytes(r)};return n instanceof WebSocket?(n.binaryType="arraybuffer",n.onopen=()=>{e.onWritableBytes(1048576)},n.onclose=n=>{const t="Error code "+n.code+(n.reason?": "+n.reason:"");e.onConnectionReset(t)},n.onmessage=n=>{e.onMessage(new Uint8Array(n.data))}):setTimeout((()=>{!n||n instanceof WebSocket||(e.onConnectionReset(n),n=null)}),1),{reset:()=>{n instanceof WebSocket&&(n.onopen=null,n.onclose=null,n.onmessage=null,n.onerror=null,n.readyState==WebSocket.OPEN&&n.close()),n=null},send:e=>{0==t.quenedUnreportedBytes&&(t.nextTimeout=10,setTimeout(s,10));for(const n of e)t.quenedUnreportedBytes+=n.length;n.send(new Blob(e))},closeSend:()=>{throw new Error("Wrong connection type")},openOutSubstream:()=>{throw new Error("Wrong connection type")}}}if("webrtc"===e.address.ty){const{targetPort:n,ipVersion:t,targetIp:s,remoteTlsCertificateSha256:o}=e.address,r={pc:void 0,dataChannels:new Map,nextStreamId:0,isFirstOutSubstream:!0},a=()=>{if(!r.pc)return console.assert(0===r.dataChannels.size,"substreams exist while pc is undef"),void(r.pc=null);r.pc.onconnectionstatechange=null,r.pc.onnegotiationneeded=null,r.pc.ondatachannel=null;for(const e of Array.from(r.dataChannels.values()))e.channel.onopen=null,e.channel.onerror=null,e.channel.onclose=null,e.channel.onbufferedamountlow=null,e.channel.onmessage=null;r.dataChannels.clear(),r.pc.close()},c=(n,t)=>{const s=r.nextStreamId;r.nextStreamId+=1,n.binaryType="arraybuffer";let o={value:!1};n.onopen=()=>{console.assert(!o.value,"substream opened twice"),o.value=!0,e.onStreamOpened(s,t),e.onWritableBytes(65536,s)},n.onerror=n.onclose=t=>{const c=t instanceof RTCErrorEvent?t.error.toString():"RTCDataChannel closed";o.value?(n.onopen=null,n.onerror=null,n.onclose=null,n.onbufferedamountlow=null,n.onmessage=null,r.dataChannels.delete(s),e.onStreamReset(s,c)):(a(),e.onConnectionReset("data channel failed to open: "+c))},n.onbufferedamountlow=()=>{const n=r.dataChannels.get(s),t=n.bufferedBytes;n.bufferedBytes=0,e.onWritableBytes(t,s)},n.onmessage=n=>{e.onMessage(new Uint8Array(n.data),s)},r.dataChannels.set(s,{channel:n,bufferedBytes:0})};return RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"}).then((i=>f(this,void 0,void 0,(function*(){if(null===r.pc)return;if(("localhost"==s||"127.0.0.1"==s||"::1"==s)&&-1!==navigator.userAgent.indexOf("Firefox"))return a(),void e.onConnectionReset("Firefox can't connect to a localhost WebRTC server");let d;if(r.pc=new RTCPeerConnection({certificates:[i]}),i.getFingerprints){for(const{algorithm:e,value:n}of i.getFingerprints())if("sha-256"===e){d=n;break}}else{const e=(yield r.pc.createOffer()).sdp.match(/a(\s*)=(\s*)fingerprint:(\s*)(sha|SHA)-256(\s*)(([a-fA-F0-9]{2}(:)*){32})/);e&&(d=e[6])}if(void 0===d)return void e.onConnectionReset("Failed to obtain the browser certificate fingerprint");let l=new Uint8Array(32);l.set(d.split(":").map((e=>parseInt(e,16))),0),r.pc.onconnectionstatechange=n=>{"closed"!=r.pc.connectionState&&"disconnected"!=r.pc.connectionState&&"failed"!=r.pc.connectionState||(a(),e.onConnectionReset("WebRTC state transitioned to "+r.pc.connectionState))},r.pc.onnegotiationneeded=e=>f(this,void 0,void 0,(function*(){var e;let a=(yield r.pc.createOffer()).sdp;null===a.match(/^m=application(\s+)(\d+)(\s+)UDP\/DTLS\/SCTP(\s+)webrtc-datachannel$/m)&&console.error("Local offer doesn't contain UDP data channel. WebRTC connections will likely fail. Please report this issue.");const c=null===(e=a.match(/^a=ice-pwd:(.+)$/m))||void 0===e?void 0:e.at(1);void 0===c&&console.error("Failed to set ufrag to pwd. WebRTC connections will likely fail. Please report this issue.");const i="libp2p+webrtc+v1/"+c;a=a.replace(/^a=ice-ufrag.*$/m,"a=ice-ufrag:"+i),a=a.replace(/^a=ice-pwd.*$/m,"a=ice-pwd:"+i),yield r.pc.setLocalDescription({type:"offer",sdp:a});const d=Array.from(o).map((e=>("0"+e.toString(16)).slice(-2).toUpperCase())).join(":"),l="v=0\no=- 0 0 IN IP"+t+" "+s+"\ns=-\nt=0 0\na=ice-lite\nm=application "+String(n)+" UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP"+t+" "+s+"\na=mid:0\na=ice-options:ice2\na=ice-ufrag:"+i+"\na=ice-pwd:"+i+"\na=fingerprint:sha-256 "+d+"\na=setup:passive\na=sctp-port:5000\na=max-message-size:16384\na=candidate:1 1 UDP 1 "+s+" "+String(n)+" typ host\n";yield r.pc.setRemoteDescription({type:"answer",sdp:l})})),r.pc.ondatachannel=({channel:e})=>{c(e,"inbound")},e.onMultistreamHandshakeInfo({handshake:"webrtc",localTlsCertificateSha256:l})})))),{reset:e=>{if(void 0===e)a();else{const n=r.dataChannels.get(e);n.channel.onopen=null,n.channel.onerror=null,n.channel.onclose=null,n.channel.onbufferedamountlow=null,n.channel.onmessage=null,n.channel.close(),r.dataChannels.delete(e)}},send:(e,n)=>{const t=r.dataChannels.get(n);for(const n of e)t.bufferedBytes+=n.length;t.channel.send(new Blob(e))},closeSend:()=>{throw new Error("Wrong connection type")},openOutSubstream:()=>{const e=r.isFirstOutSubstream?{negotiated:!0,id:0}:{};r.isFirstOutSubstream=!1,c(r.pc.createDataChannel("",e),"outbound")}}}throw new Error}(e)})}},51416:(e,n,t)=>{t.d(n,{Ut:()=>r,Zm:()=>c,dK:()=>s,id:()=>a,m2:()=>o});class s extends Error{constructor(e){super(e),this.name="AddChainError"}}class o extends Error{constructor(){super(),this.name="AlreadyDestroyedError"}}class r extends Error{constructor(){super(),this.name="JsonRpcDisabledError"}}class a extends Error{constructor(e){super(e)}}class c extends Error{constructor(){super("JSON-RPC requests queue is full")}}}}]);