toilscript 0.1.16 → 0.1.18

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.
package/dist/cli.js CHANGED
@@ -4,8 +4,8 @@
4
4
  * Copyright 2026 Daniel Wirtz / The ToilScript Authors
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- var se=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var fn=(e,t)=>()=>(e&&(t=e(e=0)),t);var nn=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},oe=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ue(t))!Me.call(e,s)&&s!==n&&se(e,s,{get:()=>t[s],enumerable:!(o=Ne(t,s))||o.enumerable});return e},Dn=(e,t,n)=>(oe(e,t,"default"),n&&oe(n,t,"default"));var le={};nn(le,{promises:()=>Pe});var Pe,ue=fn(()=>{"use strict";Pe={}});var fe={};nn(fe,{createRequire:()=>Ve});function Ve(){return function(t){throw new Error(`Cannot find module: '${t}'`)}}var ce=fn(()=>{"use strict"});var On={};nn(On,{argv:()=>He,cwd:()=>In,exit:()=>Xe,hrtime:()=>qe,platform:()=>je,umask:()=>Ge});function In(){return"."}function Ge(){return 0}function Xe(e=0){throw Error(`exit ${e}`)}function qe(e){var t=Ke.call(de),n=Math.floor(t*.001),o=Math.floor(t*1e6-n*1e9);return e&&(n-=e[0],o-=e[1],o<0&&(n--,o+=1e9)),[n,o]}var je,He,de,Ke,Ln=fn(()=>{"use strict";je="linux";He=[];de=globalThis.performance||{},Ke=de.now||function(){return new Date().getTime()}});var Rn={};nn(Rn,{basename:()=>Qe,delimiter:()=>it,dirname:()=>$e,extname:()=>nt,format:()=>et,isAbsolute:()=>Ye,join:()=>Je,normalize:()=>pe,parse:()=>tt,relative:()=>Ze,resolve:()=>cn,sep:()=>kn,win32:()=>rt});function V(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function xe(e,t){for(var n="",o=0,s=-1,r=0,u,f=0;f<=e.length;++f){if(f<e.length)u=e.charCodeAt(f);else{if(u===47)break;u=47}if(u===47){if(!(s===f-1||r===1))if(s!==f-1&&r===2){if(n.length<2||o!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var p=n.lastIndexOf("/");if(p!==n.length-1){p===-1?(n="",o=0):(n=n.slice(0,p),o=n.length-1-n.lastIndexOf("/")),s=f,r=0;continue}}else if(n.length===2||n.length===1){n="",o=0,s=f,r=0;continue}}t&&(n.length>0?n+="/..":n="..",o=2)}else n.length>0?n+="/"+e.slice(s+1,f):n=e.slice(s+1,f),o=f-s-1;s=f,r=0}else u===46&&r!==-1?++r:r=-1}return n}function We(e,t){var n=t.dir||t.root,o=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+o:n+e+o:o}function cn(){for(var e="",t=!1,n,o=arguments.length-1;o>=-1&&!t;o--){var s;o>=0?s=arguments[o]:(n===void 0&&(n=In()),s=n),V(s),s.length!==0&&(e=s+"/"+e,t=s.charCodeAt(0)===47)}return e=xe(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."}function pe(e){if(V(e),e.length===0)return".";var t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;return e=xe(e,!t),e.length===0&&!t&&(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e}function Ye(e){return V(e),e.length>0&&e.charCodeAt(0)===47}function Je(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var n=arguments[t];V(n),n.length>0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":pe(e)}function Ze(e,t){if(V(e),V(t),e===t||(e=cn(e),t=cn(t),e===t))return"";if(e===".")return t;for(var n=1;n<e.length&&e.charCodeAt(n)===47;++n);for(var o=e.length,s=o-n,r=1;r<t.length&&t.charCodeAt(r)===47;++r);for(var u=t.length,f=u-r,p=s<f?s:f,b=-1,d=0;d<=p;++d){if(d===p){if(f>p){if(t.charCodeAt(r+d)===47)return t.slice(r+d+1);if(d===0)return t.slice(r+d)}else s>p&&(e.charCodeAt(n+d)===47?b=d:d===0&&(b=0));break}var g=e.charCodeAt(n+d),y=t.charCodeAt(r+d);if(g!==y)break;g===47&&(b=d)}var m="";for(d=n+b+1;d<=o;++d)(d===o||e.charCodeAt(d)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(r+b):(r+=b,t.charCodeAt(r)===47&&++r,t.slice(r))}function $e(e){if(V(e),e.length===0)return".";for(var t=e.charCodeAt(0),n=t===47,o=-1,s=!0,r=e.length-1;r>=1;--r)if(t=e.charCodeAt(r),t===47){if(!s){o=r;break}}else s=!1;return o===-1?n?"/":".":n&&o===1?"//":e.slice(0,o)}function Qe(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');V(e);var n=0,o=-1,s=!0,r;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var u=t.length-1,f=-1;for(r=e.length-1;r>=0;--r){var p=e.charCodeAt(r);if(p===47){if(!s){n=r+1;break}}else f===-1&&(s=!1,f=r+1),u>=0&&(p===t.charCodeAt(u)?--u===-1&&(o=r):(u=-1,o=f))}return n===o?o=f:o===-1&&(o=e.length),e.slice(n,o)}else{for(r=e.length-1;r>=0;--r)if(e.charCodeAt(r)===47){if(!s){n=r+1;break}}else o===-1&&(s=!1,o=r+1);return o===-1?"":e.slice(n,o)}}function nt(e){V(e);for(var t=-1,n=0,o=-1,s=!0,r=0,u=e.length-1;u>=0;--u){var f=e.charCodeAt(u);if(f===47){if(!s){n=u+1;break}continue}o===-1&&(s=!1,o=u+1),f===46?t===-1?t=u:r!==1&&(r=1):t!==-1&&(r=-1)}return t===-1||o===-1||r===0||r===1&&t===o-1&&t===n+1?"":e.slice(t,o)}function et(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return We("/",e)}function tt(e){V(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var n=e.charCodeAt(0),o=n===47,s;o?(t.root="/",s=1):s=0;for(var r=-1,u=0,f=-1,p=!0,b=e.length-1,d=0;b>=s;--b){if(n=e.charCodeAt(b),n===47){if(!p){u=b+1;break}continue}f===-1&&(p=!1,f=b+1),n===46?r===-1?r=b:d!==1&&(d=1):r!==-1&&(d=-1)}return r===-1||f===-1||d===0||d===1&&r===f-1&&r===u+1?f!==-1&&(u===0&&o?t.base=t.name=e.slice(1,f):t.base=t.name=e.slice(u,f)):(u===0&&o?(t.name=e.slice(1,r),t.base=e.slice(1,f)):(t.name=e.slice(u,r),t.base=e.slice(u,f)),t.ext=e.slice(r,f)),u>0?t.dir=e.slice(0,u-1):o&&(t.dir="/"),t}var kn,it,rt,Nn=fn(()=>{"use strict";Ln();kn="/",it=":",rt=null});var he={};nn(he,{pathToFileURL:()=>ot});function at(e){return e.replace(/%/g,"%25").replace(/\\/g,"%5C").replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/\t/g,"%09")}function ot(e){let t=cn(e);e.charCodeAt(e.length-1)===47&&t[t.length-1]!==kn&&(t+="/");let n=new URL("file://");return n.pathname=at(t),n}var ge=fn(()=>{"use strict";Nn()});var Wn={};nn(Wn,{Stats:()=>Cn,checkDiagnostics:()=>gn,compileString:()=>wt,configToArguments:()=>qn,createMemoryStream:()=>Xn,default:()=>Wn,defaultOptimizeLevel:()=>Se,defaultShrinkLevel:()=>we,definitionFiles:()=>St,libraryFiles:()=>H,libraryPrefix:()=>P,main:()=>Be,options:()=>zt,tscOptions:()=>Bt,version:()=>Hn});var st=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",G,sn,v,M,dn;st?(G=await import("fs"),sn=await import("module"),v=await import("path"),M=globalThis.process,dn=await import("url")):(G=await Promise.resolve().then(()=>(ue(),le)),sn=await Promise.resolve().then(()=>(ce(),fe)),v=await Promise.resolve().then(()=>(Nn(),Rn)),M=await Promise.resolve().then(()=>(Ln(),On)),dn=await Promise.resolve().then(()=>(ge(),he)));var An=typeof process<"u"&&process||{},lt=An.env&&"CI"in An.env,ut="\x1B[90m",ft="\x1B[91m",ct="\x1B[92m",dt="\x1B[93m",xt="\x1B[94m",pt="\x1B[95m",ht="\x1B[96m",gt="\x1B[97m",W="\x1B[0m",en=class{constructor(t){this.stream=t,this.enabled=!!(this.stream&&this.stream.isTTY||lt)}gray(t){return this.enabled?ut+t+W:t}red(t){return this.enabled?ft+t+W:t}green(t){return this.enabled?ct+t+W:t}yellow(t){return this.enabled?dt+t+W:t}blue(t){return this.enabled?xt+t+W:t}magenta(t){return this.enabled?pt+t+W:t}cyan(t){return this.enabled?ht+t+W:t}white(t){return this.enabled?gt+t+W:t}},_n=new en(An.stdout),Ot=new en(An.stderr);function mt(e){for(var t=0,n=0,o=e.length;n<o;++n){let s=e.charCodeAt(n);s<128?t+=1:s<2048?t+=2:(s&64512)===55296&&n+1<o&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3}return t}function bt(e,t,n){var o=n-t;if(o<1)return"";for(var s=null,r=[],u=0,f;t<n;)f=e[t++],f<128?r[u++]=f:f>191&&f<224?r[u++]=(f&31)<<6|e[t++]&63:f>239&&f<365?(f=((f&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,r[u++]=55296+(f>>10),r[u++]=56320+(f&1023)):r[u++]=(f&15)<<12|(e[t++]&63)<<6|e[t++]&63,u>=8192&&((s||(s=[])).push(String.fromCharCode(...r)),u=0);return s?(u&&s.push(String.fromCharCode(...r.slice(0,u))),s.join("")):String.fromCharCode(...r.slice(0,u))}function yt(e,t,n){for(var o=n,s=0,r=e.length;s<r;++s){let u=e.charCodeAt(s),f;u<128?t[n++]=u:u<2048?(t[n++]=u>>6|192,t[n++]=u&63|128):(u&64512)===55296&&s+1<r&&((f=e.charCodeAt(s+1))&64512)===56320?(u=65536+((u&1023)<<10)+(f&1023),++s,t[n++]=u>>18|240,t[n++]=u>>12&63|128,t[n++]=u>>6&63|128,t[n++]=u&63|128):(t[n++]=u>>12|224,t[n++]=u>>6&63|128,t[n++]=u&63|128)}return n-o}var Tn={length:mt,read:bt,write:yt};var me=sn.createRequire(import.meta.url);function ye(e,t,n=!0){var o={},s=[],r=[],u=[],f={};Object.keys(t).forEach(d=>{if(!d.startsWith(" ")){var g=t[d];g.alias!=null&&(typeof g.alias=="string"?f[g.alias]=d:Array.isArray(g.alias)&&g.alias.forEach(y=>f[y]=d)),n&&g.default!=null&&(o[d]=g.default)}});for(var p=0,b=(e=e.slice()).length;p<b;++p){let d=e[p];if(d=="--"){++p;break}let g=/^(?:(-\w)(?:=(.*))?|(--\w{2,})(?:=(.*))?)$/.exec(d),y,m;if(g)t[d]?y=t[m=d]:g[1]!=null?(y=t[m=f[g[1].substring(1)]],y&&g[2]!=null&&(e[p--]=g[2])):g[3]!=null&&(y=t[m=g[3].substring(2)],y&&g[4]!=null&&(e[p--]=g[4]));else if(d.charCodeAt(0)==45)y=t[m=d];else{r.push(d);continue}if(y)if(y.value)Object.keys(y.value).forEach(i=>o[i]=y.value[i]);else if(y.type==null||y.type==="b")o[m]=!0;else if(p+1<e.length&&e[p+1].charCodeAt(0)!=45)switch(y.type){case"i":o[m]=parseInt(e[++p],10);break;case"I":o[m]=(o[m]||[]).concat(parseInt(e[++p],10));break;case"f":o[m]=parseFloat(e[++p]);break;case"F":o[m]=(o[m]||[]).concat(parseFloat(e[++p]));break;case"s":o[m]=String(e[++p]);break;case"S":o[m]=(o[m]||[]).concat(e[++p].split(","));break;default:s.push(d),--p}else switch(y.type){case"i":case"f":o[m]=y.default||0;break;case"s":o[m]=y.default||"";break;case"I":case"F":case"S":o[m]=y.default||[];break;default:s.push(d)}else s.push(d)}for(;p<b;)u.push(e[p++]);return n&&Mn(t,o),{options:o,unknown:s,arguments:r,trailing:u}}function Fe(e,t){t||(t={});var n=t.indent||2,o=t.padding||24,s=t.eol||`
8
- `,r={},u=[];Object.keys(e).forEach(b=>{var d=e[b];if(d.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,d.alias&&(g+=", -"+d.alias);g.length<o;)g+=" ";var y;!t.noCategories&&d.category?(y=r[d.category])||(r[d.category]=y=[]):y=u,Array.isArray(d.description)?y.push(g+d.description[0]+d.description.slice(1).map(m=>{for(let i=0;i<o;++i)m=" "+m;return s+m}).join("")):y.push(g+d.description)}});var f=[],p=!1;return Object.keys(r).forEach(b=>{p=!0,f.push(s+" "+_n.gray(b)+s),f.push(r[b].join(s))}),p&&u.length&&f.push(s+" "+_n.gray("Other")+s),f.push(u.join(s)),f.join(s)}function be(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Un(e,t,n,o){let s={};for(let[r,{type:u,mutuallyExclusive:f,isPath:p,useNodeResolution:b,cliOnly:d}]of Object.entries(e)){let g=be(t[r],u),y=be(n[r],u);if(g==null){if(y!=null){if(d)continue;if(Array.isArray(y)){let m;p&&(y=y.map(i=>tn(i,o,b))),f!=null&&(m=t[f])?s[r]=y.filter(i=>!m.includes(i)):s[r]=y.slice()}else p&&(y=tn(y,o,b)),s[r]=y}}else if(y==null)Array.isArray(g)?s[r]=g.slice():s[r]=g;else if(Array.isArray(g)){if(d){s[r]=g.slice();continue}let m;p&&(y=y.map(i=>tn(i,o,b))),f!=null&&(m=t[f])?s[r]=[...g,...y.filter(i=>!g.includes(i)&&!m.includes(i))]:s[r]=[...g,...y.filter(i=>!g.includes(i))]}else s[r]=g}return s}function Ft(e){let t=v.parse(e);return t.root||(t.root="./"),v.format(t)}function tn(e,t,n=!1){return v.isAbsolute(e)?e:n&&!e.startsWith(".")&&me.resolve?me.resolve(e,{paths:[t]}):Ft(v.join(t,e))}function Mn(e,t){for(let[n,{default:o}]of Object.entries(e))t[n]==null&&o!=null&&(t[n]=o)}var ve="0.1.16",Y={version:{category:"General",description:"Prints just the compiler's version and exits.",type:"b",alias:"v"},help:{category:"General",description:"Prints this message and exits.",type:"b",alias:"h"},config:{category:"General",description:"Configuration file to apply. CLI arguments take precedence.",type:"s",cliOnly:!0},target:{category:"General",description:"Configuration file target to use. Defaults to 'release'.",type:"s",cliOnly:!0},optimize:{category:"Optimization",description:["Optimizes the module. Typical shorthands are:",""," Default optimizations -O"," Make a release build -O --noAssert"," Make a debug build --debug"," Optimize for speed -Ospeed"," Optimize for size -Osize",""],type:"b",alias:"O"},optimizeLevel:{category:"Optimization",description:"How much to focus on optimizing code. [0-3]",type:"i"},shrinkLevel:{category:"Optimization",description:"How much to focus on shrinking code size. [0-2, s=1, z=2]",type:"i"},converge:{category:"Optimization",description:"Re-optimizes until no further improvements can be made.",type:"b",default:!1},noAssert:{category:"Optimization",description:"Replaces assertions with just their value without trapping.",type:"b",default:!1},outFile:{category:"Output",description:"Specifies the WebAssembly output file (.wasm).",type:"s",alias:"o",isPath:!0},textFile:{category:"Output",description:"Specifies the WebAssembly text output file (.wat).",type:"s",alias:"t",isPath:!0},rpcModule:{category:"Output",description:"Emits a .ts module: the @data codec + the typed client-callable Server surface.",type:"s",isPath:!0},rpcRuntime:{category:"Output",description:"Import specifier for the DataWriter/DataReader codec in the emitted RPC module.",type:"s",default:"toiljs/io"},bindings:{category:"Output",description:["Specifies the bindings to generate (.js + .d.ts).",""," esm JavaScript bindings & typings for ESM integration."," raw Like esm, but exports just the instantiate function."," Useful where modules are meant to be instantiated"," multiple times or non-ESM imports must be provided."],type:"S",alias:"b"},sourceMap:{category:"Debugging",description:["Enables source map generation. Optionally takes the URL","used to reference the source map from the binary file."],type:"s"},uncheckedBehavior:{category:"Debugging",description:["Changes the behavior of unchecked() expressions.","Using this option can potentially cause breakage.",""," default The default behavior: unchecked operations are"," only used inside of unchecked()."," never Unchecked operations are never used, even when"," inside of unchecked()."," always Unchecked operations are always used if possible,"," whether or not unchecked() is used."],type:"s",default:"default"},debug:{category:"Debugging",description:"Enables debug information in emitted binaries.",type:"b",default:!1},importMemory:{category:"Features",description:"Imports the memory from 'env.memory'.",type:"b",default:!1},noExportMemory:{category:"Features",description:"Does not export the memory as 'memory'.",type:"b",default:!1},initialMemory:{category:"Features",description:"Sets the initial memory size in pages.",type:"i",default:0},maximumMemory:{category:"Features",description:"Sets the maximum memory size in pages.",type:"i",default:0},sharedMemory:{category:"Features",description:"Declare memory as shared. Requires maximumMemory.",type:"b",default:!1},zeroFilledMemory:{category:"Features",description:"Assume imported memory is zeroed. Requires importMemory.",type:"b",default:!1},importTable:{category:"Features",description:"Imports the function table from 'env.table'.",type:"b",default:!1},exportTable:{category:"Features",description:"Exports the function table as 'table'.",type:"b",default:!1},exportStart:{category:"Features",description:["Exports the start function using the specified name instead","of calling it implicitly. Useful to obtain the exported memory","before executing any code accessing it."],type:"s"},runtime:{category:"Features",description:["Specifies the runtime variant to include in the program.",""," incremental TLSF + incremental GC (default)"," minimal TLSF + lightweight GC invoked externally"," stub Minimal runtime stub (never frees)"," ... Path to a custom runtime implementation",""],type:"s",default:"incremental"},exportRuntime:{category:"Features",description:["Always exports the runtime helpers (__new, __collect, __pin etc.).","Automatically determined when generation of --bindings is enabled."],type:"b",default:!1},stackSize:{category:"Features",description:["Overrides the stack size. Only relevant for incremental GC","or when using a custom runtime that requires stack space.","Defaults to 0 without and to 32768 with incremental GC."],default:0,type:"i"},enable:{category:"Features",description:["Enables WebAssembly features being disabled by default.",""," threads Threading and atomic operations."," simd SIMD types and operations."," reference-types Reference types and operations."," gc Garbage collection (WIP)."," stringref String reference types."," relaxed-simd Relaxed SIMD operations.",""],TODO_doesNothingYet:[" exception-handling Exception handling."," tail-calls Tail call operations."," multi-value Multi value types."," memory64 Memory64 operations."," extended-const Extended const expressions."],type:"S",mutuallyExclusive:"disable"},disable:{category:"Features",description:["Disables WebAssembly features being enabled by default.",""," mutable-globals Mutable global imports and exports."," sign-extension Sign-extension operations"," nontrapping-f2i Non-trapping float to integer ops."," bulk-memory Bulk memory operations.",""],type:"S",mutuallyExclusive:"enable"},use:{category:"Features",description:["Aliases a global object under another name, e.g., to switch","the default 'Math' implementation used: --use Math=JSMath","Can also be used to introduce an integer constant."],type:"S",alias:"u"},lowMemoryLimit:{category:"Features",description:"Enforces very low (<64k) memory constraints.",default:0,type:"i"},memoryBase:{category:"Linking",description:"Sets the start offset of emitted memory segments.",type:"i",default:0},tableBase:{category:"Linking",description:"Sets the start offset of emitted table elements.",type:"i",default:0},transform:{category:"API",description:"Specifies the path to a custom transform to load.",type:"S",isPath:!0,useNodeResolution:!0},trapMode:{category:"Binaryen",description:["Sets the trap mode to use.",""," allow Allow trapping operations. This is the default."," clamp Replace trapping operations with clamping semantics."," js Replace trapping operations with JS semantics.",""],type:"s",default:"allow"},runPasses:{category:"Binaryen",description:["Specifies additional Binaryen passes to run after other","optimizations, if any. See: Binaryen/src/passes/pass.cpp"],type:"s"},noValidate:{category:"Binaryen",description:"Skips validating the module using Binaryen.",type:"b",default:!1},baseDir:{description:"Specifies the base directory of input and output files.",type:"s",default:"."},noColors:{description:"Disables terminal colors.",type:"b",default:!1},noUnsafe:{description:["Disallows the use of unsafe features in user code.","Does not affect library files and external modules."],type:"b",default:!1},disableWarning:{description:["Disables warnings matching the given diagnostic code.","If no diagnostic code is given, all warnings are disabled."],type:"I"},noEmit:{description:"Performs compilation as usual but does not emit code.",type:"b",default:!1},showConfig:{description:"Print computed compiler options and exit.",type:"b",default:!1},stats:{description:"Prints statistics on I/O and compile times.",type:"b",default:!1},pedantic:{description:"Make yourself sad for no good reason.",type:"b",default:!1},lib:{description:["Adds one or multiple paths to custom library components and","uses exports of all top-level files at this path as globals."],type:"S",isPath:!0},path:{description:["Adds one or multiple paths to package resolution, similar","to node_modules. Prefers an 'ascMain' entry in a package's","package.json and falls back to an inner 'assembly/' folder."],type:"S",isPath:!0},wasm:{description:"Uses the specified Wasm binary of the compiler.",type:"s"}," ...":{description:"Specifies node.js options (CLI only). See: node --help"},"-Os":{value:{optimizeLevel:0,shrinkLevel:1}},"-Oz":{value:{optimizeLevel:0,shrinkLevel:2}},"-O0":{value:{optimizeLevel:0,shrinkLevel:0}},"-O1":{value:{optimizeLevel:1,shrinkLevel:0}},"-O2":{value:{optimizeLevel:2,shrinkLevel:0}},"-O3":{value:{optimizeLevel:3,shrinkLevel:0}},"-O0s":{value:{optimizeLevel:0,shrinkLevel:1}},"-O1s":{value:{optimizeLevel:1,shrinkLevel:1}},"-O2s":{value:{optimizeLevel:2,shrinkLevel:1}},"-O3s":{value:{optimizeLevel:3,shrinkLevel:1}},"-O0z":{value:{optimizeLevel:0,shrinkLevel:2}},"-O1z":{value:{optimizeLevel:1,shrinkLevel:2}},"-O2z":{value:{optimizeLevel:2,shrinkLevel:2}},"-O3z":{value:{optimizeLevel:3,shrinkLevel:2}},"-Ospeed":{value:{optimizeLevel:3,shrinkLevel:0}},"-Osize":{value:{optimizeLevel:0,shrinkLevel:2,converge:!0}},"--measure":{value:{stats:!0}}},Ee="~lib/",Ae={array:`/// <reference path="./rt/index.d.ts" />
7
+ var se=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var fn=(e,t)=>()=>(e&&(t=e(e=0)),t);var nn=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},oe=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ue(t))!Me.call(e,s)&&s!==n&&se(e,s,{get:()=>t[s],enumerable:!(o=Ne(t,s))||o.enumerable});return e},Dn=(e,t,n)=>(oe(e,t,"default"),n&&oe(n,t,"default"));var le={};nn(le,{promises:()=>Pe});var Pe,ue=fn(()=>{"use strict";Pe={}});var fe={};nn(fe,{createRequire:()=>Ve});function Ve(){return function(t){throw new Error(`Cannot find module: '${t}'`)}}var ce=fn(()=>{"use strict"});var On={};nn(On,{argv:()=>He,cwd:()=>In,exit:()=>Ke,hrtime:()=>qe,platform:()=>Ge,umask:()=>je});function In(){return"."}function je(){return 0}function Ke(e=0){throw Error(`exit ${e}`)}function qe(e){var t=Xe.call(de),n=Math.floor(t*.001),o=Math.floor(t*1e6-n*1e9);return e&&(n-=e[0],o-=e[1],o<0&&(n--,o+=1e9)),[n,o]}var Ge,He,de,Xe,Ln=fn(()=>{"use strict";Ge="linux";He=[];de=globalThis.performance||{},Xe=de.now||function(){return new Date().getTime()}});var Rn={};nn(Rn,{basename:()=>Qe,delimiter:()=>it,dirname:()=>$e,extname:()=>nt,format:()=>et,isAbsolute:()=>Ye,join:()=>Je,normalize:()=>xe,parse:()=>tt,relative:()=>Ze,resolve:()=>cn,sep:()=>kn,win32:()=>rt});function V(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function pe(e,t){for(var n="",o=0,s=-1,r=0,u,f=0;f<=e.length;++f){if(f<e.length)u=e.charCodeAt(f);else{if(u===47)break;u=47}if(u===47){if(!(s===f-1||r===1))if(s!==f-1&&r===2){if(n.length<2||o!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var x=n.lastIndexOf("/");if(x!==n.length-1){x===-1?(n="",o=0):(n=n.slice(0,x),o=n.length-1-n.lastIndexOf("/")),s=f,r=0;continue}}else if(n.length===2||n.length===1){n="",o=0,s=f,r=0;continue}}t&&(n.length>0?n+="/..":n="..",o=2)}else n.length>0?n+="/"+e.slice(s+1,f):n=e.slice(s+1,f),o=f-s-1;s=f,r=0}else u===46&&r!==-1?++r:r=-1}return n}function We(e,t){var n=t.dir||t.root,o=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+o:n+e+o:o}function cn(){for(var e="",t=!1,n,o=arguments.length-1;o>=-1&&!t;o--){var s;o>=0?s=arguments[o]:(n===void 0&&(n=In()),s=n),V(s),s.length!==0&&(e=s+"/"+e,t=s.charCodeAt(0)===47)}return e=pe(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."}function xe(e){if(V(e),e.length===0)return".";var t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;return e=pe(e,!t),e.length===0&&!t&&(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e}function Ye(e){return V(e),e.length>0&&e.charCodeAt(0)===47}function Je(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var n=arguments[t];V(n),n.length>0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":xe(e)}function Ze(e,t){if(V(e),V(t),e===t||(e=cn(e),t=cn(t),e===t))return"";if(e===".")return t;for(var n=1;n<e.length&&e.charCodeAt(n)===47;++n);for(var o=e.length,s=o-n,r=1;r<t.length&&t.charCodeAt(r)===47;++r);for(var u=t.length,f=u-r,x=s<f?s:f,b=-1,d=0;d<=x;++d){if(d===x){if(f>x){if(t.charCodeAt(r+d)===47)return t.slice(r+d+1);if(d===0)return t.slice(r+d)}else s>x&&(e.charCodeAt(n+d)===47?b=d:d===0&&(b=0));break}var g=e.charCodeAt(n+d),y=t.charCodeAt(r+d);if(g!==y)break;g===47&&(b=d)}var m="";for(d=n+b+1;d<=o;++d)(d===o||e.charCodeAt(d)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(r+b):(r+=b,t.charCodeAt(r)===47&&++r,t.slice(r))}function $e(e){if(V(e),e.length===0)return".";for(var t=e.charCodeAt(0),n=t===47,o=-1,s=!0,r=e.length-1;r>=1;--r)if(t=e.charCodeAt(r),t===47){if(!s){o=r;break}}else s=!1;return o===-1?n?"/":".":n&&o===1?"//":e.slice(0,o)}function Qe(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');V(e);var n=0,o=-1,s=!0,r;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var u=t.length-1,f=-1;for(r=e.length-1;r>=0;--r){var x=e.charCodeAt(r);if(x===47){if(!s){n=r+1;break}}else f===-1&&(s=!1,f=r+1),u>=0&&(x===t.charCodeAt(u)?--u===-1&&(o=r):(u=-1,o=f))}return n===o?o=f:o===-1&&(o=e.length),e.slice(n,o)}else{for(r=e.length-1;r>=0;--r)if(e.charCodeAt(r)===47){if(!s){n=r+1;break}}else o===-1&&(s=!1,o=r+1);return o===-1?"":e.slice(n,o)}}function nt(e){V(e);for(var t=-1,n=0,o=-1,s=!0,r=0,u=e.length-1;u>=0;--u){var f=e.charCodeAt(u);if(f===47){if(!s){n=u+1;break}continue}o===-1&&(s=!1,o=u+1),f===46?t===-1?t=u:r!==1&&(r=1):t!==-1&&(r=-1)}return t===-1||o===-1||r===0||r===1&&t===o-1&&t===n+1?"":e.slice(t,o)}function et(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return We("/",e)}function tt(e){V(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var n=e.charCodeAt(0),o=n===47,s;o?(t.root="/",s=1):s=0;for(var r=-1,u=0,f=-1,x=!0,b=e.length-1,d=0;b>=s;--b){if(n=e.charCodeAt(b),n===47){if(!x){u=b+1;break}continue}f===-1&&(x=!1,f=b+1),n===46?r===-1?r=b:d!==1&&(d=1):r!==-1&&(d=-1)}return r===-1||f===-1||d===0||d===1&&r===f-1&&r===u+1?f!==-1&&(u===0&&o?t.base=t.name=e.slice(1,f):t.base=t.name=e.slice(u,f)):(u===0&&o?(t.name=e.slice(1,r),t.base=e.slice(1,f)):(t.name=e.slice(u,r),t.base=e.slice(u,f)),t.ext=e.slice(r,f)),u>0?t.dir=e.slice(0,u-1):o&&(t.dir="/"),t}var kn,it,rt,Nn=fn(()=>{"use strict";Ln();kn="/",it=":",rt=null});var he={};nn(he,{pathToFileURL:()=>ot});function at(e){return e.replace(/%/g,"%25").replace(/\\/g,"%5C").replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/\t/g,"%09")}function ot(e){let t=cn(e);e.charCodeAt(e.length-1)===47&&t[t.length-1]!==kn&&(t+="/");let n=new URL("file://");return n.pathname=at(t),n}var ge=fn(()=>{"use strict";Nn()});var Wn={};nn(Wn,{Stats:()=>Cn,checkDiagnostics:()=>gn,compileString:()=>wt,configToArguments:()=>qn,createMemoryStream:()=>Kn,default:()=>Wn,defaultOptimizeLevel:()=>Se,defaultShrinkLevel:()=>we,definitionFiles:()=>St,libraryFiles:()=>H,libraryPrefix:()=>P,main:()=>Be,options:()=>zt,tscOptions:()=>Bt,version:()=>Hn});var st=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",j,sn,F,M,dn;st?(j=await import("fs"),sn=await import("module"),F=await import("path"),M=globalThis.process,dn=await import("url")):(j=await Promise.resolve().then(()=>(ue(),le)),sn=await Promise.resolve().then(()=>(ce(),fe)),F=await Promise.resolve().then(()=>(Nn(),Rn)),M=await Promise.resolve().then(()=>(Ln(),On)),dn=await Promise.resolve().then(()=>(ge(),he)));var An=typeof process<"u"&&process||{},lt=An.env&&"CI"in An.env,ut="\x1B[90m",ft="\x1B[91m",ct="\x1B[92m",dt="\x1B[93m",pt="\x1B[94m",xt="\x1B[95m",ht="\x1B[96m",gt="\x1B[97m",W="\x1B[0m",en=class{constructor(t){this.stream=t,this.enabled=!!(this.stream&&this.stream.isTTY||lt)}gray(t){return this.enabled?ut+t+W:t}red(t){return this.enabled?ft+t+W:t}green(t){return this.enabled?ct+t+W:t}yellow(t){return this.enabled?dt+t+W:t}blue(t){return this.enabled?pt+t+W:t}magenta(t){return this.enabled?xt+t+W:t}cyan(t){return this.enabled?ht+t+W:t}white(t){return this.enabled?gt+t+W:t}},_n=new en(An.stdout),Ot=new en(An.stderr);function mt(e){for(var t=0,n=0,o=e.length;n<o;++n){let s=e.charCodeAt(n);s<128?t+=1:s<2048?t+=2:(s&64512)===55296&&n+1<o&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3}return t}function bt(e,t,n){var o=n-t;if(o<1)return"";for(var s=null,r=[],u=0,f;t<n;)f=e[t++],f<128?r[u++]=f:f>191&&f<224?r[u++]=(f&31)<<6|e[t++]&63:f>239&&f<365?(f=((f&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,r[u++]=55296+(f>>10),r[u++]=56320+(f&1023)):r[u++]=(f&15)<<12|(e[t++]&63)<<6|e[t++]&63,u>=8192&&((s||(s=[])).push(String.fromCharCode(...r)),u=0);return s?(u&&s.push(String.fromCharCode(...r.slice(0,u))),s.join("")):String.fromCharCode(...r.slice(0,u))}function yt(e,t,n){for(var o=n,s=0,r=e.length;s<r;++s){let u=e.charCodeAt(s),f;u<128?t[n++]=u:u<2048?(t[n++]=u>>6|192,t[n++]=u&63|128):(u&64512)===55296&&s+1<r&&((f=e.charCodeAt(s+1))&64512)===56320?(u=65536+((u&1023)<<10)+(f&1023),++s,t[n++]=u>>18|240,t[n++]=u>>12&63|128,t[n++]=u>>6&63|128,t[n++]=u&63|128):(t[n++]=u>>12|224,t[n++]=u>>6&63|128,t[n++]=u&63|128)}return n-o}var Tn={length:mt,read:bt,write:yt};var me=sn.createRequire(import.meta.url);function ye(e,t,n=!0){var o={},s=[],r=[],u=[],f={};Object.keys(t).forEach(d=>{if(!d.startsWith(" ")){var g=t[d];g.alias!=null&&(typeof g.alias=="string"?f[g.alias]=d:Array.isArray(g.alias)&&g.alias.forEach(y=>f[y]=d)),n&&g.default!=null&&(o[d]=g.default)}});for(var x=0,b=(e=e.slice()).length;x<b;++x){let d=e[x];if(d=="--"){++x;break}let g=/^(?:(-\w)(?:=(.*))?|(--\w{2,})(?:=(.*))?)$/.exec(d),y,m;if(g)t[d]?y=t[m=d]:g[1]!=null?(y=t[m=f[g[1].substring(1)]],y&&g[2]!=null&&(e[x--]=g[2])):g[3]!=null&&(y=t[m=g[3].substring(2)],y&&g[4]!=null&&(e[x--]=g[4]));else if(d.charCodeAt(0)==45)y=t[m=d];else{r.push(d);continue}if(y)if(y.value)Object.keys(y.value).forEach(i=>o[i]=y.value[i]);else if(y.type==null||y.type==="b")o[m]=!0;else if(x+1<e.length&&e[x+1].charCodeAt(0)!=45)switch(y.type){case"i":o[m]=parseInt(e[++x],10);break;case"I":o[m]=(o[m]||[]).concat(parseInt(e[++x],10));break;case"f":o[m]=parseFloat(e[++x]);break;case"F":o[m]=(o[m]||[]).concat(parseFloat(e[++x]));break;case"s":o[m]=String(e[++x]);break;case"S":o[m]=(o[m]||[]).concat(e[++x].split(","));break;default:s.push(d),--x}else switch(y.type){case"i":case"f":o[m]=y.default||0;break;case"s":o[m]=y.default||"";break;case"I":case"F":case"S":o[m]=y.default||[];break;default:s.push(d)}else s.push(d)}for(;x<b;)u.push(e[x++]);return n&&Mn(t,o),{options:o,unknown:s,arguments:r,trailing:u}}function ve(e,t){t||(t={});var n=t.indent||2,o=t.padding||24,s=t.eol||`
8
+ `,r={},u=[];Object.keys(e).forEach(b=>{var d=e[b];if(d.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,d.alias&&(g+=", -"+d.alias);g.length<o;)g+=" ";var y;!t.noCategories&&d.category?(y=r[d.category])||(r[d.category]=y=[]):y=u,Array.isArray(d.description)?y.push(g+d.description[0]+d.description.slice(1).map(m=>{for(let i=0;i<o;++i)m=" "+m;return s+m}).join("")):y.push(g+d.description)}});var f=[],x=!1;return Object.keys(r).forEach(b=>{x=!0,f.push(s+" "+_n.gray(b)+s),f.push(r[b].join(s))}),x&&u.length&&f.push(s+" "+_n.gray("Other")+s),f.push(u.join(s)),f.join(s)}function be(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Un(e,t,n,o){let s={};for(let[r,{type:u,mutuallyExclusive:f,isPath:x,useNodeResolution:b,cliOnly:d}]of Object.entries(e)){let g=be(t[r],u),y=be(n[r],u);if(g==null){if(y!=null){if(d)continue;if(Array.isArray(y)){let m;x&&(y=y.map(i=>tn(i,o,b))),f!=null&&(m=t[f])?s[r]=y.filter(i=>!m.includes(i)):s[r]=y.slice()}else x&&(y=tn(y,o,b)),s[r]=y}}else if(y==null)Array.isArray(g)?s[r]=g.slice():s[r]=g;else if(Array.isArray(g)){if(d){s[r]=g.slice();continue}let m;x&&(y=y.map(i=>tn(i,o,b))),f!=null&&(m=t[f])?s[r]=[...g,...y.filter(i=>!g.includes(i)&&!m.includes(i))]:s[r]=[...g,...y.filter(i=>!g.includes(i))]}else s[r]=g}return s}function vt(e){let t=F.parse(e);return t.root||(t.root="./"),F.format(t)}function tn(e,t,n=!1){return F.isAbsolute(e)?e:n&&!e.startsWith(".")&&me.resolve?me.resolve(e,{paths:[t]}):vt(F.join(t,e))}function Mn(e,t){for(let[n,{default:o}]of Object.entries(e))t[n]==null&&o!=null&&(t[n]=o)}var Fe="0.1.18",Y={version:{category:"General",description:"Prints just the compiler's version and exits.",type:"b",alias:"v"},help:{category:"General",description:"Prints this message and exits.",type:"b",alias:"h"},config:{category:"General",description:"Configuration file to apply. CLI arguments take precedence.",type:"s",cliOnly:!0},target:{category:"General",description:"Configuration file target to use. Defaults to 'release'.",type:"s",cliOnly:!0},optimize:{category:"Optimization",description:["Optimizes the module. Typical shorthands are:",""," Default optimizations -O"," Make a release build -O --noAssert"," Make a debug build --debug"," Optimize for speed -Ospeed"," Optimize for size -Osize",""],type:"b",alias:"O"},optimizeLevel:{category:"Optimization",description:"How much to focus on optimizing code. [0-3]",type:"i"},shrinkLevel:{category:"Optimization",description:"How much to focus on shrinking code size. [0-2, s=1, z=2]",type:"i"},converge:{category:"Optimization",description:"Re-optimizes until no further improvements can be made.",type:"b",default:!1},noAssert:{category:"Optimization",description:"Replaces assertions with just their value without trapping.",type:"b",default:!1},outFile:{category:"Output",description:"Specifies the WebAssembly output file (.wasm).",type:"s",alias:"o",isPath:!0},textFile:{category:"Output",description:"Specifies the WebAssembly text output file (.wat).",type:"s",alias:"t",isPath:!0},rpcModule:{category:"Output",description:"Emits a .ts module: the @data codec + the typed client-callable Server surface.",type:"s",isPath:!0},rpcRuntime:{category:"Output",description:"Import specifier for the DataWriter/DataReader codec in the emitted RPC module.",type:"s",default:"toiljs/io"},bindings:{category:"Output",description:["Specifies the bindings to generate (.js + .d.ts).",""," esm JavaScript bindings & typings for ESM integration."," raw Like esm, but exports just the instantiate function."," Useful where modules are meant to be instantiated"," multiple times or non-ESM imports must be provided."],type:"S",alias:"b"},sourceMap:{category:"Debugging",description:["Enables source map generation. Optionally takes the URL","used to reference the source map from the binary file."],type:"s"},uncheckedBehavior:{category:"Debugging",description:["Changes the behavior of unchecked() expressions.","Using this option can potentially cause breakage.",""," default The default behavior: unchecked operations are"," only used inside of unchecked()."," never Unchecked operations are never used, even when"," inside of unchecked()."," always Unchecked operations are always used if possible,"," whether or not unchecked() is used."],type:"s",default:"default"},debug:{category:"Debugging",description:"Enables debug information in emitted binaries.",type:"b",default:!1},importMemory:{category:"Features",description:"Imports the memory from 'env.memory'.",type:"b",default:!1},noExportMemory:{category:"Features",description:"Does not export the memory as 'memory'.",type:"b",default:!1},initialMemory:{category:"Features",description:"Sets the initial memory size in pages.",type:"i",default:0},maximumMemory:{category:"Features",description:"Sets the maximum memory size in pages.",type:"i",default:0},sharedMemory:{category:"Features",description:"Declare memory as shared. Requires maximumMemory.",type:"b",default:!1},zeroFilledMemory:{category:"Features",description:"Assume imported memory is zeroed. Requires importMemory.",type:"b",default:!1},importTable:{category:"Features",description:"Imports the function table from 'env.table'.",type:"b",default:!1},exportTable:{category:"Features",description:"Exports the function table as 'table'.",type:"b",default:!1},exportStart:{category:"Features",description:["Exports the start function using the specified name instead","of calling it implicitly. Useful to obtain the exported memory","before executing any code accessing it."],type:"s"},runtime:{category:"Features",description:["Specifies the runtime variant to include in the program.",""," incremental TLSF + incremental GC (default)"," minimal TLSF + lightweight GC invoked externally"," stub Minimal runtime stub (never frees)"," ... Path to a custom runtime implementation",""],type:"s",default:"incremental"},exportRuntime:{category:"Features",description:["Always exports the runtime helpers (__new, __collect, __pin etc.).","Automatically determined when generation of --bindings is enabled."],type:"b",default:!1},stackSize:{category:"Features",description:["Overrides the stack size. Only relevant for incremental GC","or when using a custom runtime that requires stack space.","Defaults to 0 without and to 32768 with incremental GC."],default:0,type:"i"},enable:{category:"Features",description:["Enables WebAssembly features being disabled by default.",""," threads Threading and atomic operations."," simd SIMD types and operations."," reference-types Reference types and operations."," gc Garbage collection (WIP)."," stringref String reference types."," relaxed-simd Relaxed SIMD operations.",""],TODO_doesNothingYet:[" exception-handling Exception handling."," tail-calls Tail call operations."," multi-value Multi value types."," memory64 Memory64 operations."," extended-const Extended const expressions."],type:"S",mutuallyExclusive:"disable"},disable:{category:"Features",description:["Disables WebAssembly features being enabled by default.",""," mutable-globals Mutable global imports and exports."," sign-extension Sign-extension operations"," nontrapping-f2i Non-trapping float to integer ops."," bulk-memory Bulk memory operations.",""],type:"S",mutuallyExclusive:"enable"},use:{category:"Features",description:["Aliases a global object under another name, e.g., to switch","the default 'Math' implementation used: --use Math=JSMath","Can also be used to introduce an integer constant."],type:"S",alias:"u"},lowMemoryLimit:{category:"Features",description:"Enforces very low (<64k) memory constraints.",default:0,type:"i"},memoryBase:{category:"Linking",description:"Sets the start offset of emitted memory segments.",type:"i",default:0},tableBase:{category:"Linking",description:"Sets the start offset of emitted table elements.",type:"i",default:0},transform:{category:"API",description:"Specifies the path to a custom transform to load.",type:"S",isPath:!0,useNodeResolution:!0},trapMode:{category:"Binaryen",description:["Sets the trap mode to use.",""," allow Allow trapping operations. This is the default."," clamp Replace trapping operations with clamping semantics."," js Replace trapping operations with JS semantics.",""],type:"s",default:"allow"},runPasses:{category:"Binaryen",description:["Specifies additional Binaryen passes to run after other","optimizations, if any. See: Binaryen/src/passes/pass.cpp"],type:"s"},noValidate:{category:"Binaryen",description:"Skips validating the module using Binaryen.",type:"b",default:!1},baseDir:{description:"Specifies the base directory of input and output files.",type:"s",default:"."},noColors:{description:"Disables terminal colors.",type:"b",default:!1},noUnsafe:{description:["Disallows the use of unsafe features in user code.","Does not affect library files and external modules."],type:"b",default:!1},disableWarning:{description:["Disables warnings matching the given diagnostic code.","If no diagnostic code is given, all warnings are disabled."],type:"I"},noEmit:{description:"Performs compilation as usual but does not emit code.",type:"b",default:!1},showConfig:{description:"Print computed compiler options and exit.",type:"b",default:!1},stats:{description:"Prints statistics on I/O and compile times.",type:"b",default:!1},pedantic:{description:"Make yourself sad for no good reason.",type:"b",default:!1},lib:{description:["Adds one or multiple paths to custom library components and","uses exports of all top-level files at this path as globals."],type:"S",isPath:!0},path:{description:["Adds one or multiple paths to package resolution, similar","to node_modules. Prefers an 'ascMain' entry in a package's","package.json and falls back to an inner 'assembly/' folder."],type:"S",isPath:!0},wasm:{description:"Uses the specified Wasm binary of the compiler.",type:"s"}," ...":{description:"Specifies node.js options (CLI only). See: node --help"},"-Os":{value:{optimizeLevel:0,shrinkLevel:1}},"-Oz":{value:{optimizeLevel:0,shrinkLevel:2}},"-O0":{value:{optimizeLevel:0,shrinkLevel:0}},"-O1":{value:{optimizeLevel:1,shrinkLevel:0}},"-O2":{value:{optimizeLevel:2,shrinkLevel:0}},"-O3":{value:{optimizeLevel:3,shrinkLevel:0}},"-O0s":{value:{optimizeLevel:0,shrinkLevel:1}},"-O1s":{value:{optimizeLevel:1,shrinkLevel:1}},"-O2s":{value:{optimizeLevel:2,shrinkLevel:1}},"-O3s":{value:{optimizeLevel:3,shrinkLevel:1}},"-O0z":{value:{optimizeLevel:0,shrinkLevel:2}},"-O1z":{value:{optimizeLevel:1,shrinkLevel:2}},"-O2z":{value:{optimizeLevel:2,shrinkLevel:2}},"-O3z":{value:{optimizeLevel:3,shrinkLevel:2}},"-Ospeed":{value:{optimizeLevel:3,shrinkLevel:0}},"-Osize":{value:{optimizeLevel:0,shrinkLevel:2,converge:!0}},"--measure":{value:{stats:!0}}},Ee="~lib/",Ae={array:`/// <reference path="./rt/index.d.ts" />
9
9
 
10
10
  import { BLOCK_MAXSIZE } from "./rt/common";
11
11
  import { Runtime } from "shared/runtime";
@@ -4532,21 +4532,120 @@ export declare namespace performance {
4532
4532
  export function now(): f64;
4533
4533
  }
4534
4534
 
4535
- export namespace crypto {
4536
- export function getRandomValues(array: Uint8Array): void {
4537
- let values = getRandomValuesN(array.length);
4538
- array.set(values);
4539
- }
4540
- @external("env", "crypto.getRandomValuesN")
4541
- @external.js("let a = new Uint8Array(n); crypto.getRandomValues(a); return a;")
4542
- export declare function getRandomValuesN(n: u32): Uint8Array;
4543
- }
4535
+ // crypto.getRandomValues moved to the dedicated Web Crypto module
4536
+ // (std/assembly/crypto.ts), backed by the \`crypto.fill_random\` host import.
4544
4537
  `,"bindings/node":`export declare namespace process {
4545
4538
  @external("env", "process.argv")
4546
4539
  export const argv: string[];
4547
4540
  @external("env", "process.exit")
4548
4541
  export function exit(code: i32): void;
4549
4542
  }
4543
+ `,"bindings/webcrypto":`// Host-import declarations for the Web Crypto surface. The production edge
4544
+ // (toil-backend \`src/wasm/host/import_functions/crypto\`) and the toiljs dev
4545
+ // server both provide these under the \`env\` namespace. All byte regions are
4546
+ // passed as a (pointer, length) pair into guest linear memory.
4547
+ //
4548
+ // Variable-length results use a two-step pull: the op returns the result
4549
+ // length (>= 0) or a negative error code; the guest then allocates a buffer of
4550
+ // that length and calls \`take_result\` to copy the bytes out.
4551
+ //
4552
+ // This is the guest half of the ABI contract in \`crypto/algorithms.ts\`; the
4553
+ // byte layout of the packed params buffer is defined there.
4554
+
4555
+ export namespace webcrypto {
4556
+ // CSPRNG: fill outPtr..outPtr+len with random bytes.
4557
+ // @ts-ignore: decorator
4558
+ @external("env", "crypto.fill_random")
4559
+ export declare function fillRandom(outPtr: usize, len: i32): void;
4560
+
4561
+ // Write 16 random bytes to outPtr (guest applies RFC 4122 v4 bits + format).
4562
+ // @ts-ignore: decorator
4563
+ @external("env", "crypto.random_uuid")
4564
+ export declare function randomUuid(outPtr: usize): void;
4565
+
4566
+ // Copy the last stashed variable-length result into outPtr (outLen must equal
4567
+ // the length the producing op returned). Returns bytes written.
4568
+ // @ts-ignore: decorator
4569
+ @external("env", "crypto.take_result")
4570
+ export declare function takeResult(outPtr: usize, outLen: i32): i32;
4571
+
4572
+ // digest(alg, data) -> digest length (stashed) or negative error.
4573
+ // @ts-ignore: decorator
4574
+ @external("env", "crypto.digest")
4575
+ export declare function digest(alg: i32, dataPtr: usize, dataLen: i32): i32;
4576
+
4577
+ // importKey -> opaque key handle (>= 0) or negative error.
4578
+ // @ts-ignore: decorator
4579
+ @external("env", "crypto.import_key")
4580
+ export declare function importKey(
4581
+ format: i32,
4582
+ keyPtr: usize,
4583
+ keyLen: i32,
4584
+ paramsPtr: usize,
4585
+ paramsLen: i32,
4586
+ extractable: i32,
4587
+ usages: i32
4588
+ ): i32;
4589
+
4590
+ // exportKey -> exported length (stashed) or negative error.
4591
+ // @ts-ignore: decorator
4592
+ @external("env", "crypto.export_key")
4593
+ export declare function exportKey(format: i32, handle: i32): i32;
4594
+
4595
+ // encrypt / decrypt -> output length (stashed) or negative error.
4596
+ // @ts-ignore: decorator
4597
+ @external("env", "crypto.encrypt")
4598
+ export declare function encrypt(
4599
+ handle: i32,
4600
+ paramsPtr: usize,
4601
+ paramsLen: i32,
4602
+ dataPtr: usize,
4603
+ dataLen: i32
4604
+ ): i32;
4605
+ // @ts-ignore: decorator
4606
+ @external("env", "crypto.decrypt")
4607
+ export declare function decrypt(
4608
+ handle: i32,
4609
+ paramsPtr: usize,
4610
+ paramsLen: i32,
4611
+ dataPtr: usize,
4612
+ dataLen: i32
4613
+ ): i32;
4614
+
4615
+ // sign -> signature length (stashed) or negative error.
4616
+ // @ts-ignore: decorator
4617
+ @external("env", "crypto.sign")
4618
+ export declare function sign(
4619
+ handle: i32,
4620
+ paramsPtr: usize,
4621
+ paramsLen: i32,
4622
+ dataPtr: usize,
4623
+ dataLen: i32
4624
+ ): i32;
4625
+
4626
+ // verify -> 1 (valid), 0 (invalid), or negative error.
4627
+ // @ts-ignore: decorator
4628
+ @external("env", "crypto.verify")
4629
+ export declare function verify(
4630
+ handle: i32,
4631
+ paramsPtr: usize,
4632
+ paramsLen: i32,
4633
+ sigPtr: usize,
4634
+ sigLen: i32,
4635
+ dataPtr: usize,
4636
+ dataLen: i32
4637
+ ): i32;
4638
+
4639
+ // deriveBits -> derived length (stashed) or negative error.
4640
+ // @ts-ignore: decorator
4641
+ @external("env", "crypto.derive_bits")
4642
+ export declare function deriveBits(
4643
+ handle: i32,
4644
+ paramsPtr: usize,
4645
+ paramsLen: i32,
4646
+ lengthBits: i32
4647
+ ): i32;
4648
+ }
4550
4649
  `,bitflags:`// Type-safe bit manipulation utilities.
4551
4650
  // Pure @inline functions \u2014 each compiles to 1-2 wasm instructions.
4552
4651
 
@@ -7471,13 +7570,656 @@ export namespace console {
7471
7570
  binding.timeEnd(label);
7472
7571
  }
7473
7572
  }
7474
- `,crypto:`import {
7475
- crypto as crypto_binding
7476
- } from "bindings/dom";
7573
+ `,crypto:`// Web Crypto for ToilScript \u2014 a synchronous SubtleCrypto plus ergonomic
7574
+ // helpers, backed by metered host functions (see \`bindings/webcrypto.ts\` and
7575
+ // the toil-backend \`crypto\` host module).
7576
+ //
7577
+ // Deviations from the web spec (ToilScript has no Promises): every method is
7578
+ // synchronous and returns its value directly. Algorithm parameters are small
7579
+ // classes (e.g. \`AesGcmParams\`) rather than object literals, and key usages are
7580
+ // an i32 bitmask. RSA, on-host key generation, and the \`jwk\` format are not
7581
+ // provided (RSA was dropped for an unfixable timing side-channel in the only
7582
+ // pure-Rust implementation; keys are imported, never generated on-host).
7583
+
7584
+ import { webcrypto } from "bindings/webcrypto";
7585
+ import { SubtleCrypto } from "crypto/subtle";
7586
+ import { HmacImportParams, HmacParams, ALG_SHA_256, USAGE_SIGN } from "crypto/algorithms";
7587
+ import { Encoding } from "encoding";
7588
+
7589
+ // Re-export the public surface so guests can import everything from "crypto".
7590
+ export { SubtleCrypto } from "./crypto/subtle";
7591
+ export { CryptoKey, CryptoKeyPair } from "./crypto/key";
7592
+ export {
7593
+ AlgorithmParams,
7594
+ AesGcmParams,
7595
+ AesCbcParams,
7596
+ AesCtrParams,
7597
+ HmacImportParams,
7598
+ HmacParams,
7599
+ Pbkdf2Params,
7600
+ HkdfParams,
7601
+ EcdsaParams,
7602
+ EcKeyImportParams,
7603
+ Ed25519Params,
7604
+ X25519ImportParams,
7605
+ EcdhParams,
7606
+ algId,
7607
+ algName,
7608
+ formatId,
7609
+ curveId,
7610
+ cryptoError,
7611
+ ALG_SHA_1,
7612
+ ALG_SHA_256,
7613
+ ALG_SHA_384,
7614
+ ALG_SHA_512,
7615
+ ALG_AES_GCM,
7616
+ ALG_AES_CBC,
7617
+ ALG_AES_CTR,
7618
+ ALG_AES_KW,
7619
+ ALG_HMAC,
7620
+ ALG_ECDSA,
7621
+ ALG_ED25519,
7622
+ ALG_ECDH,
7623
+ ALG_X25519,
7624
+ ALG_HKDF,
7625
+ ALG_PBKDF2,
7626
+ CURVE_P256,
7627
+ CURVE_P384,
7628
+ USAGE_ENCRYPT,
7629
+ USAGE_DECRYPT,
7630
+ USAGE_SIGN,
7631
+ USAGE_VERIFY,
7632
+ USAGE_DERIVE_KEY,
7633
+ USAGE_DERIVE_BITS,
7634
+ USAGE_WRAP_KEY,
7635
+ USAGE_UNWRAP_KEY,
7636
+ } from "./crypto/algorithms";
7637
+
7638
+ function utf8Bytes(s: string): Uint8Array {
7639
+ return Uint8Array.wrap(String.UTF8.encode(s));
7640
+ }
7477
7641
 
7478
7642
  export namespace crypto {
7643
+ /// The synchronous SubtleCrypto singleton. \`@lazy\` defers initialization to
7644
+ /// first use so accessing \`crypto.subtle\` from global scope (without an
7645
+ /// explicit import of "crypto") doesn't hit a cross-module init-order error.
7646
+ // @ts-ignore: decorator
7647
+ @lazy export const subtle: SubtleCrypto = new SubtleCrypto();
7648
+
7649
+ /// Fill \`array\` with cryptographically strong random bytes.
7479
7650
  export function getRandomValues(array: Uint8Array): void {
7480
- crypto_binding.getRandomValues(array);
7651
+ webcrypto.fillRandom(array.dataStart, array.byteLength);
7652
+ }
7653
+
7654
+ /// An RFC 4122 version-4 UUID string.
7655
+ export function randomUUID(): string {
7656
+ let b = new Uint8Array(16);
7657
+ webcrypto.randomUuid(b.dataStart);
7658
+ b[6] = (b[6] & 0x0f) | 0x40; // version 4
7659
+ b[8] = (b[8] & 0x3f) | 0x80; // variant 10
7660
+ let h = toHex(b);
7661
+ return (
7662
+ h.substring(0, 8) +
7663
+ "-" +
7664
+ h.substring(8, 12) +
7665
+ "-" +
7666
+ h.substring(12, 16) +
7667
+ "-" +
7668
+ h.substring(16, 20) +
7669
+ "-" +
7670
+ h.substring(20, 32)
7671
+ );
7672
+ }
7673
+
7674
+ // --- Ergonomic digest helpers (thin wrappers over subtle.digest) ----------
7675
+ export function sha1(data: Uint8Array): Uint8Array {
7676
+ return subtle.digest("SHA-1", data);
7677
+ }
7678
+ export function sha256(data: Uint8Array): Uint8Array {
7679
+ return subtle.digest("SHA-256", data);
7680
+ }
7681
+ export function sha384(data: Uint8Array): Uint8Array {
7682
+ return subtle.digest("SHA-384", data);
7683
+ }
7684
+ export function sha512(data: Uint8Array): Uint8Array {
7685
+ return subtle.digest("SHA-512", data);
7686
+ }
7687
+
7688
+ // String-input variants (UTF-8 encode, then hash).
7689
+ export function sha1Text(s: string): Uint8Array {
7690
+ return sha1(utf8Bytes(s));
7691
+ }
7692
+ export function sha256Text(s: string): Uint8Array {
7693
+ return sha256(utf8Bytes(s));
7694
+ }
7695
+ export function sha384Text(s: string): Uint8Array {
7696
+ return sha384(utf8Bytes(s));
7697
+ }
7698
+ export function sha512Text(s: string): Uint8Array {
7699
+ return sha512(utf8Bytes(s));
7700
+ }
7701
+
7702
+ /// One-shot HMAC-SHA-256 over raw key + message bytes.
7703
+ export function hmacSha256(key: Uint8Array, msg: Uint8Array): Uint8Array {
7704
+ let k = subtle.importKey("raw", key, new HmacImportParams(ALG_SHA_256), false, USAGE_SIGN);
7705
+ return subtle.sign(new HmacParams(), k, msg);
7706
+ }
7707
+ export function hmacSha256Text(key: Uint8Array, msg: string): Uint8Array {
7708
+ return hmacSha256(key, utf8Bytes(msg));
7709
+ }
7710
+
7711
+ /// Lowercase hex string of \`bytes\` (handy for displaying digests).
7712
+ export function toHex(bytes: Uint8Array): string {
7713
+ let hexLen = bytes.length * 2;
7714
+ if (hexLen == 0) return "";
7715
+ let dst = new Uint8Array(hexLen);
7716
+ Encoding.Hex.encode(bytes.dataStart, bytes.length, dst.dataStart);
7717
+ return String.UTF8.decode(dst.buffer);
7718
+ }
7719
+ }
7720
+ `,"crypto/algorithms":`// The Web Crypto ABI contract: algorithm / format / curve ids, usage flags,
7721
+ // error codes, and the packed-parameter classes. This is the single source of
7722
+ // truth that the toil-backend Rust host and the toiljs dev mock mirror.
7723
+ //
7724
+ // Parameterized algorithms can't ride in plain scalars (AssemblyScript has no
7725
+ // object literals across the host boundary), so each \`*Params\` class serializes
7726
+ // itself into one little-endian buffer via \`DataWriter\` (whose \`writeBytes\`
7727
+ // emits a u32 length prefix + bytes \u2014 the blob format the host reads).
7728
+
7729
+ import { DataWriter } from "data";
7730
+
7731
+ // --- Algorithm ids (also used as the inner-hash id for HMAC/ECDSA/KDF) ------
7732
+ export const ALG_SHA_1: i32 = 1;
7733
+ export const ALG_SHA_256: i32 = 2;
7734
+ export const ALG_SHA_384: i32 = 3;
7735
+ export const ALG_SHA_512: i32 = 4;
7736
+ export const ALG_SHA3_256: i32 = 5;
7737
+ export const ALG_SHA3_384: i32 = 6;
7738
+ export const ALG_SHA3_512: i32 = 7;
7739
+ export const ALG_AES_GCM: i32 = 10;
7740
+ export const ALG_AES_CBC: i32 = 11;
7741
+ export const ALG_AES_CTR: i32 = 12;
7742
+ export const ALG_AES_KW: i32 = 13;
7743
+ export const ALG_HMAC: i32 = 20;
7744
+ export const ALG_ECDSA: i32 = 32;
7745
+ export const ALG_ED25519: i32 = 33;
7746
+ export const ALG_ECDH: i32 = 50;
7747
+ export const ALG_X25519: i32 = 51;
7748
+ export const ALG_HKDF: i32 = 52;
7749
+ export const ALG_PBKDF2: i32 = 53;
7750
+
7751
+ // --- Key formats ------------------------------------------------------------
7752
+ export const FMT_RAW: i32 = 0;
7753
+ export const FMT_PKCS8: i32 = 1;
7754
+ export const FMT_SPKI: i32 = 2;
7755
+ export const FMT_JWK: i32 = 3; // not supported (throws guest-side)
7756
+
7757
+ // --- Named curves -----------------------------------------------------------
7758
+ export const CURVE_P256: i32 = 1;
7759
+ export const CURVE_P384: i32 = 2;
7760
+ export const CURVE_P521: i32 = 3; // not supported
7761
+
7762
+ // --- Key-usage bit flags (OR together) --------------------------------------
7763
+ export const USAGE_ENCRYPT: i32 = 0x01;
7764
+ export const USAGE_DECRYPT: i32 = 0x02;
7765
+ export const USAGE_SIGN: i32 = 0x04;
7766
+ export const USAGE_VERIFY: i32 = 0x08;
7767
+ export const USAGE_DERIVE_KEY: i32 = 0x10;
7768
+ export const USAGE_DERIVE_BITS: i32 = 0x20;
7769
+ export const USAGE_WRAP_KEY: i32 = 0x40;
7770
+ export const USAGE_UNWRAP_KEY: i32 = 0x80;
7771
+
7772
+ function asciiUpper(s: string): string {
7773
+ let out = "";
7774
+ for (let i = 0; i < s.length; i++) {
7775
+ let c = s.charCodeAt(i);
7776
+ if (c >= 97 && c <= 122) c -= 32;
7777
+ out += String.fromCharCode(c);
7778
+ }
7779
+ return out;
7780
+ }
7781
+
7782
+ /// Map a Web Crypto algorithm name (case-insensitive) to its id, or 0.
7783
+ export function algId(name: string): i32 {
7784
+ let n = asciiUpper(name);
7785
+ if (n == "SHA-1") return ALG_SHA_1;
7786
+ if (n == "SHA-256") return ALG_SHA_256;
7787
+ if (n == "SHA-384") return ALG_SHA_384;
7788
+ if (n == "SHA-512") return ALG_SHA_512;
7789
+ if (n == "SHA3-256") return ALG_SHA3_256;
7790
+ if (n == "SHA3-384") return ALG_SHA3_384;
7791
+ if (n == "SHA3-512") return ALG_SHA3_512;
7792
+ if (n == "AES-GCM") return ALG_AES_GCM;
7793
+ if (n == "AES-CBC") return ALG_AES_CBC;
7794
+ if (n == "AES-CTR") return ALG_AES_CTR;
7795
+ if (n == "AES-KW") return ALG_AES_KW;
7796
+ if (n == "HMAC") return ALG_HMAC;
7797
+ if (n == "ECDSA") return ALG_ECDSA;
7798
+ if (n == "ED25519") return ALG_ED25519;
7799
+ if (n == "ECDH") return ALG_ECDH;
7800
+ if (n == "X25519") return ALG_X25519;
7801
+ if (n == "HKDF") return ALG_HKDF;
7802
+ if (n == "PBKDF2") return ALG_PBKDF2;
7803
+ return 0;
7804
+ }
7805
+
7806
+ /// Reverse of {@link algId}, for \`CryptoKey.algorithmName\`.
7807
+ export function algName(id: i32): string {
7808
+ if (id == ALG_SHA_1) return "SHA-1";
7809
+ if (id == ALG_SHA_256) return "SHA-256";
7810
+ if (id == ALG_SHA_384) return "SHA-384";
7811
+ if (id == ALG_SHA_512) return "SHA-512";
7812
+ if (id == ALG_AES_GCM) return "AES-GCM";
7813
+ if (id == ALG_AES_CBC) return "AES-CBC";
7814
+ if (id == ALG_AES_CTR) return "AES-CTR";
7815
+ if (id == ALG_AES_KW) return "AES-KW";
7816
+ if (id == ALG_HMAC) return "HMAC";
7817
+ if (id == ALG_ECDSA) return "ECDSA";
7818
+ if (id == ALG_ED25519) return "Ed25519";
7819
+ if (id == ALG_ECDH) return "ECDH";
7820
+ if (id == ALG_X25519) return "X25519";
7821
+ if (id == ALG_HKDF) return "HKDF";
7822
+ if (id == ALG_PBKDF2) return "PBKDF2";
7823
+ return "unknown";
7824
+ }
7825
+
7826
+ /// Map a key-format name to its id, or -1.
7827
+ export function formatId(name: string): i32 {
7828
+ let n = asciiUpper(name);
7829
+ if (n == "RAW") return FMT_RAW;
7830
+ if (n == "PKCS8") return FMT_PKCS8;
7831
+ if (n == "SPKI") return FMT_SPKI;
7832
+ if (n == "JWK") return FMT_JWK;
7833
+ return -1;
7834
+ }
7835
+
7836
+ /// Map a named-curve string to its id, or 0.
7837
+ export function curveId(name: string): i32 {
7838
+ let n = asciiUpper(name);
7839
+ if (n == "P-256") return CURVE_P256;
7840
+ if (n == "P-384") return CURVE_P384;
7841
+ if (n == "P-521") return CURVE_P521;
7842
+ return 0;
7843
+ }
7844
+
7845
+ /// Decode a negative host error code into a human-readable message.
7846
+ export function cryptoError(code: i32): string {
7847
+ if (code == -1) return "crypto: operation failed";
7848
+ if (code == -2) return "crypto: invalid key handle";
7849
+ if (code == -3) return "crypto: unsupported algorithm";
7850
+ if (code == -4) return "crypto: invalid parameters";
7851
+ if (code == -5) return "crypto: operation failed (bad tag, padding, or key)";
7852
+ if (code == -6) return "crypto: key usage not permitted";
7853
+ if (code == -7) return "crypto: key is not extractable";
7854
+ return "crypto: error " + code.toString();
7855
+ }
7856
+
7857
+ const EMPTY: Uint8Array = new Uint8Array(0);
7858
+
7859
+ // --- Parameter classes ------------------------------------------------------
7860
+
7861
+ /// Base for every algorithm-parameter object. Subclasses write a fixed
7862
+ /// \`(algId, hash)\` header followed by their tail.
7863
+ export abstract class AlgorithmParams {
7864
+ abstract serialize(w: DataWriter): void;
7865
+ /// Pack into a standalone little-endian buffer for the host.
7866
+ pack(): Uint8Array {
7867
+ let w = new DataWriter();
7868
+ this.serialize(w);
7869
+ return w.toBytes();
7870
+ }
7871
+ }
7872
+
7873
+ export class AesGcmParams extends AlgorithmParams {
7874
+ iv: Uint8Array;
7875
+ additionalData: Uint8Array;
7876
+ tagLength: i32;
7877
+ constructor(iv: Uint8Array, additionalData: Uint8Array = EMPTY, tagLength: i32 = 128) {
7878
+ super();
7879
+ this.iv = iv;
7880
+ this.additionalData = additionalData;
7881
+ this.tagLength = tagLength;
7882
+ }
7883
+ serialize(w: DataWriter): void {
7884
+ w.writeI32(ALG_AES_GCM);
7885
+ w.writeI32(0);
7886
+ w.writeBytes(this.iv);
7887
+ w.writeI32(this.tagLength);
7888
+ w.writeBytes(this.additionalData);
7889
+ }
7890
+ }
7891
+
7892
+ export class AesCbcParams extends AlgorithmParams {
7893
+ iv: Uint8Array;
7894
+ constructor(iv: Uint8Array) {
7895
+ super();
7896
+ this.iv = iv;
7897
+ }
7898
+ serialize(w: DataWriter): void {
7899
+ w.writeI32(ALG_AES_CBC);
7900
+ w.writeI32(0);
7901
+ w.writeBytes(this.iv);
7902
+ }
7903
+ }
7904
+
7905
+ export class AesCtrParams extends AlgorithmParams {
7906
+ counter: Uint8Array;
7907
+ length: i32; // counter length in bits (must be 128)
7908
+ constructor(counter: Uint8Array, length: i32 = 128) {
7909
+ super();
7910
+ this.counter = counter;
7911
+ this.length = length;
7912
+ }
7913
+ serialize(w: DataWriter): void {
7914
+ w.writeI32(ALG_AES_CTR);
7915
+ w.writeI32(0);
7916
+ w.writeBytes(this.counter);
7917
+ w.writeI32(this.length);
7918
+ }
7919
+ }
7920
+
7921
+ /// HMAC key import: carries the inner hash id.
7922
+ export class HmacImportParams extends AlgorithmParams {
7923
+ hash: i32;
7924
+ constructor(hash: i32) {
7925
+ super();
7926
+ this.hash = hash;
7927
+ }
7928
+ serialize(w: DataWriter): void {
7929
+ w.writeI32(ALG_HMAC);
7930
+ w.writeI32(this.hash);
7931
+ }
7932
+ }
7933
+
7934
+ /// HMAC sign/verify: the hash is taken from the key.
7935
+ export class HmacParams extends AlgorithmParams {
7936
+ serialize(w: DataWriter): void {
7937
+ w.writeI32(ALG_HMAC);
7938
+ w.writeI32(0);
7939
+ }
7940
+ }
7941
+
7942
+ export class Pbkdf2Params extends AlgorithmParams {
7943
+ hash: i32;
7944
+ salt: Uint8Array;
7945
+ iterations: u32;
7946
+ constructor(hash: i32, salt: Uint8Array, iterations: u32) {
7947
+ super();
7948
+ this.hash = hash;
7949
+ this.salt = salt;
7950
+ this.iterations = iterations;
7951
+ }
7952
+ serialize(w: DataWriter): void {
7953
+ w.writeI32(ALG_PBKDF2);
7954
+ w.writeI32(this.hash);
7955
+ w.writeU32(this.iterations);
7956
+ w.writeBytes(this.salt);
7957
+ }
7958
+ }
7959
+
7960
+ export class HkdfParams extends AlgorithmParams {
7961
+ hash: i32;
7962
+ salt: Uint8Array;
7963
+ info: Uint8Array;
7964
+ constructor(hash: i32, salt: Uint8Array, info: Uint8Array = EMPTY) {
7965
+ super();
7966
+ this.hash = hash;
7967
+ this.salt = salt;
7968
+ this.info = info;
7969
+ }
7970
+ serialize(w: DataWriter): void {
7971
+ w.writeI32(ALG_HKDF);
7972
+ w.writeI32(this.hash);
7973
+ w.writeBytes(this.salt);
7974
+ w.writeBytes(this.info);
7975
+ }
7976
+ }
7977
+
7978
+ /// ECDSA sign/verify: carries the hash (P-256\u2194SHA-256, P-384\u2194SHA-384).
7979
+ export class EcdsaParams extends AlgorithmParams {
7980
+ hash: i32;
7981
+ constructor(hash: i32) {
7982
+ super();
7983
+ this.hash = hash;
7984
+ }
7985
+ serialize(w: DataWriter): void {
7986
+ w.writeI32(ALG_ECDSA);
7987
+ w.writeI32(this.hash);
7988
+ }
7989
+ }
7990
+
7991
+ /// EC key import (ECDSA or ECDH): carries the named curve.
7992
+ export class EcKeyImportParams extends AlgorithmParams {
7993
+ alg: i32; // ALG_ECDSA or ALG_ECDH
7994
+ namedCurve: i32;
7995
+ constructor(alg: i32, namedCurve: i32) {
7996
+ super();
7997
+ this.alg = alg;
7998
+ this.namedCurve = namedCurve;
7999
+ }
8000
+ serialize(w: DataWriter): void {
8001
+ w.writeI32(this.alg);
8002
+ w.writeI32(0);
8003
+ w.writeI32(this.namedCurve);
8004
+ }
8005
+ }
8006
+
8007
+ export class Ed25519Params extends AlgorithmParams {
8008
+ serialize(w: DataWriter): void {
8009
+ w.writeI32(ALG_ED25519);
8010
+ w.writeI32(0);
8011
+ }
8012
+ }
8013
+
8014
+ export class X25519ImportParams extends AlgorithmParams {
8015
+ serialize(w: DataWriter): void {
8016
+ w.writeI32(ALG_X25519);
8017
+ w.writeI32(0);
8018
+ }
8019
+ }
8020
+
8021
+ /// ECDH / X25519 deriveBits: carries the peer public key handle.
8022
+ export class EcdhParams extends AlgorithmParams {
8023
+ alg: i32; // ALG_ECDH or ALG_X25519
8024
+ publicKeyHandle: i32;
8025
+ constructor(alg: i32, publicKeyHandle: i32) {
8026
+ super();
8027
+ this.alg = alg;
8028
+ this.publicKeyHandle = publicKeyHandle;
8029
+ }
8030
+ serialize(w: DataWriter): void {
8031
+ w.writeI32(this.alg);
8032
+ w.writeI32(0);
8033
+ w.writeI32(this.publicKeyHandle);
8034
+ }
8035
+ }
8036
+ `,"crypto/key":`// Opaque CryptoKey wrapping a per-request host keystore handle. Handles are
8037
+ // only valid within the request that created them (the host keystore is reset
8038
+ // between requests), so a CryptoKey must not be cached across dispatches.
8039
+
8040
+ import { algName } from "crypto/algorithms";
8041
+
8042
+ export class CryptoKey {
8043
+ readonly handle: i32;
8044
+ readonly type: string; // "secret" | "public" | "private"
8045
+ readonly extractable: bool;
8046
+ readonly algorithm: i32; // ALG_*
8047
+ readonly usages: i32; // USAGE_* bitmask
8048
+
8049
+ constructor(handle: i32, type: string, extractable: bool, algorithm: i32, usages: i32) {
8050
+ this.handle = handle;
8051
+ this.type = type;
8052
+ this.extractable = extractable;
8053
+ this.algorithm = algorithm;
8054
+ this.usages = usages;
8055
+ }
8056
+
8057
+ algorithmName(): string {
8058
+ return algName(this.algorithm);
8059
+ }
8060
+
8061
+ hasUsage(u: i32): bool {
8062
+ return (this.usages & u) != 0;
8063
+ }
8064
+ }
8065
+
8066
+ export class CryptoKeyPair {
8067
+ readonly publicKey: CryptoKey;
8068
+ readonly privateKey: CryptoKey;
8069
+ constructor(publicKey: CryptoKey, privateKey: CryptoKey) {
8070
+ this.publicKey = publicKey;
8071
+ this.privateKey = privateKey;
8072
+ }
8073
+ }
8074
+ `,"crypto/subtle":`// Synchronous SubtleCrypto. Mirrors the Web Crypto method names but, because
8075
+ // ToilScript has no Promises, every method returns its value directly rather
8076
+ // than a Promise. Variable-length results use the two-step pull (op returns
8077
+ // the length, then \`take_result\` copies the bytes out).
8078
+
8079
+ import { webcrypto } from "bindings/webcrypto";
8080
+ import { CryptoKey } from "crypto/key";
8081
+ import {
8082
+ AlgorithmParams,
8083
+ algId,
8084
+ formatId,
8085
+ cryptoError,
8086
+ FMT_JWK,
8087
+ FMT_PKCS8,
8088
+ FMT_SPKI,
8089
+ ALG_AES_GCM,
8090
+ ALG_AES_CBC,
8091
+ ALG_AES_CTR,
8092
+ ALG_AES_KW,
8093
+ ALG_HMAC,
8094
+ ALG_PBKDF2,
8095
+ ALG_HKDF,
8096
+ } from "crypto/algorithms";
8097
+
8098
+ /// Pull a stashed variable-length result out of the host, or throw on error.
8099
+ function drain(len: i32): Uint8Array {
8100
+ if (len < 0) throw new Error(cryptoError(len));
8101
+ let out = new Uint8Array(len);
8102
+ if (len > 0) webcrypto.takeResult(out.dataStart, len);
8103
+ return out;
8104
+ }
8105
+
8106
+ function isSymmetricAlg(alg: i32): bool {
8107
+ return (
8108
+ alg == ALG_AES_GCM ||
8109
+ alg == ALG_AES_CBC ||
8110
+ alg == ALG_AES_CTR ||
8111
+ alg == ALG_AES_KW ||
8112
+ alg == ALG_HMAC ||
8113
+ alg == ALG_PBKDF2 ||
8114
+ alg == ALG_HKDF
8115
+ );
8116
+ }
8117
+
8118
+ export class SubtleCrypto {
8119
+ digest(algorithm: string, data: Uint8Array): Uint8Array {
8120
+ let id = algId(algorithm);
8121
+ if (id == 0) throw new Error("Unrecognized algorithm: " + algorithm);
8122
+ return drain(webcrypto.digest(id, data.dataStart, data.byteLength));
8123
+ }
8124
+
8125
+ importKey(
8126
+ format: string,
8127
+ keyData: Uint8Array,
8128
+ algorithm: AlgorithmParams,
8129
+ extractable: bool,
8130
+ usages: i32
8131
+ ): CryptoKey {
8132
+ let fmt = formatId(format);
8133
+ if (fmt < 0) throw new Error("Unknown key format: " + format);
8134
+ if (fmt == FMT_JWK) throw new Error("jwk key format is not supported");
8135
+ let p = algorithm.pack();
8136
+ let alg = load<i32>(p.dataStart); // first packed field is the alg id
8137
+ let handle = webcrypto.importKey(
8138
+ fmt,
8139
+ keyData.dataStart,
8140
+ keyData.byteLength,
8141
+ p.dataStart,
8142
+ p.byteLength,
8143
+ extractable ? 1 : 0,
8144
+ usages
8145
+ );
8146
+ if (handle < 0) throw new Error(cryptoError(handle));
8147
+
8148
+ let type: string;
8149
+ if (fmt == FMT_PKCS8) type = "private";
8150
+ else if (fmt == FMT_SPKI) type = "public";
8151
+ else type = isSymmetricAlg(alg) ? "secret" : "public";
8152
+
8153
+ return new CryptoKey(handle, type, extractable, alg, usages);
8154
+ }
8155
+
8156
+ exportKey(format: string, key: CryptoKey): Uint8Array {
8157
+ let fmt = formatId(format);
8158
+ if (fmt < 0) throw new Error("Unknown key format: " + format);
8159
+ if (fmt == FMT_JWK) throw new Error("jwk key format is not supported");
8160
+ return drain(webcrypto.exportKey(fmt, key.handle));
8161
+ }
8162
+
8163
+ encrypt(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array {
8164
+ let p = algorithm.pack();
8165
+ return drain(
8166
+ webcrypto.encrypt(key.handle, p.dataStart, p.byteLength, data.dataStart, data.byteLength)
8167
+ );
8168
+ }
8169
+
8170
+ decrypt(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array {
8171
+ let p = algorithm.pack();
8172
+ return drain(
8173
+ webcrypto.decrypt(key.handle, p.dataStart, p.byteLength, data.dataStart, data.byteLength)
8174
+ );
8175
+ }
8176
+
8177
+ sign(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array {
8178
+ let p = algorithm.pack();
8179
+ return drain(
8180
+ webcrypto.sign(key.handle, p.dataStart, p.byteLength, data.dataStart, data.byteLength)
8181
+ );
8182
+ }
8183
+
8184
+ verify(
8185
+ algorithm: AlgorithmParams,
8186
+ key: CryptoKey,
8187
+ signature: Uint8Array,
8188
+ data: Uint8Array
8189
+ ): bool {
8190
+ let p = algorithm.pack();
8191
+ let r = webcrypto.verify(
8192
+ key.handle,
8193
+ p.dataStart,
8194
+ p.byteLength,
8195
+ signature.dataStart,
8196
+ signature.byteLength,
8197
+ data.dataStart,
8198
+ data.byteLength
8199
+ );
8200
+ if (r < 0) throw new Error(cryptoError(r));
8201
+ return r == 1;
8202
+ }
8203
+
8204
+ /// Derive \`length\` bits from \`baseKey\` (PBKDF2/HKDF/ECDH/X25519).
8205
+ deriveBits(algorithm: AlgorithmParams, baseKey: CryptoKey, length: i32): Uint8Array {
8206
+ let p = algorithm.pack();
8207
+ return drain(webcrypto.deriveBits(baseKey.handle, p.dataStart, p.byteLength, length));
8208
+ }
8209
+
8210
+ /// Composed from deriveBits + importKey. Unlike the web API, the derived bit
8211
+ /// length is passed explicitly (\`lengthBits\`) since ToilScript can't infer
8212
+ /// it from \`derivedKeyAlgorithm\` the way the spec does.
8213
+ deriveKey(
8214
+ algorithm: AlgorithmParams,
8215
+ baseKey: CryptoKey,
8216
+ lengthBits: i32,
8217
+ derivedKeyAlgorithm: AlgorithmParams,
8218
+ extractable: bool,
8219
+ usages: i32
8220
+ ): CryptoKey {
8221
+ let bits = this.deriveBits(algorithm, baseKey, lengthBits);
8222
+ return this.importKey("raw", bits, derivedKeyAlgorithm, extractable, usages);
7481
8223
  }
7482
8224
  }
7483
8225
  `,data:`/**
@@ -28088,10 +28830,93 @@ declare namespace console {
28088
28830
  export function timeEnd(label?: string): void;
28089
28831
  }
28090
28832
 
28091
- /** Browser-like crypto utilities. */
28833
+ /** Opaque key handle for the Web Crypto API (per-request on the edge). */
28834
+ declare class CryptoKey {
28835
+ readonly handle: u32;
28836
+ readonly type: string;
28837
+ readonly extractable: bool;
28838
+ readonly algorithm: i32;
28839
+ readonly usages: i32;
28840
+ algorithmName(): string;
28841
+ hasUsage(u: i32): bool;
28842
+ }
28843
+ declare class CryptoKeyPair {
28844
+ readonly publicKey: CryptoKey;
28845
+ readonly privateKey: CryptoKey;
28846
+ }
28847
+ /** Base class for the algorithm-parameter objects passed to SubtleCrypto. */
28848
+ declare abstract class AlgorithmParams {}
28849
+ declare class AesGcmParams extends AlgorithmParams {
28850
+ constructor(iv: Uint8Array, additionalData?: Uint8Array, tagLength?: i32);
28851
+ }
28852
+ declare class AesCbcParams extends AlgorithmParams {
28853
+ constructor(iv: Uint8Array);
28854
+ }
28855
+ declare class AesCtrParams extends AlgorithmParams {
28856
+ constructor(counter: Uint8Array, length?: i32);
28857
+ }
28858
+ declare class HmacImportParams extends AlgorithmParams {
28859
+ constructor(hash: i32);
28860
+ }
28861
+ declare class HmacParams extends AlgorithmParams {}
28862
+ declare class Pbkdf2Params extends AlgorithmParams {
28863
+ constructor(hash: i32, salt: Uint8Array, iterations: u32);
28864
+ }
28865
+ declare class HkdfParams extends AlgorithmParams {
28866
+ constructor(hash: i32, salt: Uint8Array, info?: Uint8Array);
28867
+ }
28868
+ declare class EcdsaParams extends AlgorithmParams {
28869
+ constructor(hash: i32);
28870
+ }
28871
+ declare class EcKeyImportParams extends AlgorithmParams {
28872
+ constructor(alg: i32, namedCurve: i32);
28873
+ }
28874
+ declare class Ed25519Params extends AlgorithmParams {}
28875
+ declare class X25519ImportParams extends AlgorithmParams {}
28876
+ declare class EcdhParams extends AlgorithmParams {
28877
+ constructor(alg: i32, publicKeyHandle: i32);
28878
+ }
28879
+ /** Synchronous SubtleCrypto (no Promises). Returns values directly. */
28880
+ declare class SubtleCrypto {
28881
+ digest(algorithm: string, data: Uint8Array): Uint8Array;
28882
+ importKey(format: string, keyData: Uint8Array, algorithm: AlgorithmParams, extractable: bool, usages: i32): CryptoKey;
28883
+ exportKey(format: string, key: CryptoKey): Uint8Array;
28884
+ encrypt(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array;
28885
+ decrypt(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array;
28886
+ sign(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array;
28887
+ verify(algorithm: AlgorithmParams, key: CryptoKey, signature: Uint8Array, data: Uint8Array): bool;
28888
+ deriveBits(algorithm: AlgorithmParams, baseKey: CryptoKey, length: i32): Uint8Array;
28889
+ deriveKey(algorithm: AlgorithmParams, baseKey: CryptoKey, lengthBits: i32, derivedKeyAlgorithm: AlgorithmParams, extractable: bool, usages: i32): CryptoKey;
28890
+ }
28891
+
28892
+ // Algorithm / format / curve / usage ids (the Web Crypto ABI contract).
28893
+ declare const ALG_SHA_1: i32, ALG_SHA_256: i32, ALG_SHA_384: i32, ALG_SHA_512: i32;
28894
+ declare const ALG_AES_GCM: i32, ALG_AES_CBC: i32, ALG_AES_CTR: i32, ALG_AES_KW: i32;
28895
+ declare const ALG_HMAC: i32, ALG_ECDSA: i32, ALG_ED25519: i32, ALG_ECDH: i32, ALG_X25519: i32, ALG_HKDF: i32, ALG_PBKDF2: i32;
28896
+ declare const CURVE_P256: i32, CURVE_P384: i32;
28897
+ declare const USAGE_ENCRYPT: i32, USAGE_DECRYPT: i32, USAGE_SIGN: i32, USAGE_VERIFY: i32;
28898
+ declare const USAGE_DERIVE_KEY: i32, USAGE_DERIVE_BITS: i32, USAGE_WRAP_KEY: i32, USAGE_UNWRAP_KEY: i32;
28899
+
28900
+ /** Browser-like Web Crypto (synchronous SubtleCrypto + ergonomic helpers). */
28092
28901
  declare namespace crypto {
28902
+ /** The synchronous SubtleCrypto instance. */
28903
+ export const subtle: SubtleCrypto;
28093
28904
  /** Fills \`array\` with cryptographically strong random values. */
28094
28905
  export function getRandomValues(array: Uint8Array): void;
28906
+ /** An RFC 4122 version-4 UUID string. */
28907
+ export function randomUUID(): string;
28908
+ export function sha1(data: Uint8Array): Uint8Array;
28909
+ export function sha256(data: Uint8Array): Uint8Array;
28910
+ export function sha384(data: Uint8Array): Uint8Array;
28911
+ export function sha512(data: Uint8Array): Uint8Array;
28912
+ export function sha1Text(s: string): Uint8Array;
28913
+ export function sha256Text(s: string): Uint8Array;
28914
+ export function sha384Text(s: string): Uint8Array;
28915
+ export function sha512Text(s: string): Uint8Array;
28916
+ export function hmacSha256(key: Uint8Array, msg: Uint8Array): Uint8Array;
28917
+ export function hmacSha256Text(key: Uint8Array, msg: string): Uint8Array;
28918
+ /** Lowercase hex string of \`bytes\`. */
28919
+ export function toHex(bytes: Uint8Array): string;
28095
28920
  }
28096
28921
 
28097
28922
  // Decorators
@@ -28632,7 +29457,7 @@ declare interface Float64Array {
28632
29457
  // FIXME: remove
28633
29458
  declare function offsetof<T>(fieldName?: string): usize;
28634
29459
  declare function idof<T>(): u32;
28635
- `};var xn={};nn(xn,{default:()=>pn});Dn(xn,Mt);import*as Mt from"binaryen";import{default as pn}from"binaryen";import*as At from"toilscript";var h=At,Pn=M.argv.indexOf("--wasm");if(~Pn){let e=String(M.argv[Pn+1]);M.argv.splice(Pn,2),h=await import(new URL(e,dn.pathToFileURL(M.cwd()+"/")))}var Vn=sn.createRequire(import.meta.url),Kn=M.platform==="win32",E=Kn?`\r
29460
+ `};var pn={};nn(pn,{default:()=>xn});Dn(pn,Mt);import*as Mt from"binaryen";import{default as xn}from"binaryen";import*as At from"toilscript";var h=At,Pn=M.argv.indexOf("--wasm");if(~Pn){let e=String(M.argv[Pn+1]);M.argv.splice(Pn,2),h=await import(new URL(e,dn.pathToFileURL(M.cwd()+"/")))}var Vn=sn.createRequire(import.meta.url),Xn=M.platform==="win32",E=Xn?`\r
28636
29461
  `:`
28637
- `,jn=Kn?"\\":"/",_=".ts",_t=`.d${_}`,hn=new RegExp("\\"+_+"$"),Tt=new RegExp("^(?!.*\\.d\\"+_+"$).*\\"+_+"$");function Te(e){return e.replace(/-/g,"_").toUpperCase()}function Ct(e){return typeof e=="string"&&e!==""}var Hn=ve,zt=Y,P=Ee,H=Ae,St=_e,Se=3,we=0;function qn(e,t=[]){return Object.keys(e||{}).forEach(n=>{let o=e[n],s=Y[n];s&&s.type==="b"?o&&t.push(`--${n}`):Array.isArray(o)?o.forEach(r=>{t.push(`--${n}`,String(r))}):t.push(`--${n}`,String(o))}),t}async function wt(e,t={}){typeof e=="string"&&(e={[`input${_}`]:e});let n=["--outFile","binary","--textFile","text"];qn(t,n);let o={},s=await Be(n.concat(Object.keys(e)),{readFile:r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:null,writeFile:(r,u)=>{o[r]=u},listFiles:()=>[]});return Object.assign(s,o)}async function Be(e,t){Array.isArray(e)||(e=qn(e)),t||(t={});let n=t.stats||new Cn,o=n.begin(),s=0,r=0,u=0,f=(Hn||"").split(".");f.length===3&&(r=parseInt(f[0])|0,s=parseInt(f[1])|0,u=parseInt(f[2])|0);let p=t.stdout||Xn(),b=t.stderr||Xn(),d=t.readFile||ee,g=t.writeFile||te,y=t.listFiles||ie,m=ye(e,Y,!1),i=m.options;e=m.arguments;let zn=new en(p),j=new en(b);i.noColors&&(zn.enabled=!1,j.enabled=!1);let Yn=m.unknown;Yn.length&&Yn.forEach(a=>{b.write(`${j.yellow("WARNING ")}Unknown option '${a}'${E}`)});let Jn=m.trailing;Jn.length&&b.write(`${j.yellow("WARNING ")}Unsupported trailing arguments: ${Jn.join(" ")}${E}`);let X=null,R=null,z=(a,l={})=>(a&&b.write(`${j.red("FAILURE ")}${a.stack.replace(/^ERROR: /i,"")}${E}`),R&&R.dispose(),n.total||(n.total=n.end(o)),Object.assign({error:a,stdout:p,stderr:b,stats:n},l));if(i.version)return p.write(`Version ${Hn}${E}`),z(null);let w=v.normalize(i.baseDir||"."),K=tn(i.config||"toilconfig.json",w),Sn=v.basename(K),J=v.dirname(K),N=await Ce(Sn,J,d),De=N!=null&&Array.isArray(N.entries)&&N.entries.length;if(i.help||!e.length&&!De){let a=i.help?p:b,l=i.help?zn:j;return a.write([l.white("SYNTAX")," "+l.cyan("toilscript")+" [entryFile ...] [options]","",l.white("EXAMPLES")," "+l.cyan("toilscript")+" hello"+_," "+l.cyan("toilscript")+" hello"+_+" -o hello.wasm -t hello.wat"," "+l.cyan("toilscript")+" hello1"+_+" hello2"+_+" -o -O > hello.wasm"," "+l.cyan("toilscript")+" --config toilconfig.json --target release","",l.white("OPTIONS")].concat(Fe(Y,24,E)).join(E)+E),z(null)}if(!(G.promises&&G.promises.readFile)){if(d===ee)throw Error("'options.readFile' must be specified");if(g===te)throw Error("'options.writeFile' must be specified");if(y===ie)throw Error("'options.listFiles' must be specified")}let wn=new Set;wn.add(K);let Ie=i.target||"release";for(;N;){if(N.targets){let l=N.targets[Ie];l&&(i=Un(Y,i,l,J))}let a=N.options;if(a&&(i=Un(Y,i,a,J)),N.entries)for(let l of N.entries)e.push(tn(l,J));if(N.extends){if(K=tn(N.extends,J,!0),Sn=v.basename(K),J=v.dirname(K),wn.has(K))break;wn.add(K),N=await Ce(Sn,J,d)}else break}if(Mn(Y,i),i.showConfig)return b.write(JSON.stringify({options:i,entries:e},null,2)),z(null);function Zn(a){return[...new Set(a)]}let B,rn,mn,T=h.newOptions();switch(i.runtime){case"stub":rn=0;break;case"minimal":rn=1;break;case"memory":rn=3;break;default:rn=2;break}switch(i.uncheckedBehavior){default:mn=0;break;case"never":mn=1;break;case"always":mn=2;break}if(h.setTarget(T,0),h.setDebugInfo(T,!!i.debug),h.setRuntime(T,rn),h.setNoAssert(T,i.noAssert),h.setExportMemory(T,!i.noExportMemory),h.setImportMemory(T,i.importMemory),h.setInitialMemory(T,i.initialMemory>>>0),h.setMaximumMemory(T,i.maximumMemory>>>0),h.setSharedMemory(T,i.sharedMemory),h.setImportTable(T,i.importTable),h.setExportTable(T,i.exportTable),i.exportStart!=null&&h.setExportStart(T,Ct(i.exportStart)?i.exportStart:"_start"),h.setMemoryBase(T,i.memoryBase>>>0),h.setTableBase(T,i.tableBase>>>0),h.setSourceMap(T,i.sourceMap!=null),h.setUncheckedBehavior(T,mn),h.setNoUnsafe(T,i.noUnsafe),h.setPedantic(T,i.pedantic),h.setLowMemoryLimit(T,i.lowMemoryLimit>>>0),h.setExportRuntime(T,i.exportRuntime),h.setBundleVersion(T,r,s,u),!i.stackSize&&rn===2&&(i.stackSize=h.DEFAULT_STACK_SIZE),h.setStackSize(T,i.stackSize),h.setBindingsHint(T,i.bindings&&i.bindings.length>0),i.use){let a=i.use;for(let l=0,c=a.length;l<c;++l){let x=a[l],A=x.indexOf("=");if(A<0)return z(Error(`Global alias '${x}' is invalid.`));let F=x.substring(0,A).trim(),C=x.substring(A+1).trim();if(!F.length)return z(Error(`Global alias '${x}' is invalid.`));h.addGlobalAlias(T,F,C)}}let U;if((U=i.disable)!=null){typeof U=="string"&&(U=U.split(","));for(let a=0,l=U.length;a<l;++a){let c=U[a].trim(),x=h[`FEATURE_${Te(c)}`];if(!x)return z(Error(`Feature '${c}' is unknown.`));h.setFeature(T,x,!1)}}if((U=i.enable)!=null){typeof U=="string"&&(U=U.split(","));for(let a=0,l=U.length;a<l;++a){let c=U[a].trim(),x=h[`FEATURE_${Te(c)}`];if(!x)return z(Error(`Feature '${c}' is unknown.`));h.setFeature(T,x,!0)}}let Z=0,$=0;i.optimize&&(Z=Se,$=we),typeof i.optimizeLevel=="number"&&(Z=i.optimizeLevel),typeof i.shrinkLevel=="number"&&($=i.shrinkLevel),Z=Math.min(Math.max(Z,0),3),$=Math.min(Math.max($,0),2),h.setOptimizeLevelHints(T,Z,$),B=h.newProgram(T);let an=[];if(Array.isArray(t.transforms)&&an.push(...t.transforms),i.transform){let a=Zn(i.transform);for(let l=0,c=a.length;l<c;++l){let x=a[l].trim(),A,F;if(Vn.resolve)try{A=Vn.resolve(x,{paths:[M.cwd(),w]}),F=await import(dn.pathToFileURL(A)),F.default&&(F=F.default)}catch(C){try{F=Vn(A)}catch{return z(C)}}else try{F=await import(new URL(x,import.meta.url)),F.default&&(F=F.default)}catch(C){return z(C)}if(!F||typeof F!="function"&&typeof F!="object")return z(Error("not a transform: "+a[l]));an.push(F)}}try{an=an.map(a=>(typeof a=="function"&&(Object.assign(a.prototype,{program:B,binaryen:pn,baseDir:w,stdout:p,stderr:b,log:console.error,readFile:d,writeFile:g,listFiles:y}),a=new a),a))}catch(a){return z(a)}async function Bn(a,...l){for(let c=0,x=an.length;c<x;++c){let A=an[c];if(typeof A[a]=="function")try{let F=n.begin();n.transformCount++,await A[a](...l),n.transformTime+=n.end(F)}catch(F){return F}}}Object.keys(H).forEach(a=>{if(a.includes("/"))return;let l=n.begin();n.parseCount++,h.parse(B,H[a],P+a+_,!1),n.parseTime+=n.end(l)});let on=[];if(i.lib){let a=i.lib;typeof a=="string"&&(a=a.split(",")),on.push(...a.map(l=>l.trim())),on=Zn(on);for(let l=0,c=on.length;l<c;++l){let x=on[l],A;x.endsWith(_)?(A=[v.basename(x)],x=v.dirname(x)):A=await y(x,w)||[];for(let F of A){let C=await d(F,x);if(C==null)return z(Error(`Library file '${F}' not found.`));H[F.replace(hn,"")]=C;let O=n.begin();n.parseCount++,h.parse(B,C,P+F,!1),n.parseTime+=n.end(O)}}}i.path=i.path||[];let bn=new Map;async function Oe(a,l){let c=null,x=null;if(!a.startsWith(P))(c=await d(x=a+_,w))==null&&(c=await d(x=a+"/index"+_,w))==null&&(x=a+_,c=await d(a+_t,w));else{let A=a.substring(P.length),F=`${A}/index`;if(Object.prototype.hasOwnProperty.call(H,A))c=H[A],x=P+A+_;else if(Object.prototype.hasOwnProperty.call(H,F))c=H[F],x=P+F+_;else{for(let C of on)if((c=await d(A+_,C))!=null){x=P+A+_;break}else if((c=await d(F+_,C))!=null){x=P+F+_;break}if(c==null){let C=a.match(/^~lib\/((?:@[^/]+\/)?[^/]+)(?:\/(.+))?/);if(C){let O=C[1],q=C[2]||"index",vn=bn.has(l)?bn.get(l):".",L=[],D=v.resolve(w,vn).split(jn);for(let S=D.length,k=Kn?1:0;S>=k;--S)D[S-1]!=="node_modules"&&L.push(`${D.slice(0,S).join(jn)}${jn}node_modules`);L.push(...i.path);for(let S of L.map(k=>v.relative(w,k))){let k=q;if((c=await d(v.join(S,O,k+_),w))!=null){x=`${P}${O}/${k}${_}`,bn.set(x.replace(hn,""),v.join(S,O));break}let un=`${q}/index`;if((c=await d(v.join(S,O,un+_),w))!=null){x=`${P}${O}/${un}${_}`,bn.set(x.replace(hn,""),v.join(S,O));break}}}}}}return c==null?null:{sourceText:c,sourcePath:x}}function Le(a=[]){do{let l=h.nextFile(B);if(l==null)break;a.push(l)}while(!0);return a}async function $n(){let a;for(;(a=Le()).length;){let c=[];for(let x of a){let A=h.getDependee(B,x);c.push(Oe(x,A))}c=await Promise.all(c);for(let x=0,A=a.length;x<A;++x){let F=a[x],C=c[x],O=n.begin();n.parseCount++,C?h.parse(B,C.sourceText,C.sourcePath,!1):h.parse(B,null,F+_,!1),n.parseTime+=n.end(O)}}let l=gn(B,b,i.disableWarning,t.reportDiagnostic,j.enabled);if(l){let c=Error(`${l} parse error(s)`);return c.stack=c.message,z(c)}}{let a=String(i.runtime),l=`rt/index-${a}`,c=H[l];if(c==null){if(l=a,c=await d(l+_,w),c==null)return z(Error(`Runtime '${v.resolve(w,l+_)}' is not found.`))}else l=`~lib/${l}`;let x=n.begin();n.parseCount++,h.parse(B,c,l+_,!0),n.parseTime+=n.end(x)}for(let a=0,l=e.length;a<l;++a){let c=String(e[a]),x=v.isAbsolute(c)?v.relative(w,c):v.normalize(c);x=x.replace(/\\/g,"/").replace(hn,"").replace(/\/$/,"");let A=await d(x+_,w);if(A==null){let C=`${x}/index${_}`;A=await d(C,w),A!=null?x=C:x+=_}else x+=_;let F=n.begin();n.parseCount++,h.parse(B,A,x,!0),n.parseTime+=n.end(F)}{let a=await $n();if(a)return a}{let a=await Bn("afterParse",B.parser);if(a)return z(a)}{let a=await $n();if(a)return a}{let a=n.begin();n.initializeCount++;try{h.initializeProgram(B)}catch(l){I("initialize",l)}n.initializeTime+=n.end(a)}{let a=await Bn("afterInitialize",B);if(a)return z(a)}{let a=n.begin();n.compileCount++;try{X=h.compile(B)}catch(l){let c=gn(B,b,i.disableWarning,t.reportDiagnostic,j.enabled);if(c){let x=Error(`${c} compile error(s)`);return x.stack=x.message,z(x)}I("compile",l)}n.compileTime+=n.end(a)}R=pn.wrapModule(typeof X=="number"||X instanceof Number?h.getBinaryenModuleRef(X):X.ref);let ln=gn(B,b,i.disableWarning,t.reportDiagnostic,j.enabled);if(ln){let a=Error(`${ln} compile error(s)`);return a.stack=a.message,z(a)}{let a=await Bn("afterCompile",R);if(a)return z(a)}if(ln=gn(B,b,i.disableWarning,t.reportDiagnostic,j.enabled),ln){let a=Error(`${ln} afterCompile error(s)`);return a.stack=a.message,z(a)}if(!i.noValidate){let a=n.begin();n.validateCount++;let l=h.validate(X);if(n.validateTime+=n.end(a),!l)return z(Error("validate error"))}if(i.trapMode==="clamp"||i.trapMode==="js"){let a=n.begin();try{R.runPasses([`trap-mode-${i.trapMode}`])}catch(l){I("runPasses",l)}n.compileTime+=n.end(a)}else if(i.trapMode!=="allow")return z(Error("Unsupported trap mode"));let Qn=i.debug,ke=i.converge,ne=i.importMemory?i.zeroFilledMemory:!1,yn=[];i.runPasses&&(typeof i.runPasses=="string"&&(i.runPasses=i.runPasses.split(",")),i.runPasses.length&&i.runPasses.forEach(a=>{yn.includes(a=a.trim())||yn.push(a)}));{let a=n.begin();try{n.optimizeCount++,h.optimize(X,Z,$,Qn,ne)}catch(l){I("optimize",l)}try{R.runPasses(yn)}catch(l){I("runPasses",l)}if(ke){let l;try{let c=n.begin();n.emitCount++,l=R.emitBinary(),n.emitTime+=n.end(c)}catch(c){I("emitBinary (converge)",c)}do{try{n.optimizeCount++,h.optimize(X,Z,$,Qn,ne)}catch(x){I("optimize (converge)",x)}try{R.runPasses(yn)}catch(x){I("runPasses (converge)",x)}let c;try{let x=n.begin();n.emitCount++,c=R.emitBinary(),n.emitTime+=n.end(x)}catch(x){I("emitBinary (converge)",x)}if(c.length>=l.length){c.length>l.length&&b.write(`Last converge was suboptimal.${E}`);break}l=c}while(!0)}n.optimizeTime+=n.end(a)}let Q=[];if(!i.noEmit){if(i.binaryFile)return z(Error("Usage of the --binaryFile compiler option is no longer supported. Use --outFile instead."));let a=i.bindings||[],l=!1,c=i.outFile!=null,x=i.textFile!=null,A=c||x,F=c&&i.outFile.length>0||x&&i.textFile.length>0,C=F?(i.outFile||i.textFile).replace(/\.\w+$/,""):null,O=F?v.basename(C):"output";if(h.setBasenameHint(T,O),i.outFile!=null){let L=i.sourceMap!=null?i.sourceMap.length?i.sourceMap:`./${O}.wasm.map`:null,D=n.begin();n.emitCount++;let S;try{S=R.emitBinary(L)}catch(k){I("emitBinary",k)}if(n.emitTime+=n.end(D),i.outFile.length?Q.push(g(i.outFile,S.binary,w)):(l=!0,Fn(S.binary)),S.sourceMap!="")if(i.outFile.length){let k=JSON.parse(S.sourceMap);k.sourceRoot=`./${O}`;let un=[];for(let En=0,Re=k.sources.length;En<Re;++En){let re=k.sources[En],ae=h.getSource(B,re.replace(hn,""));if(ae==null)return z(Error(`Source of file '${re}' not found.`));un[En]=ae}k.sourcesContent=un,Q.push(g(v.join(v.dirname(i.outFile),v.basename(L)).replace(/^\.\//,""),JSON.stringify(k),w))}else b.write(`Skipped source map (no output path)${E}`)}if(i.textFile!=null||!A){let L=n.begin();n.emitCount++;let D;try{pn.setOptimizeStackIR(!0),D=i.textFile?.endsWith(".wast")?R.emitText():R.emitStackIR()}catch(S){I("emitText",S)}n.emitTime+=n.end(L),i.textFile!=null&&i.textFile.length?Q.push(g(i.textFile,D,w)):l||Fn(D)}let q=a.includes("esm"),vn=!q&&a.includes("raw");if(q||vn)if(C){let L=n.begin();n.emitCount++;let D;try{D=h.buildTSD(B,q)}catch(S){I("buildTSD",S)}n.emitTime+=n.end(L),Q.push(g(C+".d.ts",D,w))}else b.write(`Skipped TypeScript binding (no output path)${E}`);if(q||vn)if(C){let L=n.begin();n.emitCount++;let D;try{D=h.buildJS(B,q)}catch(S){I("buildJS",S)}n.emitTime+=n.end(L),Q.push(g(C+".js",D,w))}else b.write(`Skipped JavaScript binding (no output path)${E}`);if(i.rpcModule!=null&&i.rpcModule.length){let L=n.begin();n.emitCount++;let D;try{D=h.buildServerModule(B,i.rpcRuntime||"toiljs/io")}catch(S){I("buildServerModule",S)}n.emitTime+=n.end(L),D!=null&&Q.push(g(i.rpcModule,D,w))}}try{await Promise.all(Q)}catch(a){return z(a)}return n.total=n.end(o),i.stats&&b.write(n.toString()),z(null);async function ee(a,l){let c=v.resolve(l,a);try{return n.readCount++,await G.promises.readFile(c,"utf8")}catch{return null}}async function te(a,l,c){try{n.writeCount++;let x=v.resolve(c,v.dirname(a)),A=v.join(x,v.basename(a));return await G.promises.mkdir(x,{recursive:!0}),await G.promises.writeFile(A,l),!0}catch{return!1}}async function ie(a,l){try{return n.readCount++,(await G.promises.readdir(v.join(l,a))).filter(c=>Tt.test(c))}catch{return null}}function Fn(a){Fn.used||(Fn.used=!0,n.writeCount++),p.write(a)}function I(a,l){let c=zn.red("\u258C ");console.error([E,c,"Whoops, the ToilScript compiler has crashed during ",a," :-(",E,c,E,(typeof l.stack=="string"?[c,"Here is the stack trace hinting at the problem, perhaps it's useful?",E,c,E,l.stack.replace(/^/mg,c),E]:[c,"There is no stack trace. Perhaps a Binaryen exception above / in console?",E,c,E,c,"> "+l.stack,E]).join(""),c,E,c,"If you see where the error is, feel free to send us a pull request. If not,",E,c,"please let us know: https://github.com/dacely-cloud/toilscript/issues",E,c,E,c,"Thank you!",E].join("")),M.exit(1)}}function Gn(e){return Object.prototype.toString.call(e)==="[object Object]"}async function Ce(e,t,n){let o=await n(e,t),s=v.join(t,e);if(!o)return null;let r;try{r=JSON.parse(o)}catch(u){throw new Error(`Toilconfig is not valid json: ${s}`,{cause:u})}if(r.options&&!Gn(r.options))throw new Error(`Toilconfig.options is not an object: ${s}`);if(r.include&&!Array.isArray(r.include))throw new Error(`Toilconfig.include is not an array: ${s}`);if(r.targets){if(!Gn(r.targets))throw new Error(`Toilconfig.targets is not an object: ${s}`);let u=Object.keys(r.targets);for(let f=0;f<u.length;f++){let p=u[f];if(!Gn(r.targets[p]))throw new Error(`Toilconfig.targets.${p} is not an object: ${s}`)}}if(r.extends&&typeof r.extends!="string")throw new Error(`Toilconfig.extends is not a string: ${s}`);return r}function gn(e,t,n,o,s){typeof s>"u"&&t&&(s=t.isTTY);let r=0;do{let p=h.nextDiagnostic(e);if(!p)break;if(t){let b=d=>{if(n==null)return!1;if(!n.length)return!0;let g=h.getDiagnosticCode(d);return n.includes(g)};(h.isError(p)||!b(p))&&t.write(h.formatDiagnostic(p,s,!0)+E+E)}if(o){let b=function(g){return g&&{start:h.getRangeStart(g),end:h.getRangeEnd(g),source:d(h.getRangeSource(g))}||null},d=function(g){return g&&{normalizedPath:h.getSourceNormalizedPath(g)}||null};var u=b,f=d;o({message:h.getDiagnosticMessage(p),code:h.getDiagnosticCode(p),category:h.getDiagnosticCategory(p),range:b(h.getDiagnosticRange(p)),relatedRange:b(h.getDiagnosticRelatedRange(p))})}h.isError(p)&&++r}while(!0);return r}var Cn=class{readCount=0;writeCount=0;parseTime=0;parseCount=0;initializeTime=0;initializeCount=0;compileTime=0;compileCount=0;emitTime=0;emitCount=0;validateTime=0;validateCount=0;optimizeTime=0;optimizeCount=0;transformTime=0;transformCount=0;begin(){return M.hrtime()}end(t){let n=M.hrtime(t);return n[0]*1e9+n[1]}toString(){let t=m=>m?`${(m/1e6).toFixed(3)} ms`:"n/a",n=Object.keys(this).filter(m=>m.endsWith("Time")).map(m=>m.substring(0,m.length-4)),o=n.map(m=>t(this[`${m}Time`])),s=n.map(m=>this[`${m}Count`].toString()),r=n.reduce((m,i)=>Math.max(i.length,m),0),u=o.reduce((m,i)=>Math.max(i.length,m),0),f=s.reduce((m,i)=>Math.max(i.length,m),0),p=r+u+f+6,b=[];b.push(`\u256D\u2500${"\u2500".repeat(p)}\u2500\u256E${E}`);let d="Stats";b.push(`\u2502 ${d}${" ".repeat(p-d.length)} \u2502${E}`),b.push(`\u255E\u2550${"\u2550".repeat(r)}\u2550\u2564\u2550${"\u2550".repeat(u)}\u2550\u2564\u2550${"\u2550".repeat(f)}\u2550\u2561${E}`);for(let m=0,i=n.length;m<i;++m)b.push(`\u2502 ${n[m].padEnd(r)} \u2502 ${o[m].padStart(u)} \u2502 ${s[m].padStart(f)} \u2502${E}`);b.push(`\u251C\u2500${"\u2500".repeat(r)}\u2500\u2534\u2500${"\u2500".repeat(u)}\u2500\u2534\u2500${"\u2500".repeat(f)}\u2500\u2524${E}`);let g=`Took ${t(this.total)}`;b.push(`\u2502 ${g}${" ".repeat(p-g.length)} \u2502${E}`);let y=`${this.readCount} reads, ${this.writeCount} writes`;return b.push(`\u2502 ${y}${" ".repeat(p-y.length)} \u2502${E}`),b.push(`\u2570\u2500${"\u2500".repeat(p)}\u2500\u256F${E}`),b.join("")}},ze=typeof global<"u"&&global.Buffer?global.Buffer.allocUnsafe||(e=>new global.Buffer(e)):e=>new Uint8Array(e);function Xn(e){let t=[];return t.write=function(n){if(e&&e(n),typeof n=="string"){let o=ze(Tn.length(n));Tn.write(n,o,0),n=o}this.push(n)},t.reset=function(){t.length=0},t.toBuffer=function(){let n=0,o=0,s=this.length;for(;o<s;)n+=this[o++].length;let r=ze(n);for(n=o=0;o<s;)r.set(this[o],n),n+=this[o].length,++o;return r},t.toString=function(){let n=this.toBuffer();return Tn.read(n,0,n.length)},t}var Bt={alwaysStrict:!0,strictNullChecks:!0,noImplicitAny:!0,noImplicitReturns:!0,noImplicitThis:!0,noEmitOnError:!0,noPropertyAccessFromIndexSignature:!0,experimentalDecorators:!0,target:"esnext",noLib:!0,types:[],allowJs:!1};export{Cn as Stats,gn as checkDiagnostics,wt as compileString,qn as configToArguments,Xn as createMemoryStream,Wn as default,Se as defaultOptimizeLevel,we as defaultShrinkLevel,St as definitionFiles,H as libraryFiles,P as libraryPrefix,Be as main,zt as options,Bt as tscOptions,Hn as version};
29462
+ `,Gn=Xn?"\\":"/",_=".ts",_t=`.d${_}`,hn=new RegExp("\\"+_+"$"),Tt=new RegExp("^(?!.*\\.d\\"+_+"$).*\\"+_+"$");function Te(e){return e.replace(/-/g,"_").toUpperCase()}function Ct(e){return typeof e=="string"&&e!==""}var Hn=Fe,zt=Y,P=Ee,H=Ae,St=_e,Se=3,we=0;function qn(e,t=[]){return Object.keys(e||{}).forEach(n=>{let o=e[n],s=Y[n];s&&s.type==="b"?o&&t.push(`--${n}`):Array.isArray(o)?o.forEach(r=>{t.push(`--${n}`,String(r))}):t.push(`--${n}`,String(o))}),t}async function wt(e,t={}){typeof e=="string"&&(e={[`input${_}`]:e});let n=["--outFile","binary","--textFile","text"];qn(t,n);let o={},s=await Be(n.concat(Object.keys(e)),{readFile:r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:null,writeFile:(r,u)=>{o[r]=u},listFiles:()=>[]});return Object.assign(s,o)}async function Be(e,t){Array.isArray(e)||(e=qn(e)),t||(t={});let n=t.stats||new Cn,o=n.begin(),s=0,r=0,u=0,f=(Hn||"").split(".");f.length===3&&(r=parseInt(f[0])|0,s=parseInt(f[1])|0,u=parseInt(f[2])|0);let x=t.stdout||Kn(),b=t.stderr||Kn(),d=t.readFile||ee,g=t.writeFile||te,y=t.listFiles||ie,m=ye(e,Y,!1),i=m.options;e=m.arguments;let zn=new en(x),G=new en(b);i.noColors&&(zn.enabled=!1,G.enabled=!1);let Yn=m.unknown;Yn.length&&Yn.forEach(a=>{b.write(`${G.yellow("WARNING ")}Unknown option '${a}'${E}`)});let Jn=m.trailing;Jn.length&&b.write(`${G.yellow("WARNING ")}Unsupported trailing arguments: ${Jn.join(" ")}${E}`);let K=null,R=null,z=(a,l={})=>(a&&b.write(`${G.red("FAILURE ")}${a.stack.replace(/^ERROR: /i,"")}${E}`),R&&R.dispose(),n.total||(n.total=n.end(o)),Object.assign({error:a,stdout:x,stderr:b,stats:n},l));if(i.version)return x.write(`Version ${Hn}${E}`),z(null);let w=F.normalize(i.baseDir||"."),X=tn(i.config||"toilconfig.json",w),Sn=F.basename(X),J=F.dirname(X),N=await Ce(Sn,J,d),De=N!=null&&Array.isArray(N.entries)&&N.entries.length;if(i.help||!e.length&&!De){let a=i.help?x:b,l=i.help?zn:G;return a.write([l.white("SYNTAX")," "+l.cyan("toilscript")+" [entryFile ...] [options]","",l.white("EXAMPLES")," "+l.cyan("toilscript")+" hello"+_," "+l.cyan("toilscript")+" hello"+_+" -o hello.wasm -t hello.wat"," "+l.cyan("toilscript")+" hello1"+_+" hello2"+_+" -o -O > hello.wasm"," "+l.cyan("toilscript")+" --config toilconfig.json --target release","",l.white("OPTIONS")].concat(ve(Y,24,E)).join(E)+E),z(null)}if(!(j.promises&&j.promises.readFile)){if(d===ee)throw Error("'options.readFile' must be specified");if(g===te)throw Error("'options.writeFile' must be specified");if(y===ie)throw Error("'options.listFiles' must be specified")}let wn=new Set;wn.add(X);let Ie=i.target||"release";for(;N;){if(N.targets){let l=N.targets[Ie];l&&(i=Un(Y,i,l,J))}let a=N.options;if(a&&(i=Un(Y,i,a,J)),N.entries)for(let l of N.entries)e.push(tn(l,J));if(N.extends){if(X=tn(N.extends,J,!0),Sn=F.basename(X),J=F.dirname(X),wn.has(X))break;wn.add(X),N=await Ce(Sn,J,d)}else break}if(Mn(Y,i),i.showConfig)return b.write(JSON.stringify({options:i,entries:e},null,2)),z(null);function Zn(a){return[...new Set(a)]}let B,rn,mn,T=h.newOptions();switch(i.runtime){case"stub":rn=0;break;case"minimal":rn=1;break;case"memory":rn=3;break;default:rn=2;break}switch(i.uncheckedBehavior){default:mn=0;break;case"never":mn=1;break;case"always":mn=2;break}if(h.setTarget(T,0),h.setDebugInfo(T,!!i.debug),h.setRuntime(T,rn),h.setNoAssert(T,i.noAssert),h.setExportMemory(T,!i.noExportMemory),h.setImportMemory(T,i.importMemory),h.setInitialMemory(T,i.initialMemory>>>0),h.setMaximumMemory(T,i.maximumMemory>>>0),h.setSharedMemory(T,i.sharedMemory),h.setImportTable(T,i.importTable),h.setExportTable(T,i.exportTable),i.exportStart!=null&&h.setExportStart(T,Ct(i.exportStart)?i.exportStart:"_start"),h.setMemoryBase(T,i.memoryBase>>>0),h.setTableBase(T,i.tableBase>>>0),h.setSourceMap(T,i.sourceMap!=null),h.setUncheckedBehavior(T,mn),h.setNoUnsafe(T,i.noUnsafe),h.setPedantic(T,i.pedantic),h.setLowMemoryLimit(T,i.lowMemoryLimit>>>0),h.setExportRuntime(T,i.exportRuntime),h.setBundleVersion(T,r,s,u),!i.stackSize&&rn===2&&(i.stackSize=h.DEFAULT_STACK_SIZE),h.setStackSize(T,i.stackSize),h.setBindingsHint(T,i.bindings&&i.bindings.length>0),i.use){let a=i.use;for(let l=0,c=a.length;l<c;++l){let p=a[l],A=p.indexOf("=");if(A<0)return z(Error(`Global alias '${p}' is invalid.`));let v=p.substring(0,A).trim(),C=p.substring(A+1).trim();if(!v.length)return z(Error(`Global alias '${p}' is invalid.`));h.addGlobalAlias(T,v,C)}}let U;if((U=i.disable)!=null){typeof U=="string"&&(U=U.split(","));for(let a=0,l=U.length;a<l;++a){let c=U[a].trim(),p=h[`FEATURE_${Te(c)}`];if(!p)return z(Error(`Feature '${c}' is unknown.`));h.setFeature(T,p,!1)}}if((U=i.enable)!=null){typeof U=="string"&&(U=U.split(","));for(let a=0,l=U.length;a<l;++a){let c=U[a].trim(),p=h[`FEATURE_${Te(c)}`];if(!p)return z(Error(`Feature '${c}' is unknown.`));h.setFeature(T,p,!0)}}let Z=0,$=0;i.optimize&&(Z=Se,$=we),typeof i.optimizeLevel=="number"&&(Z=i.optimizeLevel),typeof i.shrinkLevel=="number"&&($=i.shrinkLevel),Z=Math.min(Math.max(Z,0),3),$=Math.min(Math.max($,0),2),h.setOptimizeLevelHints(T,Z,$),B=h.newProgram(T);let an=[];if(Array.isArray(t.transforms)&&an.push(...t.transforms),i.transform){let a=Zn(i.transform);for(let l=0,c=a.length;l<c;++l){let p=a[l].trim(),A,v;if(Vn.resolve)try{A=Vn.resolve(p,{paths:[M.cwd(),w]}),v=await import(dn.pathToFileURL(A)),v.default&&(v=v.default)}catch(C){try{v=Vn(A)}catch{return z(C)}}else try{v=await import(new URL(p,import.meta.url)),v.default&&(v=v.default)}catch(C){return z(C)}if(!v||typeof v!="function"&&typeof v!="object")return z(Error("not a transform: "+a[l]));an.push(v)}}try{an=an.map(a=>(typeof a=="function"&&(Object.assign(a.prototype,{program:B,binaryen:xn,baseDir:w,stdout:x,stderr:b,log:console.error,readFile:d,writeFile:g,listFiles:y}),a=new a),a))}catch(a){return z(a)}async function Bn(a,...l){for(let c=0,p=an.length;c<p;++c){let A=an[c];if(typeof A[a]=="function")try{let v=n.begin();n.transformCount++,await A[a](...l),n.transformTime+=n.end(v)}catch(v){return v}}}Object.keys(H).forEach(a=>{if(a.includes("/"))return;let l=n.begin();n.parseCount++,h.parse(B,H[a],P+a+_,!1),n.parseTime+=n.end(l)});let on=[];if(i.lib){let a=i.lib;typeof a=="string"&&(a=a.split(",")),on.push(...a.map(l=>l.trim())),on=Zn(on);for(let l=0,c=on.length;l<c;++l){let p=on[l],A;p.endsWith(_)?(A=[F.basename(p)],p=F.dirname(p)):A=await y(p,w)||[];for(let v of A){let C=await d(v,p);if(C==null)return z(Error(`Library file '${v}' not found.`));H[v.replace(hn,"")]=C;let O=n.begin();n.parseCount++,h.parse(B,C,P+v,!1),n.parseTime+=n.end(O)}}}i.path=i.path||[];let bn=new Map;async function Oe(a,l){let c=null,p=null;if(!a.startsWith(P))(c=await d(p=a+_,w))==null&&(c=await d(p=a+"/index"+_,w))==null&&(p=a+_,c=await d(a+_t,w));else{let A=a.substring(P.length),v=`${A}/index`;if(Object.prototype.hasOwnProperty.call(H,A))c=H[A],p=P+A+_;else if(Object.prototype.hasOwnProperty.call(H,v))c=H[v],p=P+v+_;else{for(let C of on)if((c=await d(A+_,C))!=null){p=P+A+_;break}else if((c=await d(v+_,C))!=null){p=P+v+_;break}if(c==null){let C=a.match(/^~lib\/((?:@[^/]+\/)?[^/]+)(?:\/(.+))?/);if(C){let O=C[1],q=C[2]||"index",Fn=bn.has(l)?bn.get(l):".",L=[],D=F.resolve(w,Fn).split(Gn);for(let S=D.length,k=Xn?1:0;S>=k;--S)D[S-1]!=="node_modules"&&L.push(`${D.slice(0,S).join(Gn)}${Gn}node_modules`);L.push(...i.path);for(let S of L.map(k=>F.relative(w,k))){let k=q;if((c=await d(F.join(S,O,k+_),w))!=null){p=`${P}${O}/${k}${_}`,bn.set(p.replace(hn,""),F.join(S,O));break}let un=`${q}/index`;if((c=await d(F.join(S,O,un+_),w))!=null){p=`${P}${O}/${un}${_}`,bn.set(p.replace(hn,""),F.join(S,O));break}}}}}}return c==null?null:{sourceText:c,sourcePath:p}}function Le(a=[]){do{let l=h.nextFile(B);if(l==null)break;a.push(l)}while(!0);return a}async function $n(){let a;for(;(a=Le()).length;){let c=[];for(let p of a){let A=h.getDependee(B,p);c.push(Oe(p,A))}c=await Promise.all(c);for(let p=0,A=a.length;p<A;++p){let v=a[p],C=c[p],O=n.begin();n.parseCount++,C?h.parse(B,C.sourceText,C.sourcePath,!1):h.parse(B,null,v+_,!1),n.parseTime+=n.end(O)}}let l=gn(B,b,i.disableWarning,t.reportDiagnostic,G.enabled);if(l){let c=Error(`${l} parse error(s)`);return c.stack=c.message,z(c)}}{let a=String(i.runtime),l=`rt/index-${a}`,c=H[l];if(c==null){if(l=a,c=await d(l+_,w),c==null)return z(Error(`Runtime '${F.resolve(w,l+_)}' is not found.`))}else l=`~lib/${l}`;let p=n.begin();n.parseCount++,h.parse(B,c,l+_,!0),n.parseTime+=n.end(p)}for(let a=0,l=e.length;a<l;++a){let c=String(e[a]),p=F.isAbsolute(c)?F.relative(w,c):F.normalize(c);p=p.replace(/\\/g,"/").replace(hn,"").replace(/\/$/,"");let A=await d(p+_,w);if(A==null){let C=`${p}/index${_}`;A=await d(C,w),A!=null?p=C:p+=_}else p+=_;let v=n.begin();n.parseCount++,h.parse(B,A,p,!0),n.parseTime+=n.end(v)}{let a=await $n();if(a)return a}{let a=await Bn("afterParse",B.parser);if(a)return z(a)}{let a=await $n();if(a)return a}{let a=n.begin();n.initializeCount++;try{h.initializeProgram(B)}catch(l){I("initialize",l)}n.initializeTime+=n.end(a)}{let a=await Bn("afterInitialize",B);if(a)return z(a)}{let a=n.begin();n.compileCount++;try{K=h.compile(B)}catch(l){let c=gn(B,b,i.disableWarning,t.reportDiagnostic,G.enabled);if(c){let p=Error(`${c} compile error(s)`);return p.stack=p.message,z(p)}I("compile",l)}n.compileTime+=n.end(a)}R=xn.wrapModule(typeof K=="number"||K instanceof Number?h.getBinaryenModuleRef(K):K.ref);let ln=gn(B,b,i.disableWarning,t.reportDiagnostic,G.enabled);if(ln){let a=Error(`${ln} compile error(s)`);return a.stack=a.message,z(a)}{let a=await Bn("afterCompile",R);if(a)return z(a)}if(ln=gn(B,b,i.disableWarning,t.reportDiagnostic,G.enabled),ln){let a=Error(`${ln} afterCompile error(s)`);return a.stack=a.message,z(a)}if(!i.noValidate){let a=n.begin();n.validateCount++;let l=h.validate(K);if(n.validateTime+=n.end(a),!l)return z(Error("validate error"))}if(i.trapMode==="clamp"||i.trapMode==="js"){let a=n.begin();try{R.runPasses([`trap-mode-${i.trapMode}`])}catch(l){I("runPasses",l)}n.compileTime+=n.end(a)}else if(i.trapMode!=="allow")return z(Error("Unsupported trap mode"));let Qn=i.debug,ke=i.converge,ne=i.importMemory?i.zeroFilledMemory:!1,yn=[];i.runPasses&&(typeof i.runPasses=="string"&&(i.runPasses=i.runPasses.split(",")),i.runPasses.length&&i.runPasses.forEach(a=>{yn.includes(a=a.trim())||yn.push(a)}));{let a=n.begin();try{n.optimizeCount++,h.optimize(K,Z,$,Qn,ne)}catch(l){I("optimize",l)}try{R.runPasses(yn)}catch(l){I("runPasses",l)}if(ke){let l;try{let c=n.begin();n.emitCount++,l=R.emitBinary(),n.emitTime+=n.end(c)}catch(c){I("emitBinary (converge)",c)}do{try{n.optimizeCount++,h.optimize(K,Z,$,Qn,ne)}catch(p){I("optimize (converge)",p)}try{R.runPasses(yn)}catch(p){I("runPasses (converge)",p)}let c;try{let p=n.begin();n.emitCount++,c=R.emitBinary(),n.emitTime+=n.end(p)}catch(p){I("emitBinary (converge)",p)}if(c.length>=l.length){c.length>l.length&&b.write(`Last converge was suboptimal.${E}`);break}l=c}while(!0)}n.optimizeTime+=n.end(a)}let Q=[];if(!i.noEmit){if(i.binaryFile)return z(Error("Usage of the --binaryFile compiler option is no longer supported. Use --outFile instead."));let a=i.bindings||[],l=!1,c=i.outFile!=null,p=i.textFile!=null,A=c||p,v=c&&i.outFile.length>0||p&&i.textFile.length>0,C=v?(i.outFile||i.textFile).replace(/\.\w+$/,""):null,O=v?F.basename(C):"output";if(h.setBasenameHint(T,O),i.outFile!=null){let L=i.sourceMap!=null?i.sourceMap.length?i.sourceMap:`./${O}.wasm.map`:null,D=n.begin();n.emitCount++;let S;try{S=R.emitBinary(L)}catch(k){I("emitBinary",k)}if(n.emitTime+=n.end(D),i.outFile.length?Q.push(g(i.outFile,S.binary,w)):(l=!0,vn(S.binary)),S.sourceMap!="")if(i.outFile.length){let k=JSON.parse(S.sourceMap);k.sourceRoot=`./${O}`;let un=[];for(let En=0,Re=k.sources.length;En<Re;++En){let re=k.sources[En],ae=h.getSource(B,re.replace(hn,""));if(ae==null)return z(Error(`Source of file '${re}' not found.`));un[En]=ae}k.sourcesContent=un,Q.push(g(F.join(F.dirname(i.outFile),F.basename(L)).replace(/^\.\//,""),JSON.stringify(k),w))}else b.write(`Skipped source map (no output path)${E}`)}if(i.textFile!=null||!A){let L=n.begin();n.emitCount++;let D;try{xn.setOptimizeStackIR(!0),D=i.textFile?.endsWith(".wast")?R.emitText():R.emitStackIR()}catch(S){I("emitText",S)}n.emitTime+=n.end(L),i.textFile!=null&&i.textFile.length?Q.push(g(i.textFile,D,w)):l||vn(D)}let q=a.includes("esm"),Fn=!q&&a.includes("raw");if(q||Fn)if(C){let L=n.begin();n.emitCount++;let D;try{D=h.buildTSD(B,q)}catch(S){I("buildTSD",S)}n.emitTime+=n.end(L),Q.push(g(C+".d.ts",D,w))}else b.write(`Skipped TypeScript binding (no output path)${E}`);if(q||Fn)if(C){let L=n.begin();n.emitCount++;let D;try{D=h.buildJS(B,q)}catch(S){I("buildJS",S)}n.emitTime+=n.end(L),Q.push(g(C+".js",D,w))}else b.write(`Skipped JavaScript binding (no output path)${E}`);if(i.rpcModule!=null&&i.rpcModule.length){let L=n.begin();n.emitCount++;let D;try{D=h.buildServerModule(B,i.rpcRuntime||"toiljs/io")}catch(S){I("buildServerModule",S)}n.emitTime+=n.end(L),D!=null&&Q.push(g(i.rpcModule,D,w))}}try{await Promise.all(Q)}catch(a){return z(a)}return n.total=n.end(o),i.stats&&b.write(n.toString()),z(null);async function ee(a,l){let c=F.resolve(l,a);try{return n.readCount++,await j.promises.readFile(c,"utf8")}catch{return null}}async function te(a,l,c){try{n.writeCount++;let p=F.resolve(c,F.dirname(a)),A=F.join(p,F.basename(a));return await j.promises.mkdir(p,{recursive:!0}),await j.promises.writeFile(A,l),!0}catch{return!1}}async function ie(a,l){try{return n.readCount++,(await j.promises.readdir(F.join(l,a))).filter(c=>Tt.test(c))}catch{return null}}function vn(a){vn.used||(vn.used=!0,n.writeCount++),x.write(a)}function I(a,l){let c=zn.red("\u258C ");console.error([E,c,"Whoops, the ToilScript compiler has crashed during ",a," :-(",E,c,E,(typeof l.stack=="string"?[c,"Here is the stack trace hinting at the problem, perhaps it's useful?",E,c,E,l.stack.replace(/^/mg,c),E]:[c,"There is no stack trace. Perhaps a Binaryen exception above / in console?",E,c,E,c,"> "+l.stack,E]).join(""),c,E,c,"If you see where the error is, feel free to send us a pull request. If not,",E,c,"please let us know: https://github.com/dacely-cloud/toilscript/issues",E,c,E,c,"Thank you!",E].join("")),M.exit(1)}}function jn(e){return Object.prototype.toString.call(e)==="[object Object]"}async function Ce(e,t,n){let o=await n(e,t),s=F.join(t,e);if(!o)return null;let r;try{r=JSON.parse(o)}catch(u){throw new Error(`Toilconfig is not valid json: ${s}`,{cause:u})}if(r.options&&!jn(r.options))throw new Error(`Toilconfig.options is not an object: ${s}`);if(r.include&&!Array.isArray(r.include))throw new Error(`Toilconfig.include is not an array: ${s}`);if(r.targets){if(!jn(r.targets))throw new Error(`Toilconfig.targets is not an object: ${s}`);let u=Object.keys(r.targets);for(let f=0;f<u.length;f++){let x=u[f];if(!jn(r.targets[x]))throw new Error(`Toilconfig.targets.${x} is not an object: ${s}`)}}if(r.extends&&typeof r.extends!="string")throw new Error(`Toilconfig.extends is not a string: ${s}`);return r}function gn(e,t,n,o,s){typeof s>"u"&&t&&(s=t.isTTY);let r=0;do{let x=h.nextDiagnostic(e);if(!x)break;if(t){let b=d=>{if(n==null)return!1;if(!n.length)return!0;let g=h.getDiagnosticCode(d);return n.includes(g)};(h.isError(x)||!b(x))&&t.write(h.formatDiagnostic(x,s,!0)+E+E)}if(o){let b=function(g){return g&&{start:h.getRangeStart(g),end:h.getRangeEnd(g),source:d(h.getRangeSource(g))}||null},d=function(g){return g&&{normalizedPath:h.getSourceNormalizedPath(g)}||null};var u=b,f=d;o({message:h.getDiagnosticMessage(x),code:h.getDiagnosticCode(x),category:h.getDiagnosticCategory(x),range:b(h.getDiagnosticRange(x)),relatedRange:b(h.getDiagnosticRelatedRange(x))})}h.isError(x)&&++r}while(!0);return r}var Cn=class{readCount=0;writeCount=0;parseTime=0;parseCount=0;initializeTime=0;initializeCount=0;compileTime=0;compileCount=0;emitTime=0;emitCount=0;validateTime=0;validateCount=0;optimizeTime=0;optimizeCount=0;transformTime=0;transformCount=0;begin(){return M.hrtime()}end(t){let n=M.hrtime(t);return n[0]*1e9+n[1]}toString(){let t=m=>m?`${(m/1e6).toFixed(3)} ms`:"n/a",n=Object.keys(this).filter(m=>m.endsWith("Time")).map(m=>m.substring(0,m.length-4)),o=n.map(m=>t(this[`${m}Time`])),s=n.map(m=>this[`${m}Count`].toString()),r=n.reduce((m,i)=>Math.max(i.length,m),0),u=o.reduce((m,i)=>Math.max(i.length,m),0),f=s.reduce((m,i)=>Math.max(i.length,m),0),x=r+u+f+6,b=[];b.push(`\u256D\u2500${"\u2500".repeat(x)}\u2500\u256E${E}`);let d="Stats";b.push(`\u2502 ${d}${" ".repeat(x-d.length)} \u2502${E}`),b.push(`\u255E\u2550${"\u2550".repeat(r)}\u2550\u2564\u2550${"\u2550".repeat(u)}\u2550\u2564\u2550${"\u2550".repeat(f)}\u2550\u2561${E}`);for(let m=0,i=n.length;m<i;++m)b.push(`\u2502 ${n[m].padEnd(r)} \u2502 ${o[m].padStart(u)} \u2502 ${s[m].padStart(f)} \u2502${E}`);b.push(`\u251C\u2500${"\u2500".repeat(r)}\u2500\u2534\u2500${"\u2500".repeat(u)}\u2500\u2534\u2500${"\u2500".repeat(f)}\u2500\u2524${E}`);let g=`Took ${t(this.total)}`;b.push(`\u2502 ${g}${" ".repeat(x-g.length)} \u2502${E}`);let y=`${this.readCount} reads, ${this.writeCount} writes`;return b.push(`\u2502 ${y}${" ".repeat(x-y.length)} \u2502${E}`),b.push(`\u2570\u2500${"\u2500".repeat(x)}\u2500\u256F${E}`),b.join("")}},ze=typeof global<"u"&&global.Buffer?global.Buffer.allocUnsafe||(e=>new global.Buffer(e)):e=>new Uint8Array(e);function Kn(e){let t=[];return t.write=function(n){if(e&&e(n),typeof n=="string"){let o=ze(Tn.length(n));Tn.write(n,o,0),n=o}this.push(n)},t.reset=function(){t.length=0},t.toBuffer=function(){let n=0,o=0,s=this.length;for(;o<s;)n+=this[o++].length;let r=ze(n);for(n=o=0;o<s;)r.set(this[o],n),n+=this[o].length,++o;return r},t.toString=function(){let n=this.toBuffer();return Tn.read(n,0,n.length)},t}var Bt={alwaysStrict:!0,strictNullChecks:!0,noImplicitAny:!0,noImplicitReturns:!0,noImplicitThis:!0,noEmitOnError:!0,noPropertyAccessFromIndexSignature:!0,experimentalDecorators:!0,target:"esnext",noLib:!0,types:[],allowJs:!1};export{Cn as Stats,gn as checkDiagnostics,wt as compileString,qn as configToArguments,Kn as createMemoryStream,Wn as default,Se as defaultOptimizeLevel,we as defaultShrinkLevel,St as definitionFiles,H as libraryFiles,P as libraryPrefix,Be as main,zt as options,Bt as tscOptions,Hn as version};
28638
29463
  //# sourceMappingURL=cli.js.map