toilscript 0.1.36 → 0.1.38

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.
@@ -2877,11 +2877,31 @@ declare module "types:toilscript/src/dbcatalog" {
2877
2877
  * `schema_version`: a hash over the ORDERED field layout (name, type, is_array),
2878
2878
  * NOT the value-type name. Adding, removing, retyping, or REORDERING a field
2879
2879
  * changes it - so the runtime can tell a compatible (append-only) change from a
2880
- * breaking one, instead of silently misreading old rows. (Flat, like toildb's
2881
- * `SchemaDescriptor::layout_hash`: a change to a NESTED `@data` type's own fields
2882
- * does not bump the parent - that lands with recursive layouts later.)
2880
+ * breaking one, instead of silently misreading old rows.
2881
+ *
2882
+ * RECURSIVE into nested `@data` types: when a field's `typeName` is a KNOWN
2883
+ * `@data` type (a key of `typeMap`) and not already on the `seen` set (cycle
2884
+ * guard), the SAME running hash continues over that nested type's fields - so a
2885
+ * breaking change to a NESTED type bumps the OUTER `schema_version` and can be
2886
+ * `@migrate`d (instead of being refuse-only). This MUST stay byte-identical to
2887
+ * toildb's `SchemaDescriptor::layout_hash` (the runtime side): the algorithm,
2888
+ * the `seen` add/remove, and the declaration-order traversal are pinned in lock
2889
+ * step. A FLAT type (no field whose type is in `typeMap`) hashes to the SAME
2890
+ * value as the old flat hash, so existing pinned vectors stay green; an absent
2891
+ * `typeMap` (undefined) is flat/back-compatible.
2892
+ *
2893
+ * `typeMap` MUST contain the SAME set of `@data` types as the runtime's
2894
+ * `toildb.types` registry (collection value types + their nested types, EXCLUDING
2895
+ * old `*.migration.ts` shapes), or the two hashes diverge: a nested field whose
2896
+ * type is absent from the map on either side is treated as a LEAF on both sides.
2883
2897
  */
2884
- export function layoutHash(fields: FieldLayout[]): number;
2898
+ export function layoutHash(fields: FieldLayout[], typeMap?: Map<string, FieldLayout[]> | null, seen?: Set<string> | null): number;
2899
+ /** The recursion type map for `layoutHash`: every `@data` type the runtime's
2900
+ * `toildb.types` registry also contains (collection value types + their nested
2901
+ * types), EXCLUDING old `*.migration.ts` shapes (which the runtime registry
2902
+ * excludes by design). Both sides must recurse through the SAME set, so a
2903
+ * nested field whose type is NOT here is a leaf on both sides. */
2904
+ export function recursionTypeMap(sources: Source[]): Map<string, FieldLayout[]>;
2885
2905
  /** Extract the encoded field layout of a `@data` class, in declaration order,
2886
2906
  * mirroring `injectDataCodec` (skip static; `Array<T>` -> element + array flag;
2887
2907
  * else scalar/string/`Uint8Array`/nested-`@data` by its type name). */
@@ -2895,17 +2915,37 @@ declare module "types:toilscript/src/dbcatalog" {
2895
2915
  fnName: string;
2896
2916
  oldVersion: number;
2897
2917
  delta: boolean;
2918
+ sourceInternalPath: string;
2898
2919
  }
2899
2920
  /** Every `@migrate` function across the (non-library) sources. `layouts` maps a
2900
- * `@data` class name to its field layout, for the old-version hash. A migration
2901
- * whose param/return is not a single named type, or whose old type has no
2902
- * layout, is skipped. */
2903
- export function collectMigrations(sources: Source[], layouts: Map<string, FieldLayout[]>): DataMigration[];
2921
+ * `@data` class name to its field layout, for the old-version hash. `typeMap`
2922
+ * (optional) is the recursion type map (see [`recursionTypeMap`]) so the old
2923
+ * version hashes RECURSIVELY through its nested `@data` fields - matching the
2924
+ * `schema_version` that old layout was deployed under (or the migratable old
2925
+ * version would never match a deployed recursive hash). Absent = flat. A
2926
+ * migration whose param/return is not a single named type, or whose old type
2927
+ * has no layout, is skipped. */
2928
+ export function collectMigrations(sources: Source[], layouts: Map<string, FieldLayout[]>, typeMap?: Map<string, FieldLayout[]> | null): DataMigration[];
2929
+ /** A resolved chain that migrates a stored OLD value all the way to a target
2930
+ * type: decode `oldType`, then apply `steps` in order (each `@migrate`). For a
2931
+ * direct migration `steps` has one entry; a chain `V0 -> V1 -> V2` has two. */
2932
+ export class MigrationChain {
2933
+ oldType: string;
2934
+ oldVersion: number;
2935
+ steps: DataMigration[];
2936
+ }
2937
+ /** Every old type that reaches `target` through a chain of `@migrate` edges, with
2938
+ * the ordered transforms to apply. A backward breadth-first walk of the migration
2939
+ * graph (edges OLD -> NEW), so the SHORTEST chain wins and cycles terminate; a
2940
+ * direct migration is just a one-step chain. This is what lets a row written under
2941
+ * version 0 reach the current version 2 via `0->1` then `1->2`. */
2942
+ export function chainsTo(target: string, migrations: DataMigration[]): MigrationChain[];
2904
2943
  /**
2905
2944
  * Build the `toildb.catalog` section bytes, or `null` if the program declares
2906
2945
  * no `@database`.
2907
2946
  */
2908
2947
  export function buildToilDbCatalog(program: Program): Uint8Array | null;
2948
+ export function buildToilDbTypes(program: Program): Uint8Array | null;
2909
2949
  }
2910
2950
  declare module "types:toilscript/src/parser" {
2911
2951
  /**
@@ -2980,8 +3020,30 @@ declare module "types:toilscript/src/parser" {
2980
3020
  /** Finishes parsing. */
2981
3021
  finish(): void;
2982
3022
  weaveDataMigrations(): void;
2983
- /** Replace `newType`'s generated `decodeInto` with a version-dispatching one. */
3023
+ /** Enforce the migration-file convention (folder AND extension): every `@migrate`
3024
+ * must live in a `*.migration.ts` file under a `migrations/` directory. Keeping
3025
+ * migrations in one discoverable place is what lets the build auto-parse them and
3026
+ * the weave inject the cross-file imports; a stray `@migrate` elsewhere would not
3027
+ * be discovered (silently never run), so it is a hard error. */
3028
+ private checkMigrationLocations;
3029
+ /** Replace `target`'s generated `decodeInto` with a version-dispatching one: a
3030
+ * row at any chain-reachable old version is decoded as its shape and run forward
3031
+ * through every transform until it reaches `target`. */
2984
3032
  private weaveDecodeInto;
3033
+ /** Record that `sym` (an old `@data` shape or a transform fn) must be imported
3034
+ * into the value type's source from `srcPath`. A blank or same-file source is a
3035
+ * no-op (the symbol is already in scope). Deduped per source via parallel arrays. */
3036
+ private addMigrationImport;
3037
+ /** Internal path of the source declaring the `@data` class `name`, or "" if it
3038
+ * isn't a known `@data` type (then there is nothing to import). */
3039
+ private typeSourcePath;
3040
+ /** A `"./.."`-style module specifier from importing file `fromInternal` to target
3041
+ * module `toInternal` (both extension-less internal paths), e.g.
3042
+ * `("models/User","migrations/User.migration") -> "../migrations/User.migration"`. */
3043
+ private relativeModulePath;
3044
+ /** Copy the fields a delta-step's old and new layouts SHARE (same name + type +
3045
+ * array-ness) from `prevVar` into `nextVar`. */
3046
+ private migrationCarry;
2985
3047
  private checkToilDbKinds;
2986
3048
  /** Map every `@database` class (incl. inside namespaces) to its
2987
3049
  * collection-name -> handle-family-name. */
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,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var nn=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},oe=(e,t,n,r)=>{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:!(r=Ne(t,s))||r.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),r=Math.floor(t*1e6-n*1e9);return e&&(n-=e[0],r-=e[1],r<0&&(n--,r+=1e9)),[n,r]}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="",r=0,s=-1,a=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||a===1))if(s!==f-1&&a===2){if(n.length<2||r!==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="",r=0):(n=n.slice(0,h),r=n.length-1-n.lastIndexOf("/")),s=f,a=0;continue}}else if(n.length===2||n.length===1){n="",r=0,s=f,a=0;continue}}t&&(n.length>0?n+="/..":n="..",r=2)}else n.length>0?n+="/"+e.slice(s+1,f):n=e.slice(s+1,f),r=f-s-1;s=f,a=0}else u===46&&a!==-1?++a:a=-1}return n}function We(e,t){var n=t.dir||t.root,r=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+r:n+e+r:r}function cn(){for(var e="",t=!1,n,r=arguments.length-1;r>=-1&&!t;r--){var s;r>=0?s=arguments[r]:(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 r=e.length,s=r-n,a=1;a<t.length&&t.charCodeAt(a)===47;++a);for(var u=t.length,f=u-a,h=s<f?s:f,b=-1,d=0;d<=h;++d){if(d===h){if(f>h){if(t.charCodeAt(a+d)===47)return t.slice(a+d+1);if(d===0)return t.slice(a+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(a+d);if(g!==y)break;g===47&&(b=d)}var m="";for(d=n+b+1;d<=r;++d)(d===r||e.charCodeAt(d)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(a+b):(a+=b,t.charCodeAt(a)===47&&++a,t.slice(a))}function $e(e){if(V(e),e.length===0)return".";for(var t=e.charCodeAt(0),n=t===47,r=-1,s=!0,a=e.length-1;a>=1;--a)if(t=e.charCodeAt(a),t===47){if(!s){r=a;break}}else s=!1;return r===-1?n?"/":".":n&&r===1?"//":e.slice(0,r)}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,r=-1,s=!0,a;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(a=e.length-1;a>=0;--a){var h=e.charCodeAt(a);if(h===47){if(!s){n=a+1;break}}else f===-1&&(s=!1,f=a+1),u>=0&&(h===t.charCodeAt(u)?--u===-1&&(r=a):(u=-1,r=f))}return n===r?r=f:r===-1&&(r=e.length),e.slice(n,r)}else{for(a=e.length-1;a>=0;--a)if(e.charCodeAt(a)===47){if(!s){n=a+1;break}}else r===-1&&(s=!1,r=a+1);return r===-1?"":e.slice(n,r)}}function nt(e){V(e);for(var t=-1,n=0,r=-1,s=!0,a=0,u=e.length-1;u>=0;--u){var f=e.charCodeAt(u);if(f===47){if(!s){n=u+1;break}continue}r===-1&&(s=!1,r=u+1),f===46?t===-1?t=u:a!==1&&(a=1):t!==-1&&(a=-1)}return t===-1||r===-1||a===0||a===1&&t===r-1&&t===n+1?"":e.slice(t,r)}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),r=n===47,s;r?(t.root="/",s=1):s=0;for(var a=-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?a===-1?a=b:d!==1&&(d=1):a!==-1&&(d=-1)}return a===-1||f===-1||d===0||d===1&&a===f-1&&a===u+1?f!==-1&&(u===0&&r?t.base=t.name=e.slice(1,f):t.base=t.name=e.slice(u,f)):(u===0&&r?(t.name=e.slice(1,a),t.base=e.slice(1,f)):(t.name=e.slice(u,a),t.base=e.slice(u,f)),t.ext=e.slice(a,f)),u>0?t.dir=e.slice(0,u-1):r&&(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,r=e.length;n<r;++n){let s=e.charCodeAt(n);s<128?t+=1:s<2048?t+=2:(s&64512)===55296&&n+1<r&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3}return t}function bt(e,t,n){var r=n-t;if(r<1)return"";for(var s=null,a=[],u=0,f;t<n;)f=e[t++],f<128?a[u++]=f:f>191&&f<224?a[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,a[u++]=55296+(f>>10),a[u++]=56320+(f&1023)):a[u++]=(f&15)<<12|(e[t++]&63)<<6|e[t++]&63,u>=8192&&((s||(s=[])).push(String.fromCharCode(...a)),u=0);return s?(u&&s.push(String.fromCharCode(...a.slice(0,u))),s.join("")):String.fromCharCode(...a.slice(0,u))}function yt(e,t,n){for(var r=n,s=0,a=e.length;s<a;++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<a&&((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-r}var Tn={length:mt,read:bt,write:yt};var me=sn.createRequire(import.meta.url);function ye(e,t,n=!0){var r={},s=[],a=[],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&&(r[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{a.push(d);continue}if(y)if(y.value)Object.keys(y.value).forEach(i=>r[i]=y.value[i]);else if(y.type==null||y.type==="b")r[m]=!0;else if(h+1<e.length&&e[h+1].charCodeAt(0)!=45)switch(y.type){case"i":r[m]=parseInt(e[++h],10);break;case"I":r[m]=(r[m]||[]).concat(parseInt(e[++h],10));break;case"f":r[m]=parseFloat(e[++h]);break;case"F":r[m]=(r[m]||[]).concat(parseFloat(e[++h]));break;case"s":r[m]=String(e[++h]);break;case"S":r[m]=(r[m]||[]).concat(e[++h].split(","));break;default:s.push(d),--h}else switch(y.type){case"i":case"f":r[m]=y.default||0;break;case"s":r[m]=y.default||"";break;case"I":case"F":case"S":r[m]=y.default||[];break;default:s.push(d)}else s.push(d)}for(;h<b;)u.push(e[h++]);return n&&Mn(t,r),{options:r,unknown:s,arguments:a,trailing:u}}function ve(e,t){t||(t={});var n=t.indent||2,r=t.padding||24,s=t.eol||`
8
- `,a={},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<r;)g+=" ";var y;!t.noCategories&&d.category?(y=a[d.category])||(a[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<r;++i)m=" "+m;return s+m}).join("")):y.push(g+d.description)}});var f=[],h=!1;return Object.keys(a).forEach(b=>{h=!0,f.push(s+" "+_n.gray(b)+s),f.push(a[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,r){let s={};for(let[a,{type:u,mutuallyExclusive:f,isPath:h,useNodeResolution:b,cliOnly:d}]of Object.entries(e)){let g=be(t[a],u),y=be(n[a],u);if(g==null){if(y!=null){if(d)continue;if(Array.isArray(y)){let m;h&&(y=y.map(i=>tn(i,r,b))),f!=null&&(m=t[f])?s[a]=y.filter(i=>!m.includes(i)):s[a]=y.slice()}else h&&(y=tn(y,r,b)),s[a]=y}}else if(y==null)Array.isArray(g)?s[a]=g.slice():s[a]=g;else if(Array.isArray(g)){if(d){s[a]=g.slice();continue}let m;h&&(y=y.map(i=>tn(i,r,b))),f!=null&&(m=t[f])?s[a]=[...g,...y.filter(i=>!g.includes(i)&&!m.includes(i))]:s[a]=[...g,...y.filter(i=>!g.includes(i))]}else s[a]=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:r}]of Object.entries(e))t[n]==null&&r!=null&&(t[n]=r)}var Fe="0.1.36",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,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(a){throw n=[a],a}};var nn=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},oe=(e,t,n,a)=>{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:!(a=Ne(t,s))||a.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:()=>je,cwd:()=>In,exit:()=>Ke,hrtime:()=>qe,platform:()=>Ge,umask:()=>He});function In(){return"."}function He(){return 0}function Ke(e=0){throw Error(`exit ${e}`)}function qe(e){var t=Xe.call(de),n=Math.floor(t*.001),a=Math.floor(t*1e6-n*1e9);return e&&(n-=e[0],a-=e[1],a<0&&(n--,a+=1e9)),[n,a]}var Ge,je,de,Xe,Ln=fn(()=>{"use strict";Ge="linux";je=[];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 G(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function pe(e,t){for(var n="",a=0,s=-1,o=0,f,c=0;c<=e.length;++c){if(c<e.length)f=e.charCodeAt(c);else{if(f===47)break;f=47}if(f===47){if(!(s===c-1||o===1))if(s!==c-1&&o===2){if(n.length<2||a!==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="",a=0):(n=n.slice(0,x),a=n.length-1-n.lastIndexOf("/")),s=c,o=0;continue}}else if(n.length===2||n.length===1){n="",a=0,s=c,o=0;continue}}t&&(n.length>0?n+="/..":n="..",a=2)}else n.length>0?n+="/"+e.slice(s+1,c):n=e.slice(s+1,c),a=c-s-1;s=c,o=0}else f===46&&o!==-1?++o:o=-1}return n}function We(e,t){var n=t.dir||t.root,a=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+a:n+e+a:a}function cn(){for(var e="",t=!1,n,a=arguments.length-1;a>=-1&&!t;a--){var s;a>=0?s=arguments[a]:(n===void 0&&(n=In()),s=n),G(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(G(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 G(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];G(n),n.length>0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":he(e)}function Ze(e,t){if(G(e),G(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 a=e.length,s=a-n,o=1;o<t.length&&t.charCodeAt(o)===47;++o);for(var f=t.length,c=f-o,x=s<c?s:c,b=-1,p=0;p<=x;++p){if(p===x){if(c>x){if(t.charCodeAt(o+p)===47)return t.slice(o+p+1);if(p===0)return t.slice(o+p)}else s>x&&(e.charCodeAt(n+p)===47?b=p:p===0&&(b=0));break}var g=e.charCodeAt(n+p),y=t.charCodeAt(o+p);if(g!==y)break;g===47&&(b=p)}var m="";for(p=n+b+1;p<=a;++p)(p===a||e.charCodeAt(p)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(o+b):(o+=b,t.charCodeAt(o)===47&&++o,t.slice(o))}function $e(e){if(G(e),e.length===0)return".";for(var t=e.charCodeAt(0),n=t===47,a=-1,s=!0,o=e.length-1;o>=1;--o)if(t=e.charCodeAt(o),t===47){if(!s){a=o;break}}else s=!1;return a===-1?n?"/":".":n&&a===1?"//":e.slice(0,a)}function Qe(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');G(e);var n=0,a=-1,s=!0,o;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var f=t.length-1,c=-1;for(o=e.length-1;o>=0;--o){var x=e.charCodeAt(o);if(x===47){if(!s){n=o+1;break}}else c===-1&&(s=!1,c=o+1),f>=0&&(x===t.charCodeAt(f)?--f===-1&&(a=o):(f=-1,a=c))}return n===a?a=c:a===-1&&(a=e.length),e.slice(n,a)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!s){n=o+1;break}}else a===-1&&(s=!1,a=o+1);return a===-1?"":e.slice(n,a)}}function nt(e){G(e);for(var t=-1,n=0,a=-1,s=!0,o=0,f=e.length-1;f>=0;--f){var c=e.charCodeAt(f);if(c===47){if(!s){n=f+1;break}continue}a===-1&&(s=!1,a=f+1),c===46?t===-1?t=f:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||a===-1||o===0||o===1&&t===a-1&&t===n+1?"":e.slice(t,a)}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){G(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var n=e.charCodeAt(0),a=n===47,s;a?(t.root="/",s=1):s=0;for(var o=-1,f=0,c=-1,x=!0,b=e.length-1,p=0;b>=s;--b){if(n=e.charCodeAt(b),n===47){if(!x){f=b+1;break}continue}c===-1&&(x=!1,c=b+1),n===46?o===-1?o=b:p!==1&&(p=1):o!==-1&&(p=-1)}return o===-1||c===-1||p===0||p===1&&o===c-1&&o===f+1?c!==-1&&(f===0&&a?t.base=t.name=e.slice(1,c):t.base=t.name=e.slice(f,c)):(f===0&&a?(t.name=e.slice(1,o),t.base=e.slice(1,c)):(t.name=e.slice(f,o),t.base=e.slice(f,c)),t.ext=e.slice(o,c)),f>0?t.dir=e.slice(0,f-1):a&&(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:()=>j,libraryPrefix:()=>V,main:()=>Be,options:()=>zt,tscOptions:()=>Bt,version:()=>jn});var st=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",M,sn,A,P,dn;st?(M=await import("fs"),sn=await import("module"),A=await import("path"),P=globalThis.process,dn=await import("url")):(M=await Promise.resolve().then(()=>(ue(),le)),sn=await Promise.resolve().then(()=>(ce(),fe)),A=await Promise.resolve().then(()=>(Nn(),Rn)),P=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,a=e.length;n<a;++n){let s=e.charCodeAt(n);s<128?t+=1:s<2048?t+=2:(s&64512)===55296&&n+1<a&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3}return t}function bt(e,t,n){var a=n-t;if(a<1)return"";for(var s=null,o=[],f=0,c;t<n;)c=e[t++],c<128?o[f++]=c:c>191&&c<224?o[f++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[f++]=55296+(c>>10),o[f++]=56320+(c&1023)):o[f++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,f>=8192&&((s||(s=[])).push(String.fromCharCode(...o)),f=0);return s?(f&&s.push(String.fromCharCode(...o.slice(0,f))),s.join("")):String.fromCharCode(...o.slice(0,f))}function yt(e,t,n){for(var a=n,s=0,o=e.length;s<o;++s){let f=e.charCodeAt(s),c;f<128?t[n++]=f:f<2048?(t[n++]=f>>6|192,t[n++]=f&63|128):(f&64512)===55296&&s+1<o&&((c=e.charCodeAt(s+1))&64512)===56320?(f=65536+((f&1023)<<10)+(c&1023),++s,t[n++]=f>>18|240,t[n++]=f>>12&63|128,t[n++]=f>>6&63|128,t[n++]=f&63|128):(t[n++]=f>>12|224,t[n++]=f>>6&63|128,t[n++]=f&63|128)}return n-a}var Tn={length:mt,read:bt,write:yt};var me=sn.createRequire(import.meta.url);function ye(e,t,n=!0){var a={},s=[],o=[],f=[],c={};Object.keys(t).forEach(p=>{if(!p.startsWith(" ")){var g=t[p];g.alias!=null&&(typeof g.alias=="string"?c[g.alias]=p:Array.isArray(g.alias)&&g.alias.forEach(y=>c[y]=p)),n&&g.default!=null&&(a[p]=g.default)}});for(var x=0,b=(e=e.slice()).length;x<b;++x){let p=e[x];if(p=="--"){++x;break}let g=/^(?:(-\w)(?:=(.*))?|(--\w{2,})(?:=(.*))?)$/.exec(p),y,m;if(g)t[p]?y=t[m=p]:g[1]!=null?(y=t[m=c[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(p.charCodeAt(0)==45)y=t[m=p];else{o.push(p);continue}if(y)if(y.value)Object.keys(y.value).forEach(i=>a[i]=y.value[i]);else if(y.type==null||y.type==="b")a[m]=!0;else if(x+1<e.length&&e[x+1].charCodeAt(0)!=45)switch(y.type){case"i":a[m]=parseInt(e[++x],10);break;case"I":a[m]=(a[m]||[]).concat(parseInt(e[++x],10));break;case"f":a[m]=parseFloat(e[++x]);break;case"F":a[m]=(a[m]||[]).concat(parseFloat(e[++x]));break;case"s":a[m]=String(e[++x]);break;case"S":a[m]=(a[m]||[]).concat(e[++x].split(","));break;default:s.push(p),--x}else switch(y.type){case"i":case"f":a[m]=y.default||0;break;case"s":a[m]=y.default||"";break;case"I":case"F":case"S":a[m]=y.default||[];break;default:s.push(p)}else s.push(p)}for(;x<b;)f.push(e[x++]);return n&&Mn(t,a),{options:a,unknown:s,arguments:o,trailing:f}}function ve(e,t){t||(t={});var n=t.indent||2,a=t.padding||24,s=t.eol||`
8
+ `,o={},f=[];Object.keys(e).forEach(b=>{var p=e[b];if(p.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,p.alias&&(g+=", -"+p.alias);g.length<a;)g+=" ";var y;!t.noCategories&&p.category?(y=o[p.category])||(o[p.category]=y=[]):y=f,Array.isArray(p.description)?y.push(g+p.description[0]+p.description.slice(1).map(m=>{for(let i=0;i<a;++i)m=" "+m;return s+m}).join("")):y.push(g+p.description)}});var c=[],x=!1;return Object.keys(o).forEach(b=>{x=!0,c.push(s+" "+_n.gray(b)+s),c.push(o[b].join(s))}),x&&f.length&&c.push(s+" "+_n.gray("Other")+s),c.push(f.join(s)),c.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,a){let s={};for(let[o,{type:f,mutuallyExclusive:c,isPath:x,useNodeResolution:b,cliOnly:p}]of Object.entries(e)){let g=be(t[o],f),y=be(n[o],f);if(g==null){if(y!=null){if(p)continue;if(Array.isArray(y)){let m;x&&(y=y.map(i=>tn(i,a,b))),c!=null&&(m=t[c])?s[o]=y.filter(i=>!m.includes(i)):s[o]=y.slice()}else x&&(y=tn(y,a,b)),s[o]=y}}else if(y==null)Array.isArray(g)?s[o]=g.slice():s[o]=g;else if(Array.isArray(g)){if(p){s[o]=g.slice();continue}let m;x&&(y=y.map(i=>tn(i,a,b))),c!=null&&(m=t[c])?s[o]=[...g,...y.filter(i=>!g.includes(i)&&!m.includes(i))]:s[o]=[...g,...y.filter(i=>!g.includes(i))]}else s[o]=g}return s}function vt(e){let t=A.parse(e);return t.root||(t.root="./"),A.format(t)}function tn(e,t,n=!1){return A.isAbsolute(e)?e:n&&!e.startsWith(".")&&me.resolve?me.resolve(e,{paths:[t]}):vt(A.join(t,e))}function Mn(e,t){for(let[n,{default:a}]of Object.entries(e))t[n]==null&&a!=null&&(t[n]=a)}var Fe="0.1.38",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";
@@ -4428,7 +4428,7 @@ export declare namespace Object {
4428
4428
 
4429
4429
  export declare namespace Date {
4430
4430
  @external("env", "Date.now")
4431
- export function now(): f64;
4431
+ export function now(): u64;
4432
4432
  }
4433
4433
 
4434
4434
  export declare namespace console {
@@ -4805,6 +4805,33 @@ export namespace toildbHost {
4805
4805
  @external("env", "data.latest")
4806
4806
  export declare function latest(handle: u32, keyPtr: usize, keyLen: i32, limit: i32): i32;
4807
4807
 
4808
+ // events.append_once -> 1 appended | 0 duplicate (deduped on eventId) | <0 error.
4809
+ // Idempotent append: a retried call with the same eventId never doubles the event.
4810
+ // @ts-ignore: decorator
4811
+ @external("env", "data.append_once")
4812
+ export declare function appendOnce(
4813
+ handle: u32,
4814
+ keyPtr: usize,
4815
+ keyLen: i32,
4816
+ evidPtr: usize,
4817
+ evidLen: i32,
4818
+ evPtr: usize,
4819
+ evLen: i32
4820
+ ): i32;
4821
+
4822
+ // records.enqueue -> 0 ok | <0 error (Conflict if a concurrent write won, NotFound
4823
+ // if absent). A version-checked replace of an existing record's value.
4824
+ // @ts-ignore: decorator
4825
+ @external("env", "data.enqueue")
4826
+ export declare function enqueue(
4827
+ handle: u32,
4828
+ keyPtr: usize,
4829
+ keyLen: i32,
4830
+ valPtr: usize,
4831
+ valLen: i32,
4832
+ idemPtr: usize
4833
+ ): i32;
4834
+
4808
4835
  // Copy the last stashed variable-length result into outPtr (outLen must equal
4809
4836
  // the length the producing op returned). Returns bytes written, or -1 if the
4810
4837
  // buffer is too small.
@@ -8909,8 +8936,8 @@ export class Date {
8909
8936
  return ms;
8910
8937
  }
8911
8938
 
8912
- @inline static now(): i64 {
8913
- return <i64>Date_binding.now();
8939
+ @inline static now(): u64 {
8940
+ return Date_binding.now();
8914
8941
  }
8915
8942
 
8916
8943
  // It can parse only ISO 8601 inputs like YYYY-MM-DDTHH:MM:SS.000Z
@@ -18737,7 +18764,14 @@ export function __toildbReadVersion(): i64 {
18737
18764
  /// before each decode and reads it after; the dispatch marks it AFTER the
18738
18765
  /// transform runs, so a transform that itself reads (resetting the flag) does not
18739
18766
  /// clear the outer migration.
18740
- let __toildbMigratedFlag: bool = false;
18767
+ // \`@lazy\`: initialized on first access rather than in module-init order. A value
18768
+ // type's woven \`decodeInto\` (which, under the cross-file \`@migrate\` convention,
18769
+ // lives in a DIFFERENT module than this one) compiles these exported accessors on
18770
+ // demand; @lazy breaks the init-order dependency so that never trips a
18771
+ // use-before-declaration that a plain global would in that circular import graph.
18772
+ // @ts-ignore: decorator
18773
+ @lazy
18774
+ var __toildbMigratedFlag: bool = false;
18741
18775
  export function __toildbResetMigrated(): void { __toildbMigratedFlag = false; }
18742
18776
  export function __toildbMarkMigrated(): void { __toildbMigratedFlag = true; }
18743
18777
  export function __toildbWasMigrated(): bool { return __toildbMigratedFlag; }
@@ -18822,10 +18856,12 @@ export class Documents<K, V> {
18822
18856
  results.push(null);
18823
18857
  continue;
18824
18858
  }
18859
+ const ver = <i64>load<u32>(out.dataStart + off);
18860
+ off += 4;
18825
18861
  const len = <i32>load<u32>(out.dataStart + off);
18826
18862
  off += 4;
18827
18863
  const v = instantiate<V>();
18828
- v.decodeInto(out.subarray(off, off + len));
18864
+ v.decodeIntoVersioned(out.subarray(off, off + len), ver);
18829
18865
  off += len;
18830
18866
  results.push(v);
18831
18867
  }
@@ -18860,6 +18896,15 @@ export class Documents<K, V> {
18860
18896
  return v;
18861
18897
  }
18862
18898
 
18899
+ /// Atomically replace an EXISTING record's value, version-checked: returns true
18900
+ /// if applied, false if a concurrent write changed the record first (optimistic
18901
+ /// concurrency - re-read and retry) or the record is absent.
18902
+ enqueue(key: K, value: V): bool {
18903
+ const kb = key.encode();
18904
+ const vb = value.encode();
18905
+ return toildbHost.enqueue(this.__handle, kb.dataStart, kb.byteLength, vb.dataStart, vb.byteLength, 0) == 0;
18906
+ }
18907
+
18863
18908
  /// Delete the record (idempotent).
18864
18909
  delete(key: K): void {
18865
18910
  const kb = key.encode();
@@ -19022,10 +19067,12 @@ export class Membership<K, M> {
19022
19067
  const count = load<u32>(blob.dataStart + off);
19023
19068
  off += 4;
19024
19069
  for (let i: u32 = 0; i < count; i++) {
19070
+ const ver = <i64>load<u32>(blob.dataStart + off);
19071
+ off += 4;
19025
19072
  const len = <i32>load<u32>(blob.dataStart + off);
19026
19073
  off += 4;
19027
19074
  const m = instantiate<M>();
19028
- m.decodeInto(blob.subarray(off, off + len));
19075
+ m.decodeIntoVersioned(blob.subarray(off, off + len), ver);
19029
19076
  out.push(m);
19030
19077
  off += len;
19031
19078
  }
@@ -19134,6 +19181,20 @@ export class Events<K, V> {
19134
19181
  toildbHost.append(this.__handle, kb.dataStart, kb.byteLength, eb.dataStart, eb.byteLength, 0);
19135
19182
  }
19136
19183
 
19184
+ /// Append \`event\` exactly once per \`eventId\`: a retried call with the same id is
19185
+ /// a no-op and returns false; the first call appends and returns true. Idempotent
19186
+ /// under at-least-once delivery / client retries (dedup on the caller-chosen id).
19187
+ appendOnce(key: K, eventId: string, event: V): bool {
19188
+ const kb = key.encode();
19189
+ const idb = Uint8Array.wrap(String.UTF8.encode(eventId));
19190
+ const eb = event.encode();
19191
+ const status = toildbHost.appendOnce(
19192
+ this.__handle, kb.dataStart, kb.byteLength,
19193
+ idb.dataStart, idb.byteLength, eb.dataStart, eb.byteLength);
19194
+ if (status < 0) unreachable();
19195
+ return status == 1;
19196
+ }
19197
+
19137
19198
  /// The newest \`limit\` events, newest first. Decodes each framed event into a
19138
19199
  /// \`V\`. The host frames them as \`u32 count\` then per event \`u32 len + bytes\`.
19139
19200
  latest(key: K, limit: i32): V[] {
@@ -19146,10 +19207,12 @@ export class Events<K, V> {
19146
19207
  const count = load<u32>(blob.dataStart + off);
19147
19208
  off += 4;
19148
19209
  for (let i: u32 = 0; i < count; i++) {
19210
+ const ver = <i64>load<u32>(blob.dataStart + off);
19211
+ off += 4;
19149
19212
  const len = <i32>load<u32>(blob.dataStart + off);
19150
19213
  off += 4;
19151
19214
  const ev = instantiate<V>();
19152
- ev.decodeInto(blob.subarray(off, off + len));
19215
+ ev.decodeIntoVersioned(blob.subarray(off, off + len), ver);
19153
19216
  out.push(ev);
19154
19217
  off += len;
19155
19218
  }
@@ -29018,7 +29081,7 @@ declare class Date {
29018
29081
  millisecond: i32
29019
29082
  ): i64;
29020
29083
  /** Returns the current UTC timestamp in milliseconds. */
29021
- static now(): i64;
29084
+ static now(): u64;
29022
29085
  /** Parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. */
29023
29086
  static parse(dateString: string): Date;
29024
29087
  static fromString(dateString: string): Date;
@@ -30226,7 +30289,7 @@ declare interface Float64Array {
30226
30289
  // FIXME: remove
30227
30290
  declare function offsetof<T>(fieldName?: string): usize;
30228
30291
  declare function idof<T>(): u32;
30229
- `};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
30292
+ `};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 h=At,Pn=P.argv.indexOf("--wasm");if(~Pn){let e=String(P.argv[Pn+1]);P.argv.splice(Pn,2),h=await import(new URL(e,dn.pathToFileURL(P.cwd()+"/")))}var Vn=sn.createRequire(import.meta.url),Xn=P.platform==="win32",_=Xn?`\r
30230
30293
  `:`
30231
- `,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 r=e[n],s=Y[n];s&&s.type==="b"?r&&t.push(`--${n}`):Array.isArray(r)?r.forEach(a=>{t.push(`--${n}`,String(a))}):t.push(`--${n}`,String(r))}),t}async function wt(e,t={}){typeof e=="string"&&(e={[`input${_}`]:e});let n=["--outFile","binary","--textFile","text"];qn(t,n);let r={},s=await Be(n.concat(Object.keys(e)),{readFile:a=>Object.prototype.hasOwnProperty.call(e,a)?e[a]:null,writeFile:(a,u)=>{r[a]=u},listFiles:()=>[]});return Object.assign(s,r)}async function Be(e,t){Array.isArray(e)||(e=qn(e)),t||(t={});let n=t.stats||new Cn,r=n.begin(),s=0,a=0,u=0,f=(Hn||"").split(".");f.length===3&&(a=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(o=>{b.write(`${G.yellow("WARNING ")}Unknown option '${o}'${E}`)});let Jn=m.trailing;Jn.length&&b.write(`${G.yellow("WARNING ")}Unsupported trailing arguments: ${Jn.join(" ")}${E}`);let K=null,R=null,z=(o,l={})=>(o&&b.write(`${G.red("FAILURE ")}${o.stack.replace(/^ERROR: /i,"")}${E}`),R&&R.dispose(),n.total||(n.total=n.end(r)),Object.assign({error:o,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 o=i.help?h:b,l=i.help?zn:G;return o.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 o=N.options;if(o&&(i=Un(Y,i,o,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(o){return[...new Set(o)]}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,a,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 o=i.use;for(let l=0,c=o.length;l<c;++l){let p=o[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 o=0,l=U.length;o<l;++o){let c=U[o].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 o=0,l=U.length;o<l;++o){let c=U[o].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 o=Zn(i.transform);for(let l=0,c=o.length;l<c;++l){let p=o[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: "+o[l]));an.push(v)}}try{an=an.map(o=>(typeof o=="function"&&(Object.assign(o.prototype,{program:B,binaryen:hn,baseDir:w,stdout:h,stderr:b,log:console.error,readFile:d,writeFile:g,listFiles:y}),o=new o),o))}catch(o){return z(o)}async function Bn(o,...l){for(let c=0,p=an.length;c<p;++c){let A=an[c];if(typeof A[o]=="function")try{let v=n.begin();n.transformCount++,await A[o](...l),n.transformTime+=n.end(v)}catch(v){return v}}}Object.keys(H).forEach(o=>{if(o.includes("/"))return;let l=n.begin();n.parseCount++,x.parse(B,H[o],P+o+_,!1),n.parseTime+=n.end(l)});let on=[];if(i.lib){let o=i.lib;typeof o=="string"&&(o=o.split(",")),on.push(...o.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(o,l){let c=null,p=null;if(!o.startsWith(P))(c=await d(p=o+_,w))==null&&(c=await d(p=o+"/index"+_,w))==null&&(p=o+_,c=await d(o+_t,w));else{let A=o.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=o.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(o=[]){do{let l=x.nextFile(B);if(l==null)break;o.push(l)}while(!0);return o}async function $n(){let o;for(;(o=Le()).length;){let c=[];for(let p of o){let A=x.getDependee(B,p);c.push(Oe(p,A))}c=await Promise.all(c);for(let p=0,A=o.length;p<A;++p){let v=o[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 o=String(i.runtime),l=`rt/index-${o}`,c=H[l];if(c==null){if(l=o,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 o=0,l=e.length;o<l;++o){let c=String(e[o]),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 o=await $n();if(o)return o}{let o=await Bn("afterParse",B.parser);if(o)return z(o)}{let o=await $n();if(o)return o}{let o=n.begin();n.initializeCount++;try{x.initializeProgram(B)}catch(l){I("initialize",l)}n.initializeTime+=n.end(o)}{let o=await Bn("afterInitialize",B);if(o)return z(o)}{let o=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(o)}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 o=Error(`${ln} compile error(s)`);return o.stack=o.message,z(o)}{let o=await Bn("afterCompile",R);if(o)return z(o)}if(ln=gn(B,b,i.disableWarning,t.reportDiagnostic,G.enabled),ln){let o=Error(`${ln} afterCompile error(s)`);return o.stack=o.message,z(o)}if(!i.noValidate){let o=n.begin();n.validateCount++;let l=x.validate(K);if(n.validateTime+=n.end(o),!l)return z(Error("validate error"))}if(i.trapMode==="clamp"||i.trapMode==="js"){let o=n.begin();try{R.runPasses([`trap-mode-${i.trapMode}`])}catch(l){I("runPasses",l)}n.compileTime+=n.end(o)}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(o=>{yn.includes(o=o.trim())||yn.push(o)}));{let o=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(o)}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 o=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=o.includes("esm"),Fn=!q&&o.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(o){return z(o)}return n.total=n.end(r),i.stats&&b.write(n.toString()),z(null);async function ee(o,l){let c=F.resolve(l,o);try{return n.readCount++,await j.promises.readFile(c,"utf8")}catch{return null}}async function te(o,l,c){try{n.writeCount++;let p=F.resolve(c,F.dirname(o)),A=F.join(p,F.basename(o));return await j.promises.mkdir(p,{recursive:!0}),await j.promises.writeFile(A,l),!0}catch{return!1}}async function ie(o,l){try{return n.readCount++,(await j.promises.readdir(F.join(l,o))).filter(c=>Tt.test(c))}catch{return null}}function vn(o){vn.used||(vn.used=!0,n.writeCount++),h.write(o)}function I(o,l){let c=zn.red("\u258C ");console.error([E,c,"Whoops, the ToilScript compiler has crashed during ",o," :-(",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 r=await n(e,t),s=F.join(t,e);if(!r)return null;let a;try{a=JSON.parse(r)}catch(u){throw new Error(`Toilconfig is not valid json: ${s}`,{cause:u})}if(a.options&&!jn(a.options))throw new Error(`Toilconfig.options is not an object: ${s}`);if(a.include&&!Array.isArray(a.include))throw new Error(`Toilconfig.include is not an array: ${s}`);if(a.targets){if(!jn(a.targets))throw new Error(`Toilconfig.targets is not an object: ${s}`);let u=Object.keys(a.targets);for(let f=0;f<u.length;f++){let h=u[f];if(!jn(a.targets[h]))throw new Error(`Toilconfig.targets.${h} is not an object: ${s}`)}}if(a.extends&&typeof a.extends!="string")throw new Error(`Toilconfig.extends is not a string: ${s}`);return a}function gn(e,t,n,r,s){typeof s>"u"&&t&&(s=t.isTTY);let a=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(r){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;r({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)&&++a}while(!0);return a}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)),r=n.map(m=>t(this[`${m}Time`])),s=n.map(m=>this[`${m}Count`].toString()),a=n.reduce((m,i)=>Math.max(i.length,m),0),u=r.reduce((m,i)=>Math.max(i.length,m),0),f=s.reduce((m,i)=>Math.max(i.length,m),0),h=a+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(a)}\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(a)} \u2502 ${r[m].padStart(u)} \u2502 ${s[m].padStart(f)} \u2502${E}`);b.push(`\u251C\u2500${"\u2500".repeat(a)}\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 r=ze(Tn.length(n));Tn.write(n,r,0),n=r}this.push(n)},t.reset=function(){t.length=0},t.toBuffer=function(){let n=0,r=0,s=this.length;for(;r<s;)n+=this[r++].length;let a=ze(n);for(n=r=0;r<s;)a.set(this[r],n),n+=this[r].length,++r;return a},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};
30294
+ `,Gn=Xn?"\\":"/",T=".ts",_t=`.d${T}`,xn=new RegExp("\\"+T+"$"),Tt=new RegExp("^(?!.*\\.d\\"+T+"$).*\\"+T+"$");function Te(e){return e.replace(/-/g,"_").toUpperCase()}function Ct(e){return typeof e=="string"&&e!==""}var jn=Fe,zt=Y,V=Ee,j=Ae,St=_e,Se=3,we=0;function qn(e,t=[]){return Object.keys(e||{}).forEach(n=>{let a=e[n],s=Y[n];s&&s.type==="b"?a&&t.push(`--${n}`):Array.isArray(a)?a.forEach(o=>{t.push(`--${n}`,String(o))}):t.push(`--${n}`,String(a))}),t}async function wt(e,t={}){typeof e=="string"&&(e={[`input${T}`]:e});let n=["--outFile","binary","--textFile","text"];qn(t,n);let a={},s=await Be(n.concat(Object.keys(e)),{readFile:o=>Object.prototype.hasOwnProperty.call(e,o)?e[o]:null,writeFile:(o,f)=>{a[o]=f},listFiles:()=>[]});return Object.assign(s,a)}async function Be(e,t){Array.isArray(e)||(e=qn(e)),t||(t={});let n=t.stats||new Cn,a=n.begin(),s=0,o=0,f=0,c=(jn||"").split(".");c.length===3&&(o=parseInt(c[0])|0,s=parseInt(c[1])|0,f=parseInt(c[2])|0);let x=t.stdout||Kn(),b=t.stderr||Kn(),p=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),H=new en(b);i.noColors&&(zn.enabled=!1,H.enabled=!1);let Yn=m.unknown;Yn.length&&Yn.forEach(r=>{b.write(`${H.yellow("WARNING ")}Unknown option '${r}'${_}`)});let Jn=m.trailing;Jn.length&&b.write(`${H.yellow("WARNING ")}Unsupported trailing arguments: ${Jn.join(" ")}${_}`);let K=null,R=null,z=(r,l={})=>(r&&b.write(`${H.red("FAILURE ")}${r.stack.replace(/^ERROR: /i,"")}${_}`),R&&R.dispose(),n.total||(n.total=n.end(a)),Object.assign({error:r,stdout:x,stderr:b,stats:n},l));if(i.version)return x.write(`Version ${jn}${_}`),z(null);let S=A.normalize(i.baseDir||"."),X=tn(i.config||"toilconfig.json",S),Sn=A.basename(X),J=A.dirname(X),N=await Ce(Sn,J,p),De=N!=null&&Array.isArray(N.entries)&&N.entries.length;if(i.help||!e.length&&!De){let r=i.help?x:b,l=i.help?zn:H;return r.write([l.white("SYNTAX")," "+l.cyan("toilscript")+" [entryFile ...] [options]","",l.white("EXAMPLES")," "+l.cyan("toilscript")+" hello"+T," "+l.cyan("toilscript")+" hello"+T+" -o hello.wasm -t hello.wat"," "+l.cyan("toilscript")+" hello1"+T+" hello2"+T+" -o -O > hello.wasm"," "+l.cyan("toilscript")+" --config toilconfig.json --target release","",l.white("OPTIONS")].concat(ve(Y,24,_)).join(_)+_),z(null)}if(!(M.promises&&M.promises.readFile)){if(p===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 r=N.options;if(r&&(i=Un(Y,i,r,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=A.basename(X),J=A.dirname(X),wn.has(X))break;wn.add(X),N=await Ce(Sn,J,p)}else break}if(Mn(Y,i),i.showConfig)return b.write(JSON.stringify({options:i,entries:e},null,2)),z(null);function Zn(r){return[...new Set(r)]}let w,rn,mn,C=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(C,0),h.setDebugInfo(C,!!i.debug),h.setRuntime(C,rn),h.setNoAssert(C,i.noAssert),h.setExportMemory(C,!i.noExportMemory),h.setImportMemory(C,i.importMemory),h.setInitialMemory(C,i.initialMemory>>>0),h.setMaximumMemory(C,i.maximumMemory>>>0),h.setSharedMemory(C,i.sharedMemory),h.setImportTable(C,i.importTable),h.setExportTable(C,i.exportTable),i.exportStart!=null&&h.setExportStart(C,Ct(i.exportStart)?i.exportStart:"_start"),h.setMemoryBase(C,i.memoryBase>>>0),h.setTableBase(C,i.tableBase>>>0),h.setSourceMap(C,i.sourceMap!=null),h.setUncheckedBehavior(C,mn),h.setNoUnsafe(C,i.noUnsafe),h.setPedantic(C,i.pedantic),h.setLowMemoryLimit(C,i.lowMemoryLimit>>>0),h.setExportRuntime(C,i.exportRuntime),h.setBundleVersion(C,o,s,f),!i.stackSize&&rn===2&&(i.stackSize=h.DEFAULT_STACK_SIZE),h.setStackSize(C,i.stackSize),h.setBindingsHint(C,i.bindings&&i.bindings.length>0),i.use){let r=i.use;for(let l=0,u=r.length;l<u;++l){let d=r[l],F=d.indexOf("=");if(F<0)return z(Error(`Global alias '${d}' is invalid.`));let v=d.substring(0,F).trim(),E=d.substring(F+1).trim();if(!v.length)return z(Error(`Global alias '${d}' is invalid.`));h.addGlobalAlias(C,v,E)}}let U;if((U=i.disable)!=null){typeof U=="string"&&(U=U.split(","));for(let r=0,l=U.length;r<l;++r){let u=U[r].trim(),d=h[`FEATURE_${Te(u)}`];if(!d)return z(Error(`Feature '${u}' is unknown.`));h.setFeature(C,d,!1)}}if((U=i.enable)!=null){typeof U=="string"&&(U=U.split(","));for(let r=0,l=U.length;r<l;++r){let u=U[r].trim(),d=h[`FEATURE_${Te(u)}`];if(!d)return z(Error(`Feature '${u}' is unknown.`));h.setFeature(C,d,!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(C,Z,$),w=h.newProgram(C);let an=[];if(Array.isArray(t.transforms)&&an.push(...t.transforms),i.transform){let r=Zn(i.transform);for(let l=0,u=r.length;l<u;++l){let d=r[l].trim(),F,v;if(Vn.resolve)try{F=Vn.resolve(d,{paths:[P.cwd(),S]}),v=await import(dn.pathToFileURL(F)),v.default&&(v=v.default)}catch(E){try{v=Vn(F)}catch{return z(E)}}else try{v=await import(new URL(d,import.meta.url)),v.default&&(v=v.default)}catch(E){return z(E)}if(!v||typeof v!="function"&&typeof v!="object")return z(Error("not a transform: "+r[l]));an.push(v)}}try{an=an.map(r=>(typeof r=="function"&&(Object.assign(r.prototype,{program:w,binaryen:hn,baseDir:S,stdout:x,stderr:b,log:console.error,readFile:p,writeFile:g,listFiles:y}),r=new r),r))}catch(r){return z(r)}async function Bn(r,...l){for(let u=0,d=an.length;u<d;++u){let F=an[u];if(typeof F[r]=="function")try{let v=n.begin();n.transformCount++,await F[r](...l),n.transformTime+=n.end(v)}catch(v){return v}}}Object.keys(j).forEach(r=>{if(r.includes("/"))return;let l=n.begin();n.parseCount++,h.parse(w,j[r],V+r+T,!1),n.parseTime+=n.end(l)});let on=[];if(i.lib){let r=i.lib;typeof r=="string"&&(r=r.split(",")),on.push(...r.map(l=>l.trim())),on=Zn(on);for(let l=0,u=on.length;l<u;++l){let d=on[l],F;d.endsWith(T)?(F=[A.basename(d)],d=A.dirname(d)):F=await y(d,S)||[];for(let v of F){let E=await p(v,d);if(E==null)return z(Error(`Library file '${v}' not found.`));j[v.replace(xn,"")]=E;let O=n.begin();n.parseCount++,h.parse(w,E,V+v,!1),n.parseTime+=n.end(O)}}}i.path=i.path||[];let bn=new Map;async function Oe(r,l){let u=null,d=null;if(!r.startsWith(V))(u=await p(d=r+T,S))==null&&(u=await p(d=r+"/index"+T,S))==null&&(d=r+T,u=await p(r+_t,S));else{let F=r.substring(V.length),v=`${F}/index`;if(Object.prototype.hasOwnProperty.call(j,F))u=j[F],d=V+F+T;else if(Object.prototype.hasOwnProperty.call(j,v))u=j[v],d=V+v+T;else{for(let E of on)if((u=await p(F+T,E))!=null){d=V+F+T;break}else if((u=await p(v+T,E))!=null){d=V+v+T;break}if(u==null){let E=r.match(/^~lib\/((?:@[^/]+\/)?[^/]+)(?:\/(.+))?/);if(E){let O=E[1],q=E[2]||"index",Fn=bn.has(l)?bn.get(l):".",L=[],D=A.resolve(S,Fn).split(Gn);for(let B=D.length,k=Xn?1:0;B>=k;--B)D[B-1]!=="node_modules"&&L.push(`${D.slice(0,B).join(Gn)}${Gn}node_modules`);L.push(...i.path);for(let B of L.map(k=>A.relative(S,k))){let k=q;if((u=await p(A.join(B,O,k+T),S))!=null){d=`${V}${O}/${k}${T}`,bn.set(d.replace(xn,""),A.join(B,O));break}let un=`${q}/index`;if((u=await p(A.join(B,O,un+T),S))!=null){d=`${V}${O}/${un}${T}`,bn.set(d.replace(xn,""),A.join(B,O));break}}}}}}return u==null?null:{sourceText:u,sourcePath:d}}function Le(r=[]){do{let l=h.nextFile(w);if(l==null)break;r.push(l)}while(!0);return r}async function $n(){let r;for(;(r=Le()).length;){let u=[];for(let d of r){let F=h.getDependee(w,d);u.push(Oe(d,F))}u=await Promise.all(u);for(let d=0,F=r.length;d<F;++d){let v=r[d],E=u[d],O=n.begin();n.parseCount++,E?h.parse(w,E.sourceText,E.sourcePath,!1):h.parse(w,null,v+T,!1),n.parseTime+=n.end(O)}}let l=gn(w,b,i.disableWarning,t.reportDiagnostic,H.enabled);if(l){let u=Error(`${l} parse error(s)`);return u.stack=u.message,z(u)}}{let r=String(i.runtime),l=`rt/index-${r}`,u=j[l];if(u==null){if(l=r,u=await p(l+T,S),u==null)return z(Error(`Runtime '${A.resolve(S,l+T)}' is not found.`))}else l=`~lib/${l}`;let d=n.begin();n.parseCount++,h.parse(w,u,l+T,!0),n.parseTime+=n.end(d)}for(let r=0,l=e.length;r<l;++r){let u=String(e[r]),d=A.isAbsolute(u)?A.relative(S,u):A.normalize(u);d=d.replace(/\\/g,"/").replace(xn,"").replace(/\/$/,"");let F=await p(d+T,S);if(F==null){let E=`${d}/index${T}`;F=await p(E,S),F!=null?d=E:d+=T}else d+=T;let v=n.begin();n.parseCount++,h.parse(w,F,d,!0),n.parseTime+=n.end(v)}if(M.promises&&M.promises.readdir){let r=[],l=async(u,d)=>{let F;try{F=await M.promises.readdir(u,{withFileTypes:!0})}catch{return}for(let v of F){let E=v.name;if(v.isDirectory()){if(E==="node_modules"||E==="build"||E==="dist"||E.charAt(0)===".")continue;await l(A.join(u,E),d?d+"/"+E:E)}else E.endsWith(".migration"+T)&&r.push(d?d+"/"+E:E)}};await l(A.resolve(S),"");for(let u of r){let d=u.replace(/\\/g,"/"),F=await p(d,S);F!=null&&(n.parseCount++,h.parse(w,F,d,!1))}}{let r=await $n();if(r)return r}{let r=await Bn("afterParse",w.parser);if(r)return z(r)}{let r=await $n();if(r)return r}{let r=n.begin();n.initializeCount++;try{h.initializeProgram(w)}catch(l){I("initialize",l)}n.initializeTime+=n.end(r)}{let r=await Bn("afterInitialize",w);if(r)return z(r)}{let r=n.begin();n.compileCount++;try{K=h.compile(w)}catch(l){let u=gn(w,b,i.disableWarning,t.reportDiagnostic,H.enabled);if(u){let d=Error(`${u} compile error(s)`);return d.stack=d.message,z(d)}I("compile",l)}n.compileTime+=n.end(r)}R=hn.wrapModule(typeof K=="number"||K instanceof Number?h.getBinaryenModuleRef(K):K.ref);let ln=gn(w,b,i.disableWarning,t.reportDiagnostic,H.enabled);if(ln){let r=Error(`${ln} compile error(s)`);return r.stack=r.message,z(r)}{let r=await Bn("afterCompile",R);if(r)return z(r)}if(ln=gn(w,b,i.disableWarning,t.reportDiagnostic,H.enabled),ln){let r=Error(`${ln} afterCompile error(s)`);return r.stack=r.message,z(r)}if(!i.noValidate){let r=n.begin();n.validateCount++;let l=h.validate(K);if(n.validateTime+=n.end(r),!l)return z(Error("validate error"))}if(i.trapMode==="clamp"||i.trapMode==="js"){let r=n.begin();try{R.runPasses([`trap-mode-${i.trapMode}`])}catch(l){I("runPasses",l)}n.compileTime+=n.end(r)}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(r=>{yn.includes(r=r.trim())||yn.push(r)}));{let r=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 u=n.begin();n.emitCount++,l=R.emitBinary(),n.emitTime+=n.end(u)}catch(u){I("emitBinary (converge)",u)}do{try{n.optimizeCount++,h.optimize(K,Z,$,Qn,ne)}catch(d){I("optimize (converge)",d)}try{R.runPasses(yn)}catch(d){I("runPasses (converge)",d)}let u;try{let d=n.begin();n.emitCount++,u=R.emitBinary(),n.emitTime+=n.end(d)}catch(d){I("emitBinary (converge)",d)}if(u.length>=l.length){u.length>l.length&&b.write(`Last converge was suboptimal.${_}`);break}l=u}while(!0)}n.optimizeTime+=n.end(r)}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 r=i.bindings||[],l=!1,u=i.outFile!=null,d=i.textFile!=null,F=u||d,v=u&&i.outFile.length>0||d&&i.textFile.length>0,E=v?(i.outFile||i.textFile).replace(/\.\w+$/,""):null,O=v?A.basename(E):"output";if(h.setBasenameHint(C,O),i.outFile!=null){let L=i.sourceMap!=null?i.sourceMap.length?i.sourceMap:`./${O}.wasm.map`:null,D=n.begin();n.emitCount++;let B;try{B=R.emitBinary(L)}catch(k){I("emitBinary",k)}if(n.emitTime+=n.end(D),i.outFile.length?Q.push(g(i.outFile,B.binary,S)):(l=!0,vn(B.binary)),B.sourceMap!="")if(i.outFile.length){let k=JSON.parse(B.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(w,re.replace(xn,""));if(ae==null)return z(Error(`Source of file '${re}' not found.`));un[En]=ae}k.sourcesContent=un,Q.push(g(A.join(A.dirname(i.outFile),A.basename(L)).replace(/^\.\//,""),JSON.stringify(k),S))}else b.write(`Skipped source map (no output path)${_}`)}if(i.textFile!=null||!F){let L=n.begin();n.emitCount++;let D;try{hn.setOptimizeStackIR(!0),D=i.textFile?.endsWith(".wast")?R.emitText():R.emitStackIR()}catch(B){I("emitText",B)}n.emitTime+=n.end(L),i.textFile!=null&&i.textFile.length?Q.push(g(i.textFile,D,S)):l||vn(D)}let q=r.includes("esm"),Fn=!q&&r.includes("raw");if(q||Fn)if(E){let L=n.begin();n.emitCount++;let D;try{D=h.buildTSD(w,q)}catch(B){I("buildTSD",B)}n.emitTime+=n.end(L),Q.push(g(E+".d.ts",D,S))}else b.write(`Skipped TypeScript binding (no output path)${_}`);if(q||Fn)if(E){let L=n.begin();n.emitCount++;let D;try{D=h.buildJS(w,q)}catch(B){I("buildJS",B)}n.emitTime+=n.end(L),Q.push(g(E+".js",D,S))}else b.write(`Skipped JavaScript binding (no output path)${_}`);if(i.rpcModule!=null&&i.rpcModule.length){let L=n.begin();n.emitCount++;let D;try{D=h.buildServerModule(w,i.rpcRuntime||"toiljs/io")}catch(B){I("buildServerModule",B)}n.emitTime+=n.end(L),D!=null&&Q.push(g(i.rpcModule,D,S))}}try{await Promise.all(Q)}catch(r){return z(r)}return n.total=n.end(a),i.stats&&b.write(n.toString()),z(null);async function ee(r,l){let u=A.resolve(l,r);try{return n.readCount++,await M.promises.readFile(u,"utf8")}catch{return null}}async function te(r,l,u){try{n.writeCount++;let d=A.resolve(u,A.dirname(r)),F=A.join(d,A.basename(r));return await M.promises.mkdir(d,{recursive:!0}),await M.promises.writeFile(F,l),!0}catch{return!1}}async function ie(r,l){try{return n.readCount++,(await M.promises.readdir(A.join(l,r))).filter(u=>Tt.test(u))}catch{return null}}function vn(r){vn.used||(vn.used=!0,n.writeCount++),x.write(r)}function I(r,l){let u=zn.red("\u258C ");console.error([_,u,"Whoops, the ToilScript compiler has crashed during ",r," :-(",_,u,_,(typeof l.stack=="string"?[u,"Here is the stack trace hinting at the problem, perhaps it's useful?",_,u,_,l.stack.replace(/^/mg,u),_]:[u,"There is no stack trace. Perhaps a Binaryen exception above / in console?",_,u,_,u,"> "+l.stack,_]).join(""),u,_,u,"If you see where the error is, feel free to send us a pull request. If not,",_,u,"please let us know: https://github.com/dacely-cloud/toilscript/issues",_,u,_,u,"Thank you!",_].join("")),P.exit(1)}}function Hn(e){return Object.prototype.toString.call(e)==="[object Object]"}async function Ce(e,t,n){let a=await n(e,t),s=A.join(t,e);if(!a)return null;let o;try{o=JSON.parse(a)}catch(f){throw new Error(`Toilconfig is not valid json: ${s}`,{cause:f})}if(o.options&&!Hn(o.options))throw new Error(`Toilconfig.options is not an object: ${s}`);if(o.include&&!Array.isArray(o.include))throw new Error(`Toilconfig.include is not an array: ${s}`);if(o.targets){if(!Hn(o.targets))throw new Error(`Toilconfig.targets is not an object: ${s}`);let f=Object.keys(o.targets);for(let c=0;c<f.length;c++){let x=f[c];if(!Hn(o.targets[x]))throw new Error(`Toilconfig.targets.${x} is not an object: ${s}`)}}if(o.extends&&typeof o.extends!="string")throw new Error(`Toilconfig.extends is not a string: ${s}`);return o}function gn(e,t,n,a,s){typeof s>"u"&&t&&(s=t.isTTY);let o=0;do{let x=h.nextDiagnostic(e);if(!x)break;if(t){let b=p=>{if(n==null)return!1;if(!n.length)return!0;let g=h.getDiagnosticCode(p);return n.includes(g)};(h.isError(x)||!b(x))&&t.write(h.formatDiagnostic(x,s,!0)+_+_)}if(a){let b=function(g){return g&&{start:h.getRangeStart(g),end:h.getRangeEnd(g),source:p(h.getRangeSource(g))}||null},p=function(g){return g&&{normalizedPath:h.getSourceNormalizedPath(g)}||null};var f=b,c=p;a({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)&&++o}while(!0);return o}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 P.hrtime()}end(t){let n=P.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)),a=n.map(m=>t(this[`${m}Time`])),s=n.map(m=>this[`${m}Count`].toString()),o=n.reduce((m,i)=>Math.max(i.length,m),0),f=a.reduce((m,i)=>Math.max(i.length,m),0),c=s.reduce((m,i)=>Math.max(i.length,m),0),x=o+f+c+6,b=[];b.push(`\u256D\u2500${"\u2500".repeat(x)}\u2500\u256E${_}`);let p="Stats";b.push(`\u2502 ${p}${" ".repeat(x-p.length)} \u2502${_}`),b.push(`\u255E\u2550${"\u2550".repeat(o)}\u2550\u2564\u2550${"\u2550".repeat(f)}\u2550\u2564\u2550${"\u2550".repeat(c)}\u2550\u2561${_}`);for(let m=0,i=n.length;m<i;++m)b.push(`\u2502 ${n[m].padEnd(o)} \u2502 ${a[m].padStart(f)} \u2502 ${s[m].padStart(c)} \u2502${_}`);b.push(`\u251C\u2500${"\u2500".repeat(o)}\u2500\u2534\u2500${"\u2500".repeat(f)}\u2500\u2534\u2500${"\u2500".repeat(c)}\u2500\u2524${_}`);let g=`Took ${t(this.total)}`;b.push(`\u2502 ${g}${" ".repeat(x-g.length)} \u2502${_}`);let y=`${this.readCount} reads, ${this.writeCount} writes`;return b.push(`\u2502 ${y}${" ".repeat(x-y.length)} \u2502${_}`),b.push(`\u2570\u2500${"\u2500".repeat(x)}\u2500\u256F${_}`),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 a=ze(Tn.length(n));Tn.write(n,a,0),n=a}this.push(n)},t.reset=function(){t.length=0},t.toBuffer=function(){let n=0,a=0,s=this.length;for(;a<s;)n+=this[a++].length;let o=ze(n);for(n=a=0;a<s;)o.set(this[a],n),n+=this[a].length,++a;return o},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,j as libraryFiles,V as libraryPrefix,Be as main,zt as options,Bt as tscOptions,jn as version};
30232
30295
  //# sourceMappingURL=cli.js.map