toilscript 0.1.27 → 0.1.29

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:()=>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.27",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:()=>he,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 h=n.lastIndexOf("/");if(h!==n.length-1){h===-1?(n="",o=0):(n=n.slice(0,h),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 he(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?".":he(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,h=s<f?s:f,b=-1,d=0;d<=h;++d){if(d===h){if(f>h){if(t.charCodeAt(r+d)===47)return t.slice(r+d+1);if(d===0)return t.slice(r+d)}else s>h&&(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 h=e.charCodeAt(r);if(h===47){if(!s){n=r+1;break}}else f===-1&&(s=!1,f=r+1),u>=0&&(h===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,h=!0,b=e.length-1,d=0;b>=s;--b){if(n=e.charCodeAt(b),n===47){if(!h){u=b+1;break}continue}f===-1&&(h=!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 xe={};nn(xe,{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(),xe)));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",ht="\x1B[95m",xt="\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?ht+t+W:t}cyan(t){return this.enabled?xt+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 h=0,b=(e=e.slice()).length;h<b;++h){let d=e[h];if(d=="--"){++h;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[h--]=g[2])):g[3]!=null&&(y=t[m=g[3].substring(2)],y&&g[4]!=null&&(e[h--]=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(h+1<e.length&&e[h+1].charCodeAt(0)!=45)switch(y.type){case"i":o[m]=parseInt(e[++h],10);break;case"I":o[m]=(o[m]||[]).concat(parseInt(e[++h],10));break;case"f":o[m]=parseFloat(e[++h]);break;case"F":o[m]=(o[m]||[]).concat(parseFloat(e[++h]));break;case"s":o[m]=String(e[++h]);break;case"S":o[m]=(o[m]||[]).concat(e[++h].split(","));break;default:s.push(d),--h}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(;h<b;)u.push(e[h++]);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=[],h=!1;return Object.keys(r).forEach(b=>{h=!0,f.push(s+" "+_n.gray(b)+s),f.push(r[b].join(s))}),h&&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:h,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;h&&(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 h&&(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;h&&(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.29",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";
@@ -4582,6 +4582,236 @@ export declare namespace performance {
4582
4582
  @external("env", "process.exit")
4583
4583
  export function exit(code: i32): void;
4584
4584
  }
4585
+ `,"bindings/toildb":`// Host-import declarations for the ToilDB data API. The production edge
4586
+ // (toil-backend \`src/wasm/host/import_functions/db\`) and the toiljs dev server
4587
+ // both provide these under the \`env\` namespace. All byte regions are passed as
4588
+ // a (pointer, length) pair into guest linear memory.
4589
+ //
4590
+ // Collections are resolved by name ONCE at module init (\`resolveCollection\`),
4591
+ // which returns an opaque numeric handle; request-time ops pass the handle.
4592
+ //
4593
+ // Return convention (see toildb/ABI.md):
4594
+ // >= 0 success: a length (a value stashed for \`takeResult\`), a count, a
4595
+ // boolean (0/1), a tag, or 0 (ok).
4596
+ // -1 output buffer too small (retry \`takeResult\` with a bigger buffer).
4597
+ // -2 absent (a normal null / not-found).
4598
+ // <= -1000 a typed failure; the diagnostic is TDL(|v| - 1000).
4599
+ //
4600
+ // Variable-length results (a fetched value, a patched record, a claim owner)
4601
+ // use the two-step pull: the op returns the stashed length, then the guest
4602
+ // allocates a buffer and calls \`takeResult\` to copy the bytes out.
4603
+ //
4604
+ // \`idemPtr\` is 0 for none, otherwise a pointer to a 16-byte idempotency key.
4605
+ //
4606
+ // This is the guest half of the ABI contract; the byte framing of keys/values
4607
+ // is the \`@data\` binary codec (\`DataWriter\`/\`DataReader\`).
4608
+
4609
+ export namespace toildbHost {
4610
+ // Resolve a collection by its "<db>/<collection>" name; writes the u32 handle
4611
+ // to outHandlePtr. Returns 0 on success or a negative TDL code.
4612
+ // @ts-ignore: decorator
4613
+ @external("env", "data.resolve_collection")
4614
+ export declare function resolveCollection(namePtr: usize, nameLen: i32, outHandlePtr: usize): i32;
4615
+
4616
+ // record.get -> value length (stashed) | -2 absent | negative error.
4617
+ // @ts-ignore: decorator
4618
+ @external("env", "data.get")
4619
+ export declare function get(handle: u32, keyPtr: usize, keyLen: i32): i32;
4620
+
4621
+ // record bounded multi-get. Input at keysPtr: u32 count + per key (u32 len +
4622
+ // bytes). Result (stashed): u32 count + per item u8 present (+ u32 len + bytes
4623
+ // when present), in request order. Returns the stashed length | negative error.
4624
+ // @ts-ignore: decorator
4625
+ @external("env", "data.get_many")
4626
+ export declare function getMany(handle: u32, keysPtr: usize, keysLen: i32): i32;
4627
+
4628
+ // record.exists -> 1 | 0 | negative error.
4629
+ // @ts-ignore: decorator
4630
+ @external("env", "data.exists")
4631
+ export declare function exists(handle: u32, keyPtr: usize, keyLen: i32): i32;
4632
+
4633
+ // record.create -> 0 ok | AlreadyExists/typed code.
4634
+ // @ts-ignore: decorator
4635
+ @external("env", "data.create")
4636
+ export declare function create(
4637
+ handle: u32,
4638
+ keyPtr: usize,
4639
+ keyLen: i32,
4640
+ valPtr: usize,
4641
+ valLen: i32,
4642
+ idemPtr: usize
4643
+ ): i32;
4644
+
4645
+ // record.patch -> length of the new record (stashed) | negative error.
4646
+ // @ts-ignore: decorator
4647
+ @external("env", "data.patch")
4648
+ export declare function patch(
4649
+ handle: u32,
4650
+ keyPtr: usize,
4651
+ keyLen: i32,
4652
+ patchPtr: usize,
4653
+ patchLen: i32,
4654
+ idemPtr: usize
4655
+ ): i32;
4656
+
4657
+ // record.delete -> 0 ok | negative error.
4658
+ // @ts-ignore: decorator
4659
+ @external("env", "data.delete")
4660
+ export declare function del(handle: u32, keyPtr: usize, keyLen: i32, idemPtr: usize): i32;
4661
+
4662
+ // record consume-once fetch-and-delete -> prior value length (stashed) | -2.
4663
+ // @ts-ignore: decorator
4664
+ @external("env", "data.get_delete")
4665
+ export declare function getDelete(handle: u32, keyPtr: usize, keyLen: i32, idemPtr: usize): i32;
4666
+
4667
+ // unique.lookup -> owner value length (stashed) | -2 absent.
4668
+ // @ts-ignore: decorator
4669
+ @external("env", "data.unique_lookup")
4670
+ export declare function uniqueLookup(handle: u32, keyPtr: usize, keyLen: i32): i32;
4671
+
4672
+ // unique.claim -> 0 Claimed | 1 AlreadyClaimed (owner stashed) | 2 owned-by-caller | neg.
4673
+ // @ts-ignore: decorator
4674
+ @external("env", "data.unique_claim")
4675
+ export declare function uniqueClaim(
4676
+ handle: u32,
4677
+ keyPtr: usize,
4678
+ keyLen: i32,
4679
+ valPtr: usize,
4680
+ valLen: i32,
4681
+ idemPtr: usize
4682
+ ): i32;
4683
+
4684
+ // unique.release -> 0 ok | neg (Conflict if not the owner).
4685
+ // @ts-ignore: decorator
4686
+ @external("env", "data.unique_release")
4687
+ export declare function uniqueRelease(
4688
+ handle: u32,
4689
+ keyPtr: usize,
4690
+ keyLen: i32,
4691
+ valPtr: usize,
4692
+ valLen: i32,
4693
+ idemPtr: usize
4694
+ ): i32;
4695
+
4696
+ // view.get -> view value length (stashed) | -2 absent | negative error.
4697
+ // @ts-ignore: decorator
4698
+ @external("env", "data.view_get")
4699
+ export declare function viewGet(handle: u32, keyPtr: usize, keyLen: i32): i32;
4700
+
4701
+ // view.publish -> 0 ok | negative error (derive/job only; the host gate enforces).
4702
+ // @ts-ignore: decorator
4703
+ @external("env", "data.view_publish")
4704
+ export declare function viewPublish(
4705
+ handle: u32,
4706
+ keyPtr: usize,
4707
+ keyLen: i32,
4708
+ valPtr: usize,
4709
+ valLen: i32,
4710
+ idemPtr: usize
4711
+ ): i32;
4712
+
4713
+ // membership.contains -> 1 present | 0 absent | negative error.
4714
+ // @ts-ignore: decorator
4715
+ @external("env", "data.membership_contains")
4716
+ export declare function membershipContains(
4717
+ handle: u32, setPtr: usize, setLen: i32, memberPtr: usize, memberLen: i32
4718
+ ): i32;
4719
+
4720
+ // membership.add -> 0 ok | negative error.
4721
+ // @ts-ignore: decorator
4722
+ @external("env", "data.membership_add")
4723
+ export declare function membershipAdd(
4724
+ handle: u32, setPtr: usize, setLen: i32, memberPtr: usize, memberLen: i32, idemPtr: usize
4725
+ ): i32;
4726
+
4727
+ // membership.remove -> 0 ok | negative error.
4728
+ // @ts-ignore: decorator
4729
+ @external("env", "data.membership_remove")
4730
+ export declare function membershipRemove(
4731
+ handle: u32, setPtr: usize, setLen: i32, memberPtr: usize, memberLen: i32, idemPtr: usize
4732
+ ): i32;
4733
+
4734
+ // membership.list(limit) -> framed-list length (stashed) | negative error.
4735
+ // The blob is \`u32 count\` then per member \`u32 len + bytes\`.
4736
+ // @ts-ignore: decorator
4737
+ @external("env", "data.membership_list")
4738
+ export declare function membershipList(handle: u32, setPtr: usize, setLen: i32, limit: i32): i32;
4739
+
4740
+ // capacity.set_total(total: i64) -> 0 ok | negative error (job/derive only).
4741
+ // @ts-ignore: decorator
4742
+ @external("env", "data.capacity_set_total")
4743
+ export declare function capacitySetTotal(
4744
+ handle: u32, keyPtr: usize, keyLen: i32, total: i64, idemPtr: usize
4745
+ ): i32;
4746
+
4747
+ // capacity.available -> 8 (the i64 available stashed as 8 LE bytes) | neg.
4748
+ // @ts-ignore: decorator
4749
+ @external("env", "data.capacity_available")
4750
+ export declare function capacityAvailable(handle: u32, keyPtr: usize, keyLen: i32): i32;
4751
+
4752
+ // capacity.reserve(amount: i64, ttl_ms: i64) -> 8 (the u64 reservation id
4753
+ // stashed) | -2 insufficient | negative error.
4754
+ // @ts-ignore: decorator
4755
+ @external("env", "data.capacity_reserve")
4756
+ export declare function capacityReserve(
4757
+ handle: u32, keyPtr: usize, keyLen: i32, amount: i64, ttlMs: i64, idemPtr: usize
4758
+ ): i32;
4759
+
4760
+ // capacity.confirm(reservationId: i64) -> 1 confirmed | 0 unknown | neg.
4761
+ // @ts-ignore: decorator
4762
+ @external("env", "data.capacity_confirm")
4763
+ export declare function capacityConfirm(
4764
+ handle: u32, keyPtr: usize, keyLen: i32, reservationId: i64, idemPtr: usize
4765
+ ): i32;
4766
+
4767
+ // capacity.cancel(reservationId: i64) -> 1 cancelled | 0 unknown/confirmed | neg.
4768
+ // @ts-ignore: decorator
4769
+ @external("env", "data.capacity_cancel")
4770
+ export declare function capacityCancel(
4771
+ handle: u32, keyPtr: usize, keyLen: i32, reservationId: i64, idemPtr: usize
4772
+ ): i32;
4773
+
4774
+ // counter.get -> 8 (the i64 sum stashed as 8 LE bytes) | negative error.
4775
+ // @ts-ignore: decorator
4776
+ @external("env", "data.counter_get")
4777
+ export declare function counterGet(handle: u32, keyPtr: usize, keyLen: i32): i32;
4778
+
4779
+ // counter.add(delta: i64) -> 0 ok | negative error.
4780
+ // @ts-ignore: decorator
4781
+ @external("env", "data.counter_add")
4782
+ export declare function counterAdd(
4783
+ handle: u32,
4784
+ keyPtr: usize,
4785
+ keyLen: i32,
4786
+ delta: i64,
4787
+ idemPtr: usize
4788
+ ): i32;
4789
+
4790
+ // events.append -> 0 ok | negative error.
4791
+ // @ts-ignore: decorator
4792
+ @external("env", "data.append")
4793
+ export declare function append(
4794
+ handle: u32,
4795
+ keyPtr: usize,
4796
+ keyLen: i32,
4797
+ evPtr: usize,
4798
+ evLen: i32,
4799
+ idemPtr: usize
4800
+ ): i32;
4801
+
4802
+ // events.latest(limit) -> framed-list length (stashed) | negative error.
4803
+ // The blob is \`u32 count\` then per event \`u32 len + bytes\`, newest first.
4804
+ // @ts-ignore: decorator
4805
+ @external("env", "data.latest")
4806
+ export declare function latest(handle: u32, keyPtr: usize, keyLen: i32, limit: i32): i32;
4807
+
4808
+ // Copy the last stashed variable-length result into outPtr (outLen must equal
4809
+ // the length the producing op returned). Returns bytes written, or -1 if the
4810
+ // buffer is too small.
4811
+ // @ts-ignore: decorator
4812
+ @external("env", "data.take_result")
4813
+ export declare function takeResult(outPtr: usize, outLen: i32): i32;
4814
+ }
4585
4815
  `,"bindings/webcrypto":`// Host-import declarations for the Web Crypto surface. The production edge
4586
4816
  // (toil-backend \`src/wasm/host/import_functions/crypto\`) and the toiljs dev
4587
4817
  // server both provide these under the \`env\` namespace. All byte regions are
@@ -7625,7 +7855,16 @@ export namespace console {
7625
7855
 
7626
7856
  import { webcrypto } from "bindings/webcrypto";
7627
7857
  import { SubtleCrypto } from "crypto/subtle";
7628
- import { HmacImportParams, HmacParams, ALG_SHA_256, USAGE_SIGN } from "crypto/algorithms";
7858
+ import {
7859
+ HmacImportParams,
7860
+ HmacParams,
7861
+ ALG_SHA_1,
7862
+ ALG_SHA_256,
7863
+ ALG_SHA_384,
7864
+ ALG_SHA_512,
7865
+ FMT_RAW,
7866
+ USAGE_SIGN,
7867
+ } from "crypto/algorithms";
7629
7868
  import { Encoding } from "encoding";
7630
7869
 
7631
7870
  // Re-export the public surface so guests can import everything from "crypto".
@@ -7665,6 +7904,13 @@ export {
7665
7904
  ALG_X25519,
7666
7905
  ALG_HKDF,
7667
7906
  ALG_PBKDF2,
7907
+ ALG_SHA3_256,
7908
+ ALG_SHA3_384,
7909
+ ALG_SHA3_512,
7910
+ FMT_RAW,
7911
+ FMT_PKCS8,
7912
+ FMT_SPKI,
7913
+ FMT_JWK,
7668
7914
  CURVE_P256,
7669
7915
  CURVE_P384,
7670
7916
  USAGE_ENCRYPT,
@@ -7715,16 +7961,16 @@ export namespace crypto {
7715
7961
 
7716
7962
  // --- Ergonomic digest helpers (thin wrappers over subtle.digest) ----------
7717
7963
  export function sha1(data: Uint8Array): Uint8Array {
7718
- return subtle.digest("SHA-1", data);
7964
+ return subtle.digest(ALG_SHA_1, data);
7719
7965
  }
7720
7966
  export function sha256(data: Uint8Array): Uint8Array {
7721
- return subtle.digest("SHA-256", data);
7967
+ return subtle.digest(ALG_SHA_256, data);
7722
7968
  }
7723
7969
  export function sha384(data: Uint8Array): Uint8Array {
7724
- return subtle.digest("SHA-384", data);
7970
+ return subtle.digest(ALG_SHA_384, data);
7725
7971
  }
7726
7972
  export function sha512(data: Uint8Array): Uint8Array {
7727
- return subtle.digest("SHA-512", data);
7973
+ return subtle.digest(ALG_SHA_512, data);
7728
7974
  }
7729
7975
 
7730
7976
  // String-input variants (UTF-8 encode, then hash).
@@ -7743,7 +7989,7 @@ export namespace crypto {
7743
7989
 
7744
7990
  /// One-shot HMAC-SHA-256 over raw key + message bytes.
7745
7991
  export function hmacSha256(key: Uint8Array, msg: Uint8Array): Uint8Array {
7746
- let k = subtle.importKey("raw", key, new HmacImportParams(ALG_SHA_256), false, USAGE_SIGN);
7992
+ let k = subtle.importKey(FMT_RAW, key, new HmacImportParams(ALG_SHA_256), false, USAGE_SIGN);
7747
7993
  return subtle.sign(new HmacParams(), k, msg);
7748
7994
  }
7749
7995
  export function hmacSha256Text(key: Uint8Array, msg: string): Uint8Array {
@@ -8122,12 +8368,11 @@ import { webcrypto } from "bindings/webcrypto";
8122
8368
  import { CryptoKey } from "crypto/key";
8123
8369
  import {
8124
8370
  AlgorithmParams,
8125
- algId,
8126
- formatId,
8127
8371
  cryptoError,
8128
- FMT_JWK,
8372
+ FMT_RAW,
8129
8373
  FMT_PKCS8,
8130
8374
  FMT_SPKI,
8375
+ FMT_JWK,
8131
8376
  ALG_AES_GCM,
8132
8377
  ALG_AES_CBC,
8133
8378
  ALG_AES_CTR,
@@ -8158,26 +8403,24 @@ function isSymmetricAlg(alg: i32): bool {
8158
8403
  }
8159
8404
 
8160
8405
  export class SubtleCrypto {
8161
- digest(algorithm: string, data: Uint8Array): Uint8Array {
8162
- let id = algId(algorithm);
8163
- if (id == 0) throw new Error("Unrecognized algorithm: " + algorithm);
8164
- return drain(webcrypto.digest(id, data.dataStart, data.byteLength));
8406
+ // \`algorithm\` is a hash-id selector: an \`ALG_SHA_*\` const (NOT a magic string).
8407
+ digest(algorithm: i32, data: Uint8Array): Uint8Array {
8408
+ return drain(webcrypto.digest(algorithm, data.dataStart, data.byteLength));
8165
8409
  }
8166
8410
 
8411
+ // \`format\` is an \`FMT_*\` selector const (FMT_RAW / FMT_PKCS8 / FMT_SPKI).
8167
8412
  importKey(
8168
- format: string,
8413
+ format: i32,
8169
8414
  keyData: Uint8Array,
8170
8415
  algorithm: AlgorithmParams,
8171
8416
  extractable: bool,
8172
8417
  usages: i32
8173
8418
  ): CryptoKey {
8174
- let fmt = formatId(format);
8175
- if (fmt < 0) throw new Error("Unknown key format: " + format);
8176
- if (fmt == FMT_JWK) throw new Error("jwk key format is not supported");
8419
+ if (format == FMT_JWK) throw new Error("jwk key format is not supported");
8177
8420
  let p = algorithm.pack();
8178
8421
  let alg = load<i32>(p.dataStart); // first packed field is the alg id
8179
8422
  let handle = webcrypto.importKey(
8180
- fmt,
8423
+ format,
8181
8424
  keyData.dataStart,
8182
8425
  keyData.byteLength,
8183
8426
  p.dataStart,
@@ -8188,18 +8431,17 @@ export class SubtleCrypto {
8188
8431
  if (handle < 0) throw new Error(cryptoError(handle));
8189
8432
 
8190
8433
  let type: string;
8191
- if (fmt == FMT_PKCS8) type = "private";
8192
- else if (fmt == FMT_SPKI) type = "public";
8434
+ if (format == FMT_PKCS8) type = "private";
8435
+ else if (format == FMT_SPKI) type = "public";
8193
8436
  else type = isSymmetricAlg(alg) ? "secret" : "public";
8194
8437
 
8195
8438
  return new CryptoKey(handle, type, extractable, alg, usages);
8196
8439
  }
8197
8440
 
8198
- exportKey(format: string, key: CryptoKey): Uint8Array {
8199
- let fmt = formatId(format);
8200
- if (fmt < 0) throw new Error("Unknown key format: " + format);
8201
- if (fmt == FMT_JWK) throw new Error("jwk key format is not supported");
8202
- return drain(webcrypto.exportKey(fmt, key.handle));
8441
+ // \`format\` is an \`FMT_*\` selector const (FMT_RAW / FMT_PKCS8 / FMT_SPKI).
8442
+ exportKey(format: i32, key: CryptoKey): Uint8Array {
8443
+ if (format == FMT_JWK) throw new Error("jwk key format is not supported");
8444
+ return drain(webcrypto.exportKey(format, key.handle));
8203
8445
  }
8204
8446
 
8205
8447
  encrypt(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array {
@@ -8261,7 +8503,7 @@ export class SubtleCrypto {
8261
8503
  usages: i32
8262
8504
  ): CryptoKey {
8263
8505
  let bits = this.deriveBits(algorithm, baseKey, lengthBits);
8264
- return this.importKey("raw", bits, derivedKeyAlgorithm, extractable, usages);
8506
+ return this.importKey(FMT_RAW, bits, derivedKeyAlgorithm, extractable, usages);
8265
8507
  }
8266
8508
  }
8267
8509
  `,data:`/**
@@ -18439,6 +18681,438 @@ export namespace table {
18439
18681
  throw new Error(E_NOTIMPLEMENTED);
18440
18682
  }
18441
18683
  }
18684
+ `,toildb:`// ToilDB: the developer-facing edge-database API.
18685
+ //
18686
+ // \`@database class App { @collection(...) users!: Record<User, UserId>; ... }\`
18687
+ // declares logical collections; the compiler (see parser \`injectDatabaseBinding\`)
18688
+ // synthesizes a \`@global App\` singleton whose fields are these typed handles,
18689
+ // resolved to numeric host handles once at module init.
18690
+ //
18691
+ // The handles marshal \`@data\` keys/values to the \`env.data.*\` host imports
18692
+ // (\`bindings/toildb\`). Keys and values are \`@data\` types (they have the injected
18693
+ // \`encode(): Uint8Array\` + \`decodeInto(buf): void\` instance methods). Both
18694
+ // encode and decode go through INSTANCE methods on the generic type parameter,
18695
+ // which AssemblyScript resolves at specialization (it cannot call the \`decode\`
18696
+ // static through a type parameter, but \`instantiate<V>()\` + \`v.decodeInto(buf)\`
18697
+ // works). Value types must be default-constructible.
18698
+
18699
+ import { toildbHost } from "bindings/toildb";
18700
+ import { DataWriter } from "data";
18701
+
18702
+ /// Resolve a \`"<db>/<collection>"\` name to its numeric host handle. Called once
18703
+ /// per collection at module init by the generated \`App\` binding.
18704
+ export function __toildbResolve(name: string): u32 {
18705
+ const nb = Uint8Array.wrap(String.UTF8.encode(name));
18706
+ const out = new Uint8Array(4);
18707
+ toildbHost.resolveCollection(nb.dataStart, nb.byteLength, out.dataStart);
18708
+ return load<u32>(out.dataStart);
18709
+ }
18710
+
18711
+ /// Pull the last stashed variable-length result of \`len\` bytes into a buffer.
18712
+ function __toildbTake(len: i32): Uint8Array {
18713
+ const buf = new Uint8Array(len);
18714
+ toildbHost.takeResult(buf.dataStart, len);
18715
+ return buf;
18716
+ }
18717
+
18718
+ /// Pull a stashed result whose length is NOT known up front (e.g. the owner
18719
+ /// returned by a failed \`claim\`): grow the buffer until \`take_result\` fits.
18720
+ function __toildbTakeGrow(): Uint8Array {
18721
+ let cap = 256;
18722
+ let buf = new Uint8Array(cap);
18723
+ let n = toildbHost.takeResult(buf.dataStart, cap);
18724
+ while (n == -1) {
18725
+ cap = cap * 2;
18726
+ buf = new Uint8Array(cap);
18727
+ n = toildbHost.takeResult(buf.dataStart, cap);
18728
+ }
18729
+ return buf.subarray(0, n);
18730
+ }
18731
+
18732
+ /// A mutable keyed-entity collection (spec 7.1). \`V\` is the \`@data\` value type,
18733
+ /// \`K\` the \`@data\` key type.
18734
+ @global
18735
+ export class Record<V, K> {
18736
+ private __handle: u32;
18737
+
18738
+ constructor(handle: u32) {
18739
+ this.__handle = handle;
18740
+ }
18741
+
18742
+ /// Return the record, or \`null\` if it does not exist.
18743
+ get(key: K): V | null {
18744
+ const kb = key.encode();
18745
+ const status = toildbHost.get(this.__handle, kb.dataStart, kb.byteLength);
18746
+ if (status < 0) return null;
18747
+ const v = instantiate<V>();
18748
+ v.decodeInto(__toildbTake(status));
18749
+ return v;
18750
+ }
18751
+
18752
+ /// Like \`get\`, but traps if the record is absent.
18753
+ require(key: K): V {
18754
+ const v = this.get(key);
18755
+ if (v == null) unreachable();
18756
+ return v!;
18757
+ }
18758
+
18759
+ /// Bounded multi-get: one op, one result per key (in order), each the value
18760
+ /// or \`null\` if absent. The key count is capped by the request budget.
18761
+ getMany(keys: K[]): Array<V | null> {
18762
+ const w = new DataWriter();
18763
+ w.writeU32(<u32>keys.length);
18764
+ for (let i = 0, n = keys.length; i < n; i++) {
18765
+ w.writeBytes(keys[i].encode());
18766
+ }
18767
+ const blob = w.toBytes();
18768
+ const status = toildbHost.getMany(this.__handle, blob.dataStart, blob.byteLength);
18769
+ if (status < 0) unreachable();
18770
+ const out = __toildbTake(status);
18771
+ const results = new Array<V | null>();
18772
+ let off: i32 = 0;
18773
+ const count = load<u32>(out.dataStart + off);
18774
+ off += 4;
18775
+ for (let i: u32 = 0; i < count; i++) {
18776
+ const present = load<u8>(out.dataStart + off);
18777
+ off += 1;
18778
+ if (present == 0) {
18779
+ results.push(null);
18780
+ continue;
18781
+ }
18782
+ const len = <i32>load<u32>(out.dataStart + off);
18783
+ off += 4;
18784
+ const v = instantiate<V>();
18785
+ v.decodeInto(out.subarray(off, off + len));
18786
+ off += len;
18787
+ results.push(v);
18788
+ }
18789
+ return results;
18790
+ }
18791
+
18792
+ /// Whether the record exists.
18793
+ exists(key: K): bool {
18794
+ const kb = key.encode();
18795
+ return toildbHost.exists(this.__handle, kb.dataStart, kb.byteLength) == 1;
18796
+ }
18797
+
18798
+ /// Create the record if absent. Returns false if it already existed.
18799
+ create(key: K, value: V): bool {
18800
+ const kb = key.encode();
18801
+ const vb = value.encode();
18802
+ return toildbHost.create(
18803
+ this.__handle, kb.dataStart, kb.byteLength, vb.dataStart, vb.byteLength, 0
18804
+ ) == 0;
18805
+ }
18806
+
18807
+ /// Apply a write through the key's home cell; returns the stored record.
18808
+ patch(key: K, value: V): V {
18809
+ const kb = key.encode();
18810
+ const vb = value.encode();
18811
+ const status = toildbHost.patch(
18812
+ this.__handle, kb.dataStart, kb.byteLength, vb.dataStart, vb.byteLength, 0
18813
+ );
18814
+ if (status < 0) unreachable();
18815
+ const v = instantiate<V>();
18816
+ v.decodeInto(__toildbTake(status));
18817
+ return v;
18818
+ }
18819
+
18820
+ /// Delete the record (idempotent).
18821
+ delete(key: K): void {
18822
+ const kb = key.encode();
18823
+ toildbHost.del(this.__handle, kb.dataStart, kb.byteLength, 0);
18824
+ }
18825
+
18826
+ /// Atomic fetch-and-delete (consume-once); returns the prior value or \`null\`.
18827
+ getDelete(key: K): V | null {
18828
+ const kb = key.encode();
18829
+ const status = toildbHost.getDelete(this.__handle, kb.dataStart, kb.byteLength, 0);
18830
+ if (status < 0) return null;
18831
+ const v = instantiate<V>();
18832
+ v.decodeInto(__toildbTake(status));
18833
+ return v;
18834
+ }
18835
+ }
18836
+
18837
+ /// A precomputed, read-optimized projection (spec 7.2): home pages,
18838
+ /// leaderboards, rendered fragments. Read by any function kind; PUBLISHED only
18839
+ /// by a \`@derive\`/\`@job\` (the host kind gate enforces it). \`V\` is the \`@data\`
18840
+ /// value type, \`K\` the \`@data\` key type.
18841
+ @global
18842
+ export class View<V, K> {
18843
+ private __handle: u32;
18844
+
18845
+ constructor(handle: u32) {
18846
+ this.__handle = handle;
18847
+ }
18848
+
18849
+ /// The published view for \`key\`, or \`null\` if none has been published.
18850
+ get(key: K): V | null {
18851
+ const kb = key.encode();
18852
+ const status = toildbHost.viewGet(this.__handle, kb.dataStart, kb.byteLength);
18853
+ if (status < 0) return null;
18854
+ const v = instantiate<V>();
18855
+ v.decodeInto(__toildbTake(status));
18856
+ return v;
18857
+ }
18858
+
18859
+ /// Like \`get\`, but traps if no view is published.
18860
+ require(key: K): V {
18861
+ const v = this.get(key);
18862
+ if (v == null) unreachable();
18863
+ return v!;
18864
+ }
18865
+
18866
+ /// Publish (overwrite) the view for \`key\`. Derive/job only; the host assigns
18867
+ /// the version so a later publish always supersedes an earlier one.
18868
+ publish(key: K, value: V): void {
18869
+ const kb = key.encode();
18870
+ const vb = value.encode();
18871
+ toildbHost.viewPublish(
18872
+ this.__handle, kb.dataStart, kb.byteLength, vb.dataStart, vb.byteLength, 0
18873
+ );
18874
+ }
18875
+ }
18876
+
18877
+ /// The result of a \`unique.claim\` (spec 8.6). \`claimed\` is true when the caller
18878
+ /// owns the key (a fresh claim or an idempotent re-claim of its own); when
18879
+ /// false, \`owner\` is the value that currently holds the key.
18880
+ @global
18881
+ export class ClaimResult<V> {
18882
+ constructor(public claimed: bool, public owner: V | null) {}
18883
+ }
18884
+
18885
+ /// A globally-unique claim collection (spec 7.6): username, email, slug, ...
18886
+ /// \`V\` is the \`@data\` OWNER value type, \`K\` the \`@data\` claim-key type.
18887
+ @global
18888
+ export class Unique<V, K> {
18889
+ private __handle: u32;
18890
+
18891
+ constructor(handle: u32) {
18892
+ this.__handle = handle;
18893
+ }
18894
+
18895
+ /// The value that owns \`key\`, or \`null\` if unclaimed.
18896
+ lookup(key: K): V | null {
18897
+ const kb = key.encode();
18898
+ const status = toildbHost.uniqueLookup(this.__handle, kb.dataStart, kb.byteLength);
18899
+ if (status < 0) return null;
18900
+ const v = instantiate<V>();
18901
+ v.decodeInto(__toildbTake(status));
18902
+ return v;
18903
+ }
18904
+
18905
+ /// Claim \`key\` for \`value\`. Returns whether the caller owns it, and (when
18906
+ /// another owns it) who.
18907
+ claim(key: K, value: V): ClaimResult<V> {
18908
+ const kb = key.encode();
18909
+ const vb = value.encode();
18910
+ const tag = toildbHost.uniqueClaim(
18911
+ this.__handle, kb.dataStart, kb.byteLength, vb.dataStart, vb.byteLength, 0
18912
+ );
18913
+ if (tag < 0) unreachable();
18914
+ if (tag == 1) {
18915
+ // AlreadyClaimed: the current owner is stashed.
18916
+ const owner = instantiate<V>();
18917
+ owner.decodeInto(__toildbTakeGrow());
18918
+ return new ClaimResult<V>(false, owner);
18919
+ }
18920
+ // 0 Claimed, 2 AlreadyOwnedByCaller -> the caller owns it.
18921
+ return new ClaimResult<V>(true, null);
18922
+ }
18923
+
18924
+ /// Release \`key\` (only the current owner may; a non-owner release traps).
18925
+ release(key: K, value: V): void {
18926
+ const kb = key.encode();
18927
+ const vb = value.encode();
18928
+ toildbHost.uniqueRelease(
18929
+ this.__handle, kb.dataStart, kb.byteLength, vb.dataStart, vb.byteLength, 0
18930
+ );
18931
+ }
18932
+ }
18933
+
18934
+ /// An unordered set (spec 7.3): followers, tags, ACLs, room members. \`M\` is the
18935
+ /// \`@data\` member type, \`K\` the \`@data\` set-key type.
18936
+ @global
18937
+ export class Membership<M, K> {
18938
+ private __handle: u32;
18939
+
18940
+ constructor(handle: u32) {
18941
+ this.__handle = handle;
18942
+ }
18943
+
18944
+ /// Whether \`member\` is in the set keyed by \`key\`.
18945
+ contains(key: K, member: M): bool {
18946
+ const kb = key.encode();
18947
+ const mb = member.encode();
18948
+ return toildbHost.membershipContains(
18949
+ this.__handle, kb.dataStart, kb.byteLength, mb.dataStart, mb.byteLength
18950
+ ) == 1;
18951
+ }
18952
+
18953
+ /// Add \`member\` to the set (idempotent).
18954
+ add(key: K, member: M): void {
18955
+ const kb = key.encode();
18956
+ const mb = member.encode();
18957
+ toildbHost.membershipAdd(
18958
+ this.__handle, kb.dataStart, kb.byteLength, mb.dataStart, mb.byteLength, 0
18959
+ );
18960
+ }
18961
+
18962
+ /// Remove \`member\` from the set (idempotent).
18963
+ remove(key: K, member: M): void {
18964
+ const kb = key.encode();
18965
+ const mb = member.encode();
18966
+ toildbHost.membershipRemove(
18967
+ this.__handle, kb.dataStart, kb.byteLength, mb.dataStart, mb.byteLength, 0
18968
+ );
18969
+ }
18970
+
18971
+ /// Up to \`limit\` members of the set. Decodes each framed member into an \`M\`.
18972
+ list(key: K, limit: i32): M[] {
18973
+ const kb = key.encode();
18974
+ const status = toildbHost.membershipList(this.__handle, kb.dataStart, kb.byteLength, limit);
18975
+ if (status < 0) unreachable();
18976
+ const blob = __toildbTake(status);
18977
+ const out = new Array<M>();
18978
+ let off: i32 = 0;
18979
+ const count = load<u32>(blob.dataStart + off);
18980
+ off += 4;
18981
+ for (let i: u32 = 0; i < count; i++) {
18982
+ const len = <i32>load<u32>(blob.dataStart + off);
18983
+ off += 4;
18984
+ const m = instantiate<M>();
18985
+ m.decodeInto(blob.subarray(off, off + len));
18986
+ out.push(m);
18987
+ off += len;
18988
+ }
18989
+ return out;
18990
+ }
18991
+ }
18992
+
18993
+ /// A finite, strongly-consistent resource (spec 7.7): limited stock, seats,
18994
+ /// rate grants. Reserve/confirm/cancel two-phase holds prevent oversell. \`K\` is
18995
+ /// the \`@data\` key type (the value is the host-owned escrow ledger).
18996
+ @global
18997
+ export class Capacity<K> {
18998
+ private __handle: u32;
18999
+
19000
+ constructor(handle: u32) {
19001
+ this.__handle = handle;
19002
+ }
19003
+
19004
+ /// Units available to reserve right now.
19005
+ available(key: K): i64 {
19006
+ const kb = key.encode();
19007
+ const status = toildbHost.capacityAvailable(this.__handle, kb.dataStart, kb.byteLength);
19008
+ if (status < 0) unreachable();
19009
+ return load<i64>(__toildbTake(status).dataStart);
19010
+ }
19011
+
19012
+ /// Hold \`amount\` for \`ttlMs\` (it auto-releases if not confirmed in time).
19013
+ /// Returns the reservation id (> 0), or 0 if there was not enough available
19014
+ /// (no oversell).
19015
+ reserve(key: K, amount: i64, ttlMs: i64): u64 {
19016
+ const kb = key.encode();
19017
+ const status = toildbHost.capacityReserve(
19018
+ this.__handle, kb.dataStart, kb.byteLength, amount, ttlMs, 0
19019
+ );
19020
+ if (status == -2) return 0; // insufficient
19021
+ if (status < 0) unreachable();
19022
+ return load<u64>(__toildbTake(status).dataStart);
19023
+ }
19024
+
19025
+ /// Finalize a hold into a permanent consume. Returns whether the id was valid.
19026
+ confirm(key: K, reservationId: u64): bool {
19027
+ const kb = key.encode();
19028
+ return toildbHost.capacityConfirm(
19029
+ this.__handle, kb.dataStart, kb.byteLength, reservationId as i64, 0
19030
+ ) == 1;
19031
+ }
19032
+
19033
+ /// Release a hold back to available (a confirmed sale cannot be cancelled).
19034
+ cancel(key: K, reservationId: u64): bool {
19035
+ const kb = key.encode();
19036
+ return toildbHost.capacityCancel(
19037
+ this.__handle, kb.dataStart, kb.byteLength, reservationId as i64, 0
19038
+ ) == 1;
19039
+ }
19040
+
19041
+ /// Set the ceiling (restock / reduce). \`@job\`/\`@derive\` only; the kind gate
19042
+ /// (compile + runtime) enforces it.
19043
+ setTotal(key: K, total: i64): void {
19044
+ const kb = key.encode();
19045
+ toildbHost.capacitySetTotal(this.__handle, kb.dataStart, kb.byteLength, total, 0);
19046
+ }
19047
+ }
19048
+
19049
+ /// A commutative integer counter (spec 7.4): likes, view counts, inventory.
19050
+ /// \`K\` is the \`@data\` key type; the value is a host-aggregated i64 rollup (there
19051
+ /// is no \`set\`, only \`add\` and \`get\`, so concurrent deltas never lose writes).
19052
+ @global
19053
+ export class Counter<K> {
19054
+ private __handle: u32;
19055
+
19056
+ constructor(handle: u32) {
19057
+ this.__handle = handle;
19058
+ }
19059
+
19060
+ /// The current sum (0 if no deltas have been applied).
19061
+ get(key: K): i64 {
19062
+ const kb = key.encode();
19063
+ const status = toildbHost.counterGet(this.__handle, kb.dataStart, kb.byteLength);
19064
+ if (status < 0) unreachable();
19065
+ const buf = __toildbTake(status);
19066
+ return load<i64>(buf.dataStart);
19067
+ }
19068
+
19069
+ /// Apply a (possibly negative) delta; saturates at the i64 bounds.
19070
+ add(key: K, delta: i64): void {
19071
+ const kb = key.encode();
19072
+ toildbHost.counterAdd(this.__handle, kb.dataStart, kb.byteLength, delta, 0);
19073
+ }
19074
+ }
19075
+
19076
+ /// An append-only event log (spec 7.5): activity feeds, audit trails, the
19077
+ /// fact stream a \`@derive\` consumes. \`V\` is the \`@data\` event type, \`K\` the
19078
+ /// \`@data\` stream-key type.
19079
+ @global
19080
+ export class Events<V, K> {
19081
+ private __handle: u32;
19082
+
19083
+ constructor(handle: u32) {
19084
+ this.__handle = handle;
19085
+ }
19086
+
19087
+ /// Append an event to the stream.
19088
+ append(key: K, event: V): void {
19089
+ const kb = key.encode();
19090
+ const eb = event.encode();
19091
+ toildbHost.append(this.__handle, kb.dataStart, kb.byteLength, eb.dataStart, eb.byteLength, 0);
19092
+ }
19093
+
19094
+ /// The newest \`limit\` events, newest first. Decodes each framed event into a
19095
+ /// \`V\`. The host frames them as \`u32 count\` then per event \`u32 len + bytes\`.
19096
+ latest(key: K, limit: i32): V[] {
19097
+ const kb = key.encode();
19098
+ const status = toildbHost.latest(this.__handle, kb.dataStart, kb.byteLength, limit);
19099
+ if (status < 0) unreachable();
19100
+ const blob = __toildbTake(status);
19101
+ const out = new Array<V>();
19102
+ let off: i32 = 0;
19103
+ const count = load<u32>(blob.dataStart + off);
19104
+ off += 4;
19105
+ for (let i: u32 = 0; i < count; i++) {
19106
+ const len = <i32>load<u32>(blob.dataStart + off);
19107
+ off += 4;
19108
+ const ev = instantiate<V>();
19109
+ ev.decodeInto(blob.subarray(off, off + len));
19110
+ out.push(ev);
19111
+ off += len;
19112
+ }
19113
+ return out;
19114
+ }
19115
+ }
18442
19116
  `,typedarray:`import { COMPARATOR, SORT } from "./util/sort";
18443
19117
  import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH, E_NOTIMPLEMENTED } from "./util/error";
18444
19118
  import { joinIntegerArray, joinFloatArray } from "./util/string";
@@ -28923,11 +29597,14 @@ declare class X25519ImportParams extends AlgorithmParams {}
28923
29597
  declare class EcdhParams extends AlgorithmParams {
28924
29598
  constructor(alg: i32, publicKeyHandle: i32);
28925
29599
  }
28926
- /** Synchronous SubtleCrypto (no Promises). Returns values directly. */
29600
+ /** Synchronous SubtleCrypto (no Promises). Returns values directly. The hash and
29601
+ * key-format arguments are typed ABI ids (no magic strings): pass an \`ALG_SHA_*\`
29602
+ * const to \`digest\`, and an \`FMT_*\` const (\`FMT_RAW\` / \`FMT_PKCS8\` / \`FMT_SPKI\`)
29603
+ * to \`importKey\` / \`exportKey\`. */
28927
29604
  declare class SubtleCrypto {
28928
- digest(algorithm: string, data: Uint8Array): Uint8Array;
28929
- importKey(format: string, keyData: Uint8Array, algorithm: AlgorithmParams, extractable: bool, usages: i32): CryptoKey;
28930
- exportKey(format: string, key: CryptoKey): Uint8Array;
29605
+ digest(algorithm: i32, data: Uint8Array): Uint8Array;
29606
+ importKey(format: i32, keyData: Uint8Array, algorithm: AlgorithmParams, extractable: bool, usages: i32): CryptoKey;
29607
+ exportKey(format: i32, key: CryptoKey): Uint8Array;
28931
29608
  encrypt(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array;
28932
29609
  decrypt(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array;
28933
29610
  sign(algorithm: AlgorithmParams, key: CryptoKey, data: Uint8Array): Uint8Array;
@@ -28938,6 +29615,8 @@ declare class SubtleCrypto {
28938
29615
 
28939
29616
  // Algorithm / format / curve / usage ids (the Web Crypto ABI contract).
28940
29617
  declare const ALG_SHA_1: i32, ALG_SHA_256: i32, ALG_SHA_384: i32, ALG_SHA_512: i32;
29618
+ declare const ALG_SHA3_256: i32, ALG_SHA3_384: i32, ALG_SHA3_512: i32;
29619
+ declare const FMT_RAW: i32, FMT_PKCS8: i32, FMT_SPKI: i32, FMT_JWK: i32;
28941
29620
  declare const ALG_AES_GCM: i32, ALG_AES_CBC: i32, ALG_AES_CTR: i32, ALG_AES_KW: i32;
28942
29621
  declare const ALG_HMAC: i32, ALG_ECDSA: i32, ALG_ED25519: i32, ALG_ECDH: i32, ALG_X25519: i32, ALG_HKDF: i32, ALG_PBKDF2: i32;
28943
29622
  declare const CURVE_P256: i32, CURVE_P384: i32;
@@ -29504,7 +30183,7 @@ declare interface Float64Array {
29504
30183
  // FIXME: remove
29505
30184
  declare function offsetof<T>(fieldName?: string): usize;
29506
30185
  declare function idof<T>(): u32;
29507
- `};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
30186
+ `};var pn={};nn(pn,{default:()=>hn});Dn(pn,Mt);import*as Mt from"binaryen";import{default as hn}from"binaryen";import*as At from"toilscript";var x=At,Pn=M.argv.indexOf("--wasm");if(~Pn){let e=String(M.argv[Pn+1]);M.argv.splice(Pn,2),x=await import(new URL(e,dn.pathToFileURL(M.cwd()+"/")))}var Vn=sn.createRequire(import.meta.url),Xn=M.platform==="win32",E=Xn?`\r
29508
30187
  `:`
29509
- `,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};
30188
+ `,Gn=Xn?"\\":"/",_=".ts",_t=`.d${_}`,xn=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 h=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(h),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:h,stderr:b,stats:n},l));if(i.version)return h.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?h: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=x.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(x.setTarget(T,0),x.setDebugInfo(T,!!i.debug),x.setRuntime(T,rn),x.setNoAssert(T,i.noAssert),x.setExportMemory(T,!i.noExportMemory),x.setImportMemory(T,i.importMemory),x.setInitialMemory(T,i.initialMemory>>>0),x.setMaximumMemory(T,i.maximumMemory>>>0),x.setSharedMemory(T,i.sharedMemory),x.setImportTable(T,i.importTable),x.setExportTable(T,i.exportTable),i.exportStart!=null&&x.setExportStart(T,Ct(i.exportStart)?i.exportStart:"_start"),x.setMemoryBase(T,i.memoryBase>>>0),x.setTableBase(T,i.tableBase>>>0),x.setSourceMap(T,i.sourceMap!=null),x.setUncheckedBehavior(T,mn),x.setNoUnsafe(T,i.noUnsafe),x.setPedantic(T,i.pedantic),x.setLowMemoryLimit(T,i.lowMemoryLimit>>>0),x.setExportRuntime(T,i.exportRuntime),x.setBundleVersion(T,r,s,u),!i.stackSize&&rn===2&&(i.stackSize=x.DEFAULT_STACK_SIZE),x.setStackSize(T,i.stackSize),x.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.`));x.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=x[`FEATURE_${Te(c)}`];if(!p)return z(Error(`Feature '${c}' is unknown.`));x.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=x[`FEATURE_${Te(c)}`];if(!p)return z(Error(`Feature '${c}' is unknown.`));x.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),x.setOptimizeLevelHints(T,Z,$),B=x.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:hn,baseDir:w,stdout:h,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++,x.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(xn,"")]=C;let O=n.begin();n.parseCount++,x.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(xn,""),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(xn,""),F.join(S,O));break}}}}}}return c==null?null:{sourceText:c,sourcePath:p}}function Le(a=[]){do{let l=x.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=x.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?x.parse(B,C.sourceText,C.sourcePath,!1):x.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++,x.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(xn,"").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++,x.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{x.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=x.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=hn.wrapModule(typeof K=="number"||K instanceof Number?x.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=x.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++,x.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++,x.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(x.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=x.getSource(B,re.replace(xn,""));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{hn.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=x.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=x.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=x.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++),h.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 h=u[f];if(!jn(r.targets[h]))throw new Error(`Toilconfig.targets.${h} 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 h=x.nextDiagnostic(e);if(!h)break;if(t){let b=d=>{if(n==null)return!1;if(!n.length)return!0;let g=x.getDiagnosticCode(d);return n.includes(g)};(x.isError(h)||!b(h))&&t.write(x.formatDiagnostic(h,s,!0)+E+E)}if(o){let b=function(g){return g&&{start:x.getRangeStart(g),end:x.getRangeEnd(g),source:d(x.getRangeSource(g))}||null},d=function(g){return g&&{normalizedPath:x.getSourceNormalizedPath(g)}||null};var u=b,f=d;o({message:x.getDiagnosticMessage(h),code:x.getDiagnosticCode(h),category:x.getDiagnosticCategory(h),range:b(x.getDiagnosticRange(h)),relatedRange:b(x.getDiagnosticRelatedRange(h))})}x.isError(h)&&++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),h=r+u+f+6,b=[];b.push(`\u256D\u2500${"\u2500".repeat(h)}\u2500\u256E${E}`);let d="Stats";b.push(`\u2502 ${d}${" ".repeat(h-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(h-g.length)} \u2502${E}`);let y=`${this.readCount} reads, ${this.writeCount} writes`;return b.push(`\u2502 ${y}${" ".repeat(h-y.length)} \u2502${E}`),b.push(`\u2570\u2500${"\u2500".repeat(h)}\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};
29510
30189
  //# sourceMappingURL=cli.js.map