toilscript 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NOTICE CHANGED
@@ -1,4 +1,4 @@
1
- The following authors have all licensed their contributions to AssemblyScript
1
+ The following authors have all licensed their contributions to ToilScript
2
2
  under the licensing terms detailed in LICENSE:
3
3
 
4
4
  * Daniel Wirtz <dcode@dcode.io>
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <a href="https://www.assemblyscript.org" target="_blank" rel="noopener"><img width="100" src="https://avatars1.githubusercontent.com/u/28916798?s=200&v=4" alt="AssemblyScript logo"></a>
2
+ <a href="https://toil.org" target="_blank" rel="noopener"><img width="256" src="media/icon.png" alt="ToilScript logo"></a>
3
3
  </p>
4
4
 
5
5
  <p align="center">
@@ -13,15 +13,6 @@
13
13
 
14
14
  **ToilScript is a fork of [AssemblyScript](https://github.com/AssemblyScript/assemblyscript)** that tracks the latest upstream and adds language features not yet available in the official release.
15
15
 
16
- ### Added features
17
-
18
- - **Closures** — full closure support with captured variables
19
- - **Try-catch-finally** — exception handling (a `throw` must be an `Error` or a subclass)
20
-
21
- ### How it's built
22
-
23
- ToilScript is the latest AssemblyScript `main` (Binaryen `129.0.0-nightly`, BigInt-based i64) with the closure and exception-handling work — originally from the [btc-vision](https://github.com/btc-vision/assemblyscript) fork — merged on top. The compiler's config file defaults to `toilconfig.json` (instead of `asconfig.json`).
24
-
25
16
  ---
26
17
 
27
18
  ## Installation
@@ -32,7 +23,7 @@ npm install toilscript
32
23
 
33
24
  ### Usage
34
25
 
35
- This fork is a drop-in replacement for AssemblyScript. Simply replace your import:
26
+ This fork is a drop-in replacement for ToilScript. Simply replace your import:
36
27
 
37
28
  ```json
38
29
  {
@@ -42,47 +33,21 @@ This fork is a drop-in replacement for AssemblyScript. Simply replace your impor
42
33
  }
43
34
  ```
44
35
 
45
- Or if migrating from official AssemblyScript:
36
+ Or if migrating from official ToilScript:
46
37
 
47
38
  ```sh
48
- npm uninstall assemblyscript
39
+ npm uninstall toilscript
49
40
  npm install toilscript
50
41
  ```
51
42
 
52
- The CLI commands remain the same:
43
+ The CLI is `toilscript` (with `toilinit` to scaffold a project):
53
44
 
54
45
  ```sh
55
- npx asc your-file.ts --outFile output.wasm
46
+ npx toilscript your-file.ts --outFile output.wasm
56
47
  ```
57
48
 
58
49
  ---
59
50
 
60
- ## Original README
61
-
62
- <p align="justify"><strong>AssemblyScript</strong> compiles a variant of <a href="http://www.typescriptlang.org">TypeScript</a> (basically JavaScript with types) to <a href="http://webassembly.org">WebAssembly</a> using <a href="https://github.com/WebAssembly/binaryen">Binaryen</a>. It generates lean and mean WebAssembly modules while being just an <code>npm install</code> away.</p>
63
-
64
- <h3 align="center">
65
- <a href="https://www.assemblyscript.org">About</a> &nbsp;·&nbsp;
66
- <a href="https://www.assemblyscript.org/getting-started.html">Getting&nbsp;started</a> &nbsp;·&nbsp;
67
- <a href="https://www.assemblyscript.org/examples.html">Examples</a> &nbsp;·&nbsp;
68
- <a href="https://www.assemblyscript.org/built-with-assemblyscript.html">Built with AssemblyScript</a>
69
- </h3>
70
- <br>
71
-
72
- <h2 align="center">Contributors</h2>
73
-
74
- <p align="center">
75
- <a href="https://www.assemblyscript.org/#contributors"><img src="https://www.assemblyscript.org/contributors.svg" alt="Contributor logos" width="720" /></a>
76
- </p>
77
-
78
- <h2 align="center">Thanks to our sponsors!</h2>
79
-
80
- <p align="justify">Most of the maintainers and contributors do this open source work in their free time. If you use AssemblyScript for a serious task or plan to do so, and you'd like us to invest more time on it, <a href="https://opencollective.com/assemblyscript/donate" target="_blank" rel="noopener">please donate</a> to our <a href="https://opencollective.com/assemblyscript" target="_blank" rel="noopener">OpenCollective</a>. By sponsoring this project, your logo will show up below. Thank you so much for your support!</p>
81
-
82
- <p align="center">
83
- <a href="https://www.assemblyscript.org/#sponsors"><img src="https://www.assemblyscript.org/sponsors.svg" alt="Sponsor logos" width="720" /></a>
84
- </p>
85
-
86
51
  ## Development instructions
87
52
 
88
53
  A development environment can be set up by cloning the repository:
@@ -40,7 +40,7 @@ if (typeof process.env.npm_config_user_agent === "string") {
40
40
  }
41
41
  }
42
42
 
43
- const asinitOptions = {
43
+ const toilinitOptions = {
44
44
  "help": {
45
45
  "category": "General",
46
46
  "description": "Prints this help message.",
@@ -63,7 +63,7 @@ const asinitOptions = {
63
63
  },
64
64
  };
65
65
 
66
- const cliOptions = optionsUtil.parse(process.argv.slice(2), asinitOptions);
66
+ const cliOptions = optionsUtil.parse(process.argv.slice(2), toilinitOptions);
67
67
 
68
68
  if (cliOptions.options.noColors) {
69
69
  stdoutColors.enabled = false;
@@ -76,14 +76,14 @@ function printHelp() {
76
76
  "Sets up a new ToilScript project or updates an existing one.",
77
77
  "",
78
78
  stdoutColors.white("SYNTAX"),
79
- " " + stdoutColors.cyan("asinit") + " directory [options]",
79
+ " " + stdoutColors.cyan("toilinit") + " directory [options]",
80
80
  "",
81
81
  stdoutColors.white("EXAMPLES"),
82
- " " + stdoutColors.cyan("asinit") + " .",
83
- " " + stdoutColors.cyan("asinit") + " ./newProject -y",
82
+ " " + stdoutColors.cyan("toilinit") + " .",
83
+ " " + stdoutColors.cyan("toilinit") + " ./newProject -y",
84
84
  "",
85
85
  stdoutColors.white("OPTIONS"),
86
- optionsUtil.help(asinitOptions, { noCategories: true })
86
+ optionsUtil.help(toilinitOptions, { noCategories: true })
87
87
  ].join("\n"));
88
88
  process.exit(0);
89
89
  }
@@ -126,7 +126,7 @@ if (fs.existsSync(packageFile)) {
126
126
  if ("type" in pkg && pkg["type"] !== "module") {
127
127
  console.error(stdoutColors.red([
128
128
  `Error: The "type" field in ${formatPath(packageFile)} is set to "${pkg["type"]}".`,
129
- ` asinit requires the "type" field to be set to "module" (ES modules).`
129
+ ` toilinit requires the "type" field to be set to "module" (ES modules).`
130
130
  ].join("\n")));
131
131
  process.exit(1);
132
132
  }
@@ -159,7 +159,7 @@ function createProject(answer) {
159
159
  ensureBuildDirectory();
160
160
  ensureGitignore();
161
161
  ensurePackageJson();
162
- ensureAsconfigJson();
162
+ ensureToilconfigJson();
163
163
  ensureTestsDirectory();
164
164
  ensureTestsIndexJs();
165
165
  ensureIndexHtml();
@@ -263,7 +263,7 @@ function ensureTsconfigJson() {
263
263
  console.log();
264
264
  }
265
265
 
266
- function ensureAsconfigJson() {
266
+ function ensureToilconfigJson() {
267
267
  console.log("- Making sure that 'toilconfig.json' is set up...");
268
268
  if (!fs.existsSync(toilconfigFile)) {
269
269
  fs.writeFileSync(toilconfigFile, JSON.stringify({
@@ -342,8 +342,8 @@ function ensureGitignore() {
342
342
  function ensurePackageJson() {
343
343
  console.log("- Making sure that 'package.json' contains the build commands...");
344
344
  const entryPath = path.relative(projectDir, entryFile).replace(/\\/g, "/");
345
- const buildDebug = "asc " + entryPath + " --target debug";
346
- const buildRelease = "asc " + entryPath + " --target release";
345
+ const buildDebug = "toilscript " + entryPath + " --target debug";
346
+ const buildRelease = "toilscript " + entryPath + " --target release";
347
347
  const buildAll = commands[pm].run + " asbuild:debug && " + commands[pm].run + " asbuild:release";
348
348
  if (!fs.existsSync(packageFile)) {
349
349
  fs.writeFileSync(packageFile, JSON.stringify({
@@ -26,7 +26,7 @@ if ((!hasSourceMaps || ~posCustomArgs) && !isDeno) {
26
26
  );
27
27
  if (status || signal) process.exitCode = 1;
28
28
  } else {
29
- const apiResult = (await import("../dist/asc.js")).main(process.argv.slice(2), {
29
+ const apiResult = (await import("../dist/cli.js")).main(process.argv.slice(2), {
30
30
  stdout: process.stdout,
31
31
  stderr: process.stderr
32
32
  });
package/dist/cli.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /// <reference path="./cli.generated.d.ts" />
2
+ export * from "types:toilscript/cli/index";
3
+ import * as cli from "types:toilscript/cli/index";
4
+ export default cli;
@@ -65,7 +65,7 @@ declare module "types:toilscript/lib/binaryen" {
65
65
  export { default } from "binaryen";
66
66
  }
67
67
  /**
68
- * Environment definitions for compiling AssemblyScript to JavaScript using tsc.
68
+ * Environment definitions for compiling ToilScript to JavaScript using tsc.
69
69
  *
70
70
  * Note that semantic differences require additional explicit conversions for full compatibility.
71
71
  * For example, when casting an i32 to an u8, doing `<u8>(someI32 & 0xff)` will yield the same
@@ -494,7 +494,7 @@ declare module "types:toilscript/src/glue/binaryen" {
494
494
  /**
495
495
  * @fileoverview Portable definitions for Binaryen's C-API.
496
496
  *
497
- * tsc uses the .js file next to it, while asc makes it a Wasm import.
497
+ * tsc uses the .js file next to it, while toilscript makes it a Wasm import.
498
498
  *
499
499
  * See: https://github.com/WebAssembly/binaryen/blob/main/src/binaryen-c.h
500
500
  *
@@ -2120,7 +2120,7 @@ declare module "types:toilscript/src/util" {
2120
2120
  }
2121
2121
  declare module "types:toilscript/src/tokenizer" {
2122
2122
  /**
2123
- * @fileoverview A TypeScript tokenizer modified for AssemblyScript.
2123
+ * @fileoverview A TypeScript tokenizer modified for ToilScript.
2124
2124
  *
2125
2125
  * The `Tokenizer` scans over a source file and returns one syntactic token
2126
2126
  * at a time that the parser will combine to an abstract syntax tree.
@@ -2861,7 +2861,7 @@ declare module "types:toilscript/src/resolver" {
2861
2861
  }
2862
2862
  declare module "types:toilscript/src/parser" {
2863
2863
  /**
2864
- * @fileoverview A TypeScript parser for the AssemblyScript subset.
2864
+ * @fileoverview A TypeScript parser for the ToilScript subset.
2865
2865
  *
2866
2866
  * Takes the tokens produced by the `Tokenizer` and builds an abstract
2867
2867
  * syntax tree composed of `Node`s wrapped in a `Source` out of it.
@@ -3007,7 +3007,7 @@ declare module "types:toilscript/src/parser" {
3007
3007
  }
3008
3008
  declare module "types:toilscript/src/program" {
3009
3009
  /**
3010
- * @fileoverview AssemblyScript's intermediate representation.
3010
+ * @fileoverview ToilScript's intermediate representation.
3011
3011
  *
3012
3012
  * The compiler uses Binaryen IR, which is fairly low level, as its
3013
3013
  * primary intermediate representation, with the following structures
@@ -3077,7 +3077,7 @@ declare module "types:toilscript/src/program" {
3077
3077
  /** Converts a unary postfix operator token to the respective operator kind. */
3078
3078
  function fromUnaryPostfixToken(token: Token): OperatorKind;
3079
3079
  }
3080
- /** Represents an AssemblyScript program. */
3080
+ /** Represents an ToilScript program. */
3081
3081
  export class Program extends DiagnosticEmitter {
3082
3082
  /** Compiler options. */
3083
3083
  options: Options;
@@ -3113,6 +3113,8 @@ declare module "types:toilscript/src/program" {
3113
3113
  elementsByDeclaration: Map<DeclarationStatement, DeclaredElement>;
3114
3114
  /** Element instances by unique internal name. */
3115
3115
  instancesByName: Map<string, Element>;
3116
+ /** Function decorated with `@main` (toil module entry point), if any. */
3117
+ mainFunction: FunctionPrototype | null;
3116
3118
  /** Classes wrapping basic types like `i32`. */
3117
3119
  wrapperClasses: Map<Type, Class>;
3118
3120
  /** Managed classes contained in the program, by id. */
@@ -3427,7 +3429,9 @@ declare module "types:toilscript/src/program" {
3427
3429
  /** Is compiled lazily. */
3428
3430
  Lazy = 1024,
3429
3431
  /** Is considered unsafe code. */
3430
- Unsafe = 2048
3432
+ Unsafe = 2048,
3433
+ /** Is the toil module entry point (`@main`). */
3434
+ Main = 4096
3431
3435
  }
3432
3436
  export namespace DecoratorFlags {
3433
3437
  /** Translates a decorator kind to the respective decorator flag. */
@@ -4082,7 +4086,7 @@ declare module "types:toilscript/src/program" {
4082
4086
  }
4083
4087
  declare module "types:toilscript/src/types" {
4084
4088
  /**
4085
- * @fileoverview Mappings from AssemblyScript types to WebAssembly types.
4089
+ * @fileoverview Mappings from ToilScript types to WebAssembly types.
4086
4090
  * @license Apache-2.0
4087
4091
  */
4088
4092
  import { Class, Program, OperatorKind, Function } from "types:toilscript/src/program";
@@ -4417,7 +4421,7 @@ declare module "types:toilscript/src/module" {
4417
4421
  /**
4418
4422
  * @fileoverview A thin wrapper around Binaryen's C-API.
4419
4423
  *
4420
- * The AssemblyScript compiler utilizes Binaryen's C-API directly. Even
4424
+ * The ToilScript compiler utilizes Binaryen's C-API directly. Even
4421
4425
  * though it currently imports binaryen.js, none of the JS APIs it
4422
4426
  * provides are used.
4423
4427
  *
@@ -6283,7 +6287,8 @@ declare module "types:toilscript/src/ast" {
6283
6287
  ExternalJs = 10,
6284
6288
  Builtin = 11,
6285
6289
  Lazy = 12,
6286
- Unsafe = 13
6290
+ Unsafe = 13,
6291
+ Main = 14
6287
6292
  }
6288
6293
  export namespace DecoratorKind {
6289
6294
  /** Returns the kind of the specified decorator name node. Defaults to {@link DecoratorKind.CUSTOM}. */
@@ -8857,7 +8862,7 @@ declare module "types:toilscript/src/bindings/js" {
8857
8862
  }
8858
8863
  declare module "types:toilscript/src/compiler" {
8859
8864
  /**
8860
- * @fileoverview The AssemblyScript compiler.
8865
+ * @fileoverview The ToilScript compiler.
8861
8866
  * @license Apache-2.0
8862
8867
  */
8863
8868
  import { Range, DiagnosticEmitter } from "types:toilscript/src/diagnostics";
@@ -9458,8 +9463,8 @@ declare module "types:toilscript/src/index-wasm" {
9458
9463
  * as a flat namespace.
9459
9464
  *
9460
9465
  * Note though that the compiler sources are written in "portable
9461
- * AssemblyScript" that can be compiled to both JavaScript with tsc and
9462
- * to WebAssembly with asc, and as such require additional glue code
9466
+ * ToilScript" that can be compiled to both JavaScript with tsc and
9467
+ * to WebAssembly with toilscript, and as such require additional glue code
9463
9468
  * depending on the target.
9464
9469
  *
9465
9470
  * When compiling to JavaScript `glue/js/index.js` must be included.
@@ -9632,7 +9637,7 @@ declare module "types:toilscript/src/extra/ast" {
9632
9637
  /**
9633
9638
  * @fileoverview Abstract Syntax Tree extras.
9634
9639
  *
9635
- * Provides serialization of the AssemblyScript AST back to it source form.
9640
+ * Provides serialization of the ToilScript AST back to it source form.
9636
9641
  *
9637
9642
  * @license Apache-2.0
9638
9643
  */
@@ -9742,7 +9747,7 @@ declare module "types:toilscript/src/index-js" {
9742
9747
  declare module "types:toilscript/src/index" {
9743
9748
  /**
9744
9749
  * @license
9745
- * Copyright 2020 Daniel Wirtz / The AssemblyScript Authors.
9750
+ * Copyright 2020 Daniel Wirtz / The ToilScript Authors.
9746
9751
  *
9747
9752
  * Licensed under the Apache License, Version 2.0 (the "License");
9748
9753
  * you may not use this file except in compliance with the License.
@@ -9764,12 +9769,12 @@ declare module "types:toilscript/src/index" {
9764
9769
  }
9765
9770
  declare module "types:toilscript/cli/index" {
9766
9771
  /**
9767
- * @fileoverview Definitions for asc.
9772
+ * @fileoverview Definitions for the toilscript CLI.
9768
9773
  * @license Apache-2.0
9769
9774
  */
9770
9775
  import { OptionDescription } from "types:toilscript/util/options";
9771
9776
  export { OptionDescription };
9772
- /** AssemblyScript version. */
9777
+ /** ToilScript version. */
9773
9778
  export const version: string;
9774
9779
  /** Available CLI options. */
9775
9780
  export const options: {
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * @license
3
- * The AssemblyScript frontend
4
- * Copyright 2026 Daniel Wirtz / The AssemblyScript Authors
3
+ * The ToilScript frontend
4
+ * Copyright 2026 Daniel Wirtz / The ToilScript Authors
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
7
  var se=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ue=Object.prototype.hasOwnProperty;var fn=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},ae=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Me(t))!Ue.call(e,s)&&s!==n&&se(e,s,{get:()=>t[s],enumerable:!(a=Ne(t,s))||a.enumerable});return e},Dn=(e,t,n)=>(ae(e,t,"default"),n&&ae(n,t,"default"));var le={};Q(le,{promises:()=>Pe});var Pe,ue=fn(()=>{"use strict";Pe={}});var fe={};Q(fe,{createRequire:()=>Ve});function Ve(){return function(t){throw new Error(`Cannot find module: '${t}'`)}}var ce=fn(()=>{"use strict"});var On={};Q(On,{argv:()=>Xe,cwd:()=>In,exit:()=>He,hrtime:()=>qe,platform:()=>je,umask:()=>Ge});function In(){return"."}function Ge(){return 0}function He(e=0){throw Error(`exit ${e}`)}function qe(e){var t=Ke.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 je,Xe,de,Ke,Ln=fn(()=>{"use strict";je="linux";Xe=[];de=globalThis.performance||{},Ke=de.now||function(){return new Date().getTime()}});var kn={};Q(kn,{basename:()=>Qe,delimiter:()=>it,dirname:()=>Je,extname:()=>nt,format:()=>et,isAbsolute:()=>Ye,join:()=>Ze,normalize:()=>pe,parse:()=>tt,relative:()=>$e,resolve:()=>cn,sep:()=>Rn,win32:()=>rt});function V(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function xe(e,t){for(var n="",a=0,s=-1,r=0,u,f=0;f<=e.length;++f){if(f<e.length)u=e.charCodeAt(f);else{if(u===47)break;u=47}if(u===47){if(!(s===f-1||r===1))if(s!==f-1&&r===2){if(n.length<2||a!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var p=n.lastIndexOf("/");if(p!==n.length-1){p===-1?(n="",a=0):(n=n.slice(0,p),a=n.length-1-n.lastIndexOf("/")),s=f,r=0;continue}}else if(n.length===2||n.length===1){n="",a=0,s=f,r=0;continue}}t&&(n.length>0?n+="/..":n="..",a=2)}else n.length>0?n+="/"+e.slice(s+1,f):n=e.slice(s+1,f),a=f-s-1;s=f,r=0}else u===46&&r!==-1?++r:r=-1}return n}function We(e,t){var n=t.dir||t.root,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),V(s),s.length!==0&&(e=s+"/"+e,t=s.charCodeAt(0)===47)}return e=xe(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."}function pe(e){if(V(e),e.length===0)return".";var t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;return e=xe(e,!t),e.length===0&&!t&&(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e}function Ye(e){return V(e),e.length>0&&e.charCodeAt(0)===47}function Ze(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var n=arguments[t];V(n),n.length>0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":pe(e)}function $e(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 a=e.length,s=a-n,r=1;r<t.length&&t.charCodeAt(r)===47;++r);for(var u=t.length,f=u-r,p=s<f?s:f,b=-1,d=0;d<=p;++d){if(d===p){if(f>p){if(t.charCodeAt(r+d)===47)return t.slice(r+d+1);if(d===0)return t.slice(r+d)}else s>p&&(e.charCodeAt(n+d)===47?b=d:d===0&&(b=0));break}var g=e.charCodeAt(n+d),y=t.charCodeAt(r+d);if(g!==y)break;g===47&&(b=d)}var m="";for(d=n+b+1;d<=a;++d)(d===a||e.charCodeAt(d)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(r+b):(r+=b,t.charCodeAt(r)===47&&++r,t.slice(r))}function Je(e){if(V(e),e.length===0)return".";for(var t=e.charCodeAt(0),n=t===47,a=-1,s=!0,r=e.length-1;r>=1;--r)if(t=e.charCodeAt(r),t===47){if(!s){a=r;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');V(e);var n=0,a=-1,s=!0,r;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var u=t.length-1,f=-1;for(r=e.length-1;r>=0;--r){var p=e.charCodeAt(r);if(p===47){if(!s){n=r+1;break}}else f===-1&&(s=!1,f=r+1),u>=0&&(p===t.charCodeAt(u)?--u===-1&&(a=r):(u=-1,a=f))}return n===a?a=f:a===-1&&(a=e.length),e.slice(n,a)}else{for(r=e.length-1;r>=0;--r)if(e.charCodeAt(r)===47){if(!s){n=r+1;break}}else a===-1&&(s=!1,a=r+1);return a===-1?"":e.slice(n,a)}}function nt(e){V(e);for(var t=-1,n=0,a=-1,s=!0,r=0,u=e.length-1;u>=0;--u){var f=e.charCodeAt(u);if(f===47){if(!s){n=u+1;break}continue}a===-1&&(s=!1,a=u+1),f===46?t===-1?t=u:r!==1&&(r=1):t!==-1&&(r=-1)}return t===-1||a===-1||r===0||r===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){V(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 r=-1,u=0,f=-1,p=!0,b=e.length-1,d=0;b>=s;--b){if(n=e.charCodeAt(b),n===47){if(!p){u=b+1;break}continue}f===-1&&(p=!1,f=b+1),n===46?r===-1?r=b:d!==1&&(d=1):r!==-1&&(d=-1)}return r===-1||f===-1||d===0||d===1&&r===f-1&&r===u+1?f!==-1&&(u===0&&a?t.base=t.name=e.slice(1,f):t.base=t.name=e.slice(u,f)):(u===0&&a?(t.name=e.slice(1,r),t.base=e.slice(1,f)):(t.name=e.slice(u,r),t.base=e.slice(u,f)),t.ext=e.slice(r,f)),u>0?t.dir=e.slice(0,u-1):a&&(t.dir="/"),t}var Rn,it,rt,Nn=fn(()=>{"use strict";Ln();Rn="/",it=":",rt=null});var he={};Q(he,{pathToFileURL:()=>at});function ot(e){return e.replace(/%/g,"%25").replace(/\\/g,"%5C").replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/\t/g,"%09")}function at(e){let t=cn(e);e.charCodeAt(e.length-1)===47&&t[t.length-1]!==Rn&&(t+="/");let n=new URL("file://");return n.pathname=ot(t),n}var ge=fn(()=>{"use strict";Nn()});var Wn={};Q(Wn,{Stats:()=>Cn,checkDiagnostics:()=>gn,compileString:()=>St,configToArguments:()=>qn,createMemoryStream:()=>Hn,default:()=>Wn,defaultOptimizeLevel:()=>Be,defaultShrinkLevel:()=>Se,definitionFiles:()=>Bt,libraryFiles:()=>X,libraryPrefix:()=>P,main:()=>we,options:()=>zt,tscOptions:()=>wt,version:()=>Xn});var st=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",G,sn,v,U,dn;st?(G=await import("fs"),sn=await import("module"),v=await import("path"),U=globalThis.process,dn=await import("url")):(G=await Promise.resolve().then(()=>(ue(),le)),sn=await Promise.resolve().then(()=>(ce(),fe)),v=await Promise.resolve().then(()=>(Nn(),kn)),U=await Promise.resolve().then(()=>(Ln(),On)),dn=await Promise.resolve().then(()=>(ge(),he)));var An=typeof process<"u"&&process||{},lt=An.env&&"CI"in An.env,ut="\x1B[90m",ft="\x1B[91m",ct="\x1B[92m",dt="\x1B[93m",xt="\x1B[94m",pt="\x1B[95m",ht="\x1B[96m",gt="\x1B[97m",W="\x1B[0m",nn=class{constructor(t){this.stream=t,this.enabled=!!(this.stream&&this.stream.isTTY||lt)}gray(t){return this.enabled?ut+t+W:t}red(t){return this.enabled?ft+t+W:t}green(t){return this.enabled?ct+t+W:t}yellow(t){return this.enabled?dt+t+W:t}blue(t){return this.enabled?xt+t+W:t}magenta(t){return this.enabled?pt+t+W:t}cyan(t){return this.enabled?ht+t+W:t}white(t){return this.enabled?gt+t+W:t}},_n=new nn(An.stdout),Ot=new nn(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,r=[],u=0,f;t<n;)f=e[t++],f<128?r[u++]=f:f>191&&f<224?r[u++]=(f&31)<<6|e[t++]&63:f>239&&f<365?(f=((f&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,r[u++]=55296+(f>>10),r[u++]=56320+(f&1023)):r[u++]=(f&15)<<12|(e[t++]&63)<<6|e[t++]&63,u>=8192&&((s||(s=[])).push(String.fromCharCode(...r)),u=0);return s?(u&&s.push(String.fromCharCode(...r.slice(0,u))),s.join("")):String.fromCharCode(...r.slice(0,u))}function yt(e,t,n){for(var a=n,s=0,r=e.length;s<r;++s){let u=e.charCodeAt(s),f;u<128?t[n++]=u:u<2048?(t[n++]=u>>6|192,t[n++]=u&63|128):(u&64512)===55296&&s+1<r&&((f=e.charCodeAt(s+1))&64512)===56320?(u=65536+((u&1023)<<10)+(f&1023),++s,t[n++]=u>>18|240,t[n++]=u>>12&63|128,t[n++]=u>>6&63|128,t[n++]=u&63|128):(t[n++]=u>>12|224,t[n++]=u>>6&63|128,t[n++]=u&63|128)}return n-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=[],r=[],u=[],f={};Object.keys(t).forEach(d=>{if(!d.startsWith(" ")){var g=t[d];g.alias!=null&&(typeof g.alias=="string"?f[g.alias]=d:Array.isArray(g.alias)&&g.alias.forEach(y=>f[y]=d)),n&&g.default!=null&&(a[d]=g.default)}});for(var p=0,b=(e=e.slice()).length;p<b;++p){let d=e[p];if(d=="--"){++p;break}let g=/^(?:(-\w)(?:=(.*))?|(--\w{2,})(?:=(.*))?)$/.exec(d),y,m;if(g)t[d]?y=t[m=d]:g[1]!=null?(y=t[m=f[g[1].substring(1)]],y&&g[2]!=null&&(e[p--]=g[2])):g[3]!=null&&(y=t[m=g[3].substring(2)],y&&g[4]!=null&&(e[p--]=g[4]));else if(d.charCodeAt(0)==45)y=t[m=d];else{r.push(d);continue}if(y)if(y.value)Object.keys(y.value).forEach(i=>a[i]=y.value[i]);else if(y.type==null||y.type==="b")a[m]=!0;else if(p+1<e.length&&e[p+1].charCodeAt(0)!=45)switch(y.type){case"i":a[m]=parseInt(e[++p],10);break;case"I":a[m]=(a[m]||[]).concat(parseInt(e[++p],10));break;case"f":a[m]=parseFloat(e[++p]);break;case"F":a[m]=(a[m]||[]).concat(parseFloat(e[++p]));break;case"s":a[m]=String(e[++p]);break;case"S":a[m]=(a[m]||[]).concat(e[++p].split(","));break;default:s.push(d),--p}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(d)}else s.push(d)}for(;p<b;)u.push(e[p++]);return n&&Un(t,a),{options:a,unknown:s,arguments:r,trailing:u}}function Fe(e,t){t||(t={});var n=t.indent||2,a=t.padding||24,s=t.eol||`
8
- `,r={},u=[];Object.keys(e).forEach(b=>{var d=e[b];if(d.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,d.alias&&(g+=", -"+d.alias);g.length<a;)g+=" ";var y;!t.noCategories&&d.category?(y=r[d.category])||(r[d.category]=y=[]):y=u,Array.isArray(d.description)?y.push(g+d.description[0]+d.description.slice(1).map(m=>{for(let i=0;i<a;++i)m=" "+m;return s+m}).join("")):y.push(g+d.description)}});var f=[],p=!1;return Object.keys(r).forEach(b=>{p=!0,f.push(s+" "+_n.gray(b)+s),f.push(r[b].join(s))}),p&&u.length&&f.push(s+" "+_n.gray("Other")+s),f.push(u.join(s)),f.join(s)}function be(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Mn(e,t,n,a){let s={};for(let[r,{type:u,mutuallyExclusive:f,isPath:p,useNodeResolution:b,cliOnly:d}]of Object.entries(e)){let g=be(t[r],u),y=be(n[r],u);if(g==null){if(y!=null){if(d)continue;if(Array.isArray(y)){let m;p&&(y=y.map(i=>en(i,a,b))),f!=null&&(m=t[f])?s[r]=y.filter(i=>!m.includes(i)):s[r]=y.slice()}else p&&(y=en(y,a,b)),s[r]=y}}else if(y==null)Array.isArray(g)?s[r]=g.slice():s[r]=g;else if(Array.isArray(g)){if(d){s[r]=g.slice();continue}let m;p&&(y=y.map(i=>en(i,a,b))),f!=null&&(m=t[f])?s[r]=[...g,...y.filter(i=>!g.includes(i)&&!m.includes(i))]:s[r]=[...g,...y.filter(i=>!g.includes(i))]}else s[r]=g}return s}function Ft(e){let t=v.parse(e);return t.root||(t.root="./"),v.format(t)}function en(e,t,n=!1){return v.isAbsolute(e)?e:n&&!e.startsWith(".")&&me.resolve?me.resolve(e,{paths:[t]}):Ft(v.join(t,e))}function Un(e,t){for(let[n,{default:a}]of Object.entries(e))t[n]==null&&a!=null&&(t[n]=a)}var ve="0.1.0",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},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" />
8
+ `,r={},u=[];Object.keys(e).forEach(b=>{var d=e[b];if(d.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,d.alias&&(g+=", -"+d.alias);g.length<a;)g+=" ";var y;!t.noCategories&&d.category?(y=r[d.category])||(r[d.category]=y=[]):y=u,Array.isArray(d.description)?y.push(g+d.description[0]+d.description.slice(1).map(m=>{for(let i=0;i<a;++i)m=" "+m;return s+m}).join("")):y.push(g+d.description)}});var f=[],p=!1;return Object.keys(r).forEach(b=>{p=!0,f.push(s+" "+_n.gray(b)+s),f.push(r[b].join(s))}),p&&u.length&&f.push(s+" "+_n.gray("Other")+s),f.push(u.join(s)),f.join(s)}function be(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Mn(e,t,n,a){let s={};for(let[r,{type:u,mutuallyExclusive:f,isPath:p,useNodeResolution:b,cliOnly:d}]of Object.entries(e)){let g=be(t[r],u),y=be(n[r],u);if(g==null){if(y!=null){if(d)continue;if(Array.isArray(y)){let m;p&&(y=y.map(i=>en(i,a,b))),f!=null&&(m=t[f])?s[r]=y.filter(i=>!m.includes(i)):s[r]=y.slice()}else p&&(y=en(y,a,b)),s[r]=y}}else if(y==null)Array.isArray(g)?s[r]=g.slice():s[r]=g;else if(Array.isArray(g)){if(d){s[r]=g.slice();continue}let m;p&&(y=y.map(i=>en(i,a,b))),f!=null&&(m=t[f])?s[r]=[...g,...y.filter(i=>!g.includes(i)&&!m.includes(i))]:s[r]=[...g,...y.filter(i=>!g.includes(i))]}else s[r]=g}return s}function Ft(e){let t=v.parse(e);return t.root||(t.root="./"),v.format(t)}function en(e,t,n=!1){return v.isAbsolute(e)?e:n&&!e.startsWith(".")&&me.resolve?me.resolve(e,{paths:[t]}):Ft(v.join(t,e))}function Un(e,t){for(let[n,{default:a}]of Object.entries(e))t[n]==null&&a!=null&&(t[n]=a)}var ve="0.1.2",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},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";
@@ -10051,7 +10051,7 @@ export function __tostack(ptr: usize): usize {
10051
10051
  return ptr;
10052
10052
  }
10053
10053
 
10054
- // These are provided by the respective implementation, included as another entry file by asc:
10054
+ // These are provided by the respective implementation, included as another entry file by toilscript:
10055
10055
 
10056
10056
  // // @ts-ignore: decorator
10057
10057
  // @builtin @unsafe
@@ -13470,6 +13470,22 @@ export namespace table {
13470
13470
  throw new Error(E_NOTIMPLEMENTED);
13471
13471
  }
13472
13472
  }
13473
+ `,toilscript:`/**
13474
+ * ToilScript-native declarations.
13475
+ *
13476
+ * Compiler-level natives available everywhere with no import. \`@main\` is handled
13477
+ * directly by the ToilScript compiler \u2014 it exports the decorated top-level
13478
+ * function as the module's \`main\` entry \u2014 so this declaration exists only so
13479
+ * editors and type-checking recognize the decorator. Future zero-import toil
13480
+ * natives (globals/decorators) belong here too.
13481
+ */
13482
+
13483
+ /**
13484
+ * Marks a single top-level function as the module entry point. The compiler
13485
+ * exports it as the WebAssembly export \`main\` \u2014 no \`export\` keyword needed.
13486
+ * Exactly one \`@main\` is allowed per module.
13487
+ */
13488
+ declare function main(...args: any[]): any;
13473
13489
  `,typedarray:`import { COMPARATOR, SORT } from "./util/sort";
13474
13490
  import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH, E_NOTIMPLEMENTED } from "./util/error";
13475
13491
  import { joinIntegerArray, joinFloatArray } from "./util/string";
@@ -21100,11 +21116,12 @@ function loadHex(src: usize, offset: usize): u32 {
21100
21116
  export abstract class V128 {
21101
21117
  }
21102
21118
  `},_e={assembly:`/**
21103
- * Environment definitions for compiling AssemblyScript to WebAssembly using asc.
21119
+ * Environment definitions for compiling ToilScript to WebAssembly using toilscript.
21104
21120
  * @module std/assembly
21105
21121
  *//***/
21106
21122
 
21107
21123
  /// <reference no-default-lib="true"/>
21124
+ /// <reference path="./toilscript.ts" />
21108
21125
 
21109
21126
  // Types
21110
21127
 
@@ -23991,7 +24008,7 @@ declare namespace external {
23991
24008
  /** Annotates a global for lazy compilation. */
23992
24009
  declare function lazy(...args: any[]): any;
23993
24010
  `,portable:`/**
23994
- * Environment definitions for compiling AssemblyScript to JavaScript using tsc.
24011
+ * Environment definitions for compiling ToilScript to JavaScript using tsc.
23995
24012
  *
23996
24013
  * Note that semantic differences require additional explicit conversions for full compatibility.
23997
24014
  * For example, when casting an i32 to an u8, doing \`<u8>(someI32 & 0xff)\` will yield the same
@@ -24453,5 +24470,5 @@ declare function offsetof<T>(fieldName?: string): usize;
24453
24470
  declare function idof<T>(): u32;
24454
24471
  `};var xn={};Q(xn,{default:()=>pn});Dn(xn,Ut);import*as Ut from"binaryen";import{default as pn}from"binaryen";import*as At from"toilscript";var h=At,Pn=U.argv.indexOf("--wasm");if(~Pn){let e=String(U.argv[Pn+1]);U.argv.splice(Pn,2),h=await import(new URL(e,dn.pathToFileURL(U.cwd()+"/")))}var Vn=sn.createRequire(import.meta.url),Kn=U.platform==="win32",E=Kn?`\r
24455
24472
  `:`
24456
- `,jn=Kn?"\\":"/",_=".ts",_t=`.d${_}`,hn=new RegExp("\\"+_+"$"),Tt=new RegExp("^(?!.*\\.d\\"+_+"$).*\\"+_+"$");function Te(e){return e.replace(/-/g,"_").toUpperCase()}function Ct(e){return typeof e=="string"&&e!==""}var Xn=ve,zt=Y,P=Ee,X=Ae,Bt=_e,Be=3,Se=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(r=>{t.push(`--${n}`,String(r))}):t.push(`--${n}`,String(a))}),t}async function St(e,t={}){typeof e=="string"&&(e={[`input${_}`]:e});let n=["--outFile","binary","--textFile","text"];qn(t,n);let a={},s=await we(n.concat(Object.keys(e)),{readFile:r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:null,writeFile:(r,u)=>{a[r]=u},listFiles:()=>[]});return Object.assign(s,a)}async function we(e,t){Array.isArray(e)||(e=qn(e)),t||(t={});let n=t.stats||new Cn,a=n.begin(),s=0,r=0,u=0,f=(Xn||"").split(".");f.length===3&&(r=parseInt(f[0])|0,s=parseInt(f[1])|0,u=parseInt(f[2])|0);let p=t.stdout||Hn(),b=t.stderr||Hn(),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 nn(p),j=new nn(b);i.noColors&&(zn.enabled=!1,j.enabled=!1);let Yn=m.unknown;Yn.length&&Yn.forEach(o=>{b.write(`${j.yellow("WARNING ")}Unknown option '${o}'${E}`)});let Zn=m.trailing;Zn.length&&b.write(`${j.yellow("WARNING ")}Unsupported trailing arguments: ${Zn.join(" ")}${E}`);let H=null,R=null,z=(o,l={})=>(o&&b.write(`${j.red("FAILURE ")}${o.stack.replace(/^ERROR: /i,"")}${E}`),R&&R.dispose(),n.total||(n.total=n.end(a)),Object.assign({error:o,stdout:p,stderr:b,stats:n},l));if(i.version)return p.write(`Version ${Xn}${E}`),z(null);let B=v.normalize(i.baseDir||"."),K=en(i.config||"toilconfig.json",B),Bn=v.basename(K),Z=v.dirname(K),k=await Ce(Bn,Z,d),De=k!=null&&Array.isArray(k.entries)&&k.entries.length;if(i.help||!e.length&&!De){let o=i.help?p:b,l=i.help?zn:j;return o.write([l.white("SYNTAX")," "+l.cyan("asc")+" [entryFile ...] [options]","",l.white("EXAMPLES")," "+l.cyan("asc")+" hello"+_," "+l.cyan("asc")+" hello"+_+" -o hello.wasm -t hello.wat"," "+l.cyan("asc")+" hello1"+_+" hello2"+_+" -o -O > hello.wasm"," "+l.cyan("asc")+" --config toilconfig.json --target release","",l.white("OPTIONS")].concat(Fe(Y,24,E)).join(E)+E),z(null)}if(!(G.promises&&G.promises.readFile)){if(d===ee)throw Error("'options.readFile' must be specified");if(g===te)throw Error("'options.writeFile' must be specified");if(y===ie)throw Error("'options.listFiles' must be specified")}let Sn=new Set;Sn.add(K);let Ie=i.target||"release";for(;k;){if(k.targets){let l=k.targets[Ie];l&&(i=Mn(Y,i,l,Z))}let o=k.options;if(o&&(i=Mn(Y,i,o,Z)),k.entries)for(let l of k.entries)e.push(en(l,Z));if(k.extends){if(K=en(k.extends,Z,!0),Bn=v.basename(K),Z=v.dirname(K),Sn.has(K))break;Sn.add(K),k=await Ce(Bn,Z,d)}else break}if(Un(Y,i),i.showConfig)return b.write(JSON.stringify({options:i,entries:e},null,2)),z(null);function $n(o){return[...new Set(o)]}let S,tn,mn,T=h.newOptions();switch(i.runtime){case"stub":tn=0;break;case"minimal":tn=1;break;case"memory":tn=3;break;default:tn=2;break}switch(i.uncheckedBehavior){default:mn=0;break;case"never":mn=1;break;case"always":mn=2;break}if(h.setTarget(T,0),h.setDebugInfo(T,!!i.debug),h.setRuntime(T,tn),h.setNoAssert(T,i.noAssert),h.setExportMemory(T,!i.noExportMemory),h.setImportMemory(T,i.importMemory),h.setInitialMemory(T,i.initialMemory>>>0),h.setMaximumMemory(T,i.maximumMemory>>>0),h.setSharedMemory(T,i.sharedMemory),h.setImportTable(T,i.importTable),h.setExportTable(T,i.exportTable),i.exportStart!=null&&h.setExportStart(T,Ct(i.exportStart)?i.exportStart:"_start"),h.setMemoryBase(T,i.memoryBase>>>0),h.setTableBase(T,i.tableBase>>>0),h.setSourceMap(T,i.sourceMap!=null),h.setUncheckedBehavior(T,mn),h.setNoUnsafe(T,i.noUnsafe),h.setPedantic(T,i.pedantic),h.setLowMemoryLimit(T,i.lowMemoryLimit>>>0),h.setExportRuntime(T,i.exportRuntime),h.setBundleVersion(T,r,s,u),!i.stackSize&&tn===2&&(i.stackSize=h.DEFAULT_STACK_SIZE),h.setStackSize(T,i.stackSize),h.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 x=o[l],A=x.indexOf("=");if(A<0)return z(Error(`Global alias '${x}' is invalid.`));let F=x.substring(0,A).trim(),C=x.substring(A+1).trim();if(!F.length)return z(Error(`Global alias '${x}' is invalid.`));h.addGlobalAlias(T,F,C)}}let N;if((N=i.disable)!=null){typeof N=="string"&&(N=N.split(","));for(let o=0,l=N.length;o<l;++o){let c=N[o].trim(),x=h[`FEATURE_${Te(c)}`];if(!x)return z(Error(`Feature '${c}' is unknown.`));h.setFeature(T,x,!1)}}if((N=i.enable)!=null){typeof N=="string"&&(N=N.split(","));for(let o=0,l=N.length;o<l;++o){let c=N[o].trim(),x=h[`FEATURE_${Te(c)}`];if(!x)return z(Error(`Feature '${c}' is unknown.`));h.setFeature(T,x,!0)}}let $=0,J=0;i.optimize&&($=Be,J=Se),typeof i.optimizeLevel=="number"&&($=i.optimizeLevel),typeof i.shrinkLevel=="number"&&(J=i.shrinkLevel),$=Math.min(Math.max($,0),3),J=Math.min(Math.max(J,0),2),h.setOptimizeLevelHints(T,$,J),S=h.newProgram(T);let rn=[];if(Array.isArray(t.transforms)&&rn.push(...t.transforms),i.transform){let o=$n(i.transform);for(let l=0,c=o.length;l<c;++l){let x=o[l].trim(),A,F;if(Vn.resolve)try{A=Vn.resolve(x,{paths:[U.cwd(),B]}),F=await import(dn.pathToFileURL(A)),F.default&&(F=F.default)}catch(C){try{F=Vn(A)}catch{return z(C)}}else try{F=await import(new URL(x,import.meta.url)),F.default&&(F=F.default)}catch(C){return z(C)}if(!F||typeof F!="function"&&typeof F!="object")return z(Error("not a transform: "+o[l]));rn.push(F)}}try{rn=rn.map(o=>(typeof o=="function"&&(Object.assign(o.prototype,{program:S,binaryen:pn,baseDir:B,stdout:p,stderr:b,log:console.error,readFile:d,writeFile:g,listFiles:y}),o=new o),o))}catch(o){return z(o)}async function wn(o,...l){for(let c=0,x=rn.length;c<x;++c){let A=rn[c];if(typeof A[o]=="function")try{let F=n.begin();n.transformCount++,await A[o](...l),n.transformTime+=n.end(F)}catch(F){return F}}}Object.keys(X).forEach(o=>{if(o.includes("/"))return;let l=n.begin();n.parseCount++,h.parse(S,X[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=$n(on);for(let l=0,c=on.length;l<c;++l){let x=on[l],A;x.endsWith(_)?(A=[v.basename(x)],x=v.dirname(x)):A=await y(x,B)||[];for(let F of A){let C=await d(F,x);if(C==null)return z(Error(`Library file '${F}' not found.`));X[F.replace(hn,"")]=C;let I=n.begin();n.parseCount++,h.parse(S,C,P+F,!1),n.parseTime+=n.end(I)}}}i.path=i.path||[];let bn=new Map;async function Oe(o,l){let c=null,x=null;if(!o.startsWith(P))(c=await d(x=o+_,B))==null&&(c=await d(x=o+"/index"+_,B))==null&&(x=o+_,c=await d(o+_t,B));else{let A=o.substring(P.length),F=`${A}/index`;if(Object.prototype.hasOwnProperty.call(X,A))c=X[A],x=P+A+_;else if(Object.prototype.hasOwnProperty.call(X,F))c=X[F],x=P+F+_;else{for(let C of on)if((c=await d(A+_,C))!=null){x=P+A+_;break}else if((c=await d(F+_,C))!=null){x=P+F+_;break}if(c==null){let C=o.match(/^~lib\/((?:@[^/]+\/)?[^/]+)(?:\/(.+))?/);if(C){let I=C[1],q=C[2]||"index",vn=bn.has(l)?bn.get(l):".",M=[],D=v.resolve(B,vn).split(jn);for(let w=D.length,O=Kn?1:0;w>=O;--w)D[w-1]!=="node_modules"&&M.push(`${D.slice(0,w).join(jn)}${jn}node_modules`);M.push(...i.path);for(let w of M.map(O=>v.relative(B,O))){let O=q;if((c=await d(v.join(w,I,O+_),B))!=null){x=`${P}${I}/${O}${_}`,bn.set(x.replace(hn,""),v.join(w,I));break}let un=`${q}/index`;if((c=await d(v.join(w,I,un+_),B))!=null){x=`${P}${I}/${un}${_}`,bn.set(x.replace(hn,""),v.join(w,I));break}}}}}}return c==null?null:{sourceText:c,sourcePath:x}}function Le(o=[]){do{let l=h.nextFile(S);if(l==null)break;o.push(l)}while(!0);return o}async function Jn(){let o;for(;(o=Le()).length;){let c=[];for(let x of o){let A=h.getDependee(S,x);c.push(Oe(x,A))}c=await Promise.all(c);for(let x=0,A=o.length;x<A;++x){let F=o[x],C=c[x],I=n.begin();n.parseCount++,C?h.parse(S,C.sourceText,C.sourcePath,!1):h.parse(S,null,F+_,!1),n.parseTime+=n.end(I)}}let l=gn(S,b,i.disableWarning,t.reportDiagnostic,j.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=X[l];if(c==null){if(l=o,c=await d(l+_,B),c==null)return z(Error(`Runtime '${v.resolve(B,l+_)}' is not found.`))}else l=`~lib/${l}`;let x=n.begin();n.parseCount++,h.parse(S,c,l+_,!0),n.parseTime+=n.end(x)}for(let o=0,l=e.length;o<l;++o){let c=String(e[o]),x=v.isAbsolute(c)?v.relative(B,c):v.normalize(c);x=x.replace(/\\/g,"/").replace(hn,"").replace(/\/$/,"");let A=await d(x+_,B);if(A==null){let C=`${x}/index${_}`;A=await d(C,B),A!=null?x=C:x+=_}else x+=_;let F=n.begin();n.parseCount++,h.parse(S,A,x,!0),n.parseTime+=n.end(F)}{let o=await Jn();if(o)return o}{let o=await wn("afterParse",S.parser);if(o)return z(o)}{let o=await Jn();if(o)return o}{let o=n.begin();n.initializeCount++;try{h.initializeProgram(S)}catch(l){L("initialize",l)}n.initializeTime+=n.end(o)}{let o=await wn("afterInitialize",S);if(o)return z(o)}{let o=n.begin();n.compileCount++;try{H=h.compile(S)}catch(l){let c=gn(S,b,i.disableWarning,t.reportDiagnostic,j.enabled);if(c){let x=Error(`${c} compile error(s)`);return x.stack=x.message,z(x)}L("compile",l)}n.compileTime+=n.end(o)}R=pn.wrapModule(typeof H=="number"||H instanceof Number?h.getBinaryenModuleRef(H):H.ref);let ln=gn(S,b,i.disableWarning,t.reportDiagnostic,j.enabled);if(ln){let o=Error(`${ln} compile error(s)`);return o.stack=o.message,z(o)}{let o=await wn("afterCompile",R);if(o)return z(o)}if(ln=gn(S,b,i.disableWarning,t.reportDiagnostic,j.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=h.validate(H);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){L("runPasses",l)}n.compileTime+=n.end(o)}else if(i.trapMode!=="allow")return z(Error("Unsupported trap mode"));let Qn=i.debug,Re=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++,h.optimize(H,$,J,Qn,ne)}catch(l){L("optimize",l)}try{R.runPasses(yn)}catch(l){L("runPasses",l)}if(Re){let l;try{let c=n.begin();n.emitCount++,l=R.emitBinary(),n.emitTime+=n.end(c)}catch(c){L("emitBinary (converge)",c)}do{try{n.optimizeCount++,h.optimize(H,$,J,Qn,ne)}catch(x){L("optimize (converge)",x)}try{R.runPasses(yn)}catch(x){L("runPasses (converge)",x)}let c;try{let x=n.begin();n.emitCount++,c=R.emitBinary(),n.emitTime+=n.end(x)}catch(x){L("emitBinary (converge)",x)}if(c.length>=l.length){c.length>l.length&&b.write(`Last converge was suboptimal.${E}`);break}l=c}while(!0)}n.optimizeTime+=n.end(o)}let an=[];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,x=i.textFile!=null,A=c||x,F=c&&i.outFile.length>0||x&&i.textFile.length>0,C=F?(i.outFile||i.textFile).replace(/\.\w+$/,""):null,I=F?v.basename(C):"output";if(h.setBasenameHint(T,I),i.outFile!=null){let M=i.sourceMap!=null?i.sourceMap.length?i.sourceMap:`./${I}.wasm.map`:null,D=n.begin();n.emitCount++;let w;try{w=R.emitBinary(M)}catch(O){L("emitBinary",O)}if(n.emitTime+=n.end(D),i.outFile.length?an.push(g(i.outFile,w.binary,B)):(l=!0,Fn(w.binary)),w.sourceMap!="")if(i.outFile.length){let O=JSON.parse(w.sourceMap);O.sourceRoot=`./${I}`;let un=[];for(let En=0,ke=O.sources.length;En<ke;++En){let re=O.sources[En],oe=h.getSource(S,re.replace(hn,""));if(oe==null)return z(Error(`Source of file '${re}' not found.`));un[En]=oe}O.sourcesContent=un,an.push(g(v.join(v.dirname(i.outFile),v.basename(M)).replace(/^\.\//,""),JSON.stringify(O),B))}else b.write(`Skipped source map (no output path)${E}`)}if(i.textFile!=null||!A){let M=n.begin();n.emitCount++;let D;try{pn.setOptimizeStackIR(!0),D=i.textFile?.endsWith(".wast")?R.emitText():R.emitStackIR()}catch(w){L("emitText",w)}n.emitTime+=n.end(M),i.textFile!=null&&i.textFile.length?an.push(g(i.textFile,D,B)):l||Fn(D)}let q=o.includes("esm"),vn=!q&&o.includes("raw");if(q||vn)if(C){let M=n.begin();n.emitCount++;let D;try{D=h.buildTSD(S,q)}catch(w){L("buildTSD",w)}n.emitTime+=n.end(M),an.push(g(C+".d.ts",D,B))}else b.write(`Skipped TypeScript binding (no output path)${E}`);if(q||vn)if(C){let M=n.begin();n.emitCount++;let D;try{D=h.buildJS(S,q)}catch(w){L("buildJS",w)}n.emitTime+=n.end(M),an.push(g(C+".js",D,B))}else b.write(`Skipped JavaScript binding (no output path)${E}`)}try{await Promise.all(an)}catch(o){return z(o)}return n.total=n.end(a),i.stats&&b.write(n.toString()),z(null);async function ee(o,l){let c=v.resolve(l,o);try{return n.readCount++,await G.promises.readFile(c,"utf8")}catch{return null}}async function te(o,l,c){try{n.writeCount++;let x=v.resolve(c,v.dirname(o)),A=v.join(x,v.basename(o));return await G.promises.mkdir(x,{recursive:!0}),await G.promises.writeFile(A,l),!0}catch{return!1}}async function ie(o,l){try{return n.readCount++,(await G.promises.readdir(v.join(l,o))).filter(c=>Tt.test(c))}catch{return null}}function Fn(o){Fn.used||(Fn.used=!0,n.writeCount++),p.write(o)}function L(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("")),U.exit(1)}}function Gn(e){return Object.prototype.toString.call(e)==="[object Object]"}async function Ce(e,t,n){let a=await n(e,t),s=v.join(t,e);if(!a)return null;let r;try{r=JSON.parse(a)}catch(u){throw new Error(`Toilconfig is not valid json: ${s}`,{cause:u})}if(r.options&&!Gn(r.options))throw new Error(`Toilconfig.options is not an object: ${s}`);if(r.include&&!Array.isArray(r.include))throw new Error(`Toilconfig.include is not an array: ${s}`);if(r.targets){if(!Gn(r.targets))throw new Error(`Toilconfig.targets is not an object: ${s}`);let u=Object.keys(r.targets);for(let f=0;f<u.length;f++){let p=u[f];if(!Gn(r.targets[p]))throw new Error(`Toilconfig.targets.${p} is not an object: ${s}`)}}if(r.extends&&typeof r.extends!="string")throw new Error(`Toilconfig.extends is not a string: ${s}`);return r}function gn(e,t,n,a,s){typeof s>"u"&&t&&(s=t.isTTY);let r=0;do{let p=h.nextDiagnostic(e);if(!p)break;if(t){let b=d=>{if(n==null)return!1;if(!n.length)return!0;let g=h.getDiagnosticCode(d);return n.includes(g)};(h.isError(p)||!b(p))&&t.write(h.formatDiagnostic(p,s,!0)+E+E)}if(a){let b=function(g){return g&&{start:h.getRangeStart(g),end:h.getRangeEnd(g),source:d(h.getRangeSource(g))}||null},d=function(g){return g&&{normalizedPath:h.getSourceNormalizedPath(g)}||null};var u=b,f=d;a({message:h.getDiagnosticMessage(p),code:h.getDiagnosticCode(p),category:h.getDiagnosticCategory(p),range:b(h.getDiagnosticRange(p)),relatedRange:b(h.getDiagnosticRelatedRange(p))})}h.isError(p)&&++r}while(!0);return r}var Cn=class{readCount=0;writeCount=0;parseTime=0;parseCount=0;initializeTime=0;initializeCount=0;compileTime=0;compileCount=0;emitTime=0;emitCount=0;validateTime=0;validateCount=0;optimizeTime=0;optimizeCount=0;transformTime=0;transformCount=0;begin(){return U.hrtime()}end(t){let n=U.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()),r=n.reduce((m,i)=>Math.max(i.length,m),0),u=a.reduce((m,i)=>Math.max(i.length,m),0),f=s.reduce((m,i)=>Math.max(i.length,m),0),p=r+u+f+6,b=[];b.push(`\u256D\u2500${"\u2500".repeat(p)}\u2500\u256E${E}`);let d="Stats";b.push(`\u2502 ${d}${" ".repeat(p-d.length)} \u2502${E}`),b.push(`\u255E\u2550${"\u2550".repeat(r)}\u2550\u2564\u2550${"\u2550".repeat(u)}\u2550\u2564\u2550${"\u2550".repeat(f)}\u2550\u2561${E}`);for(let m=0,i=n.length;m<i;++m)b.push(`\u2502 ${n[m].padEnd(r)} \u2502 ${a[m].padStart(u)} \u2502 ${s[m].padStart(f)} \u2502${E}`);b.push(`\u251C\u2500${"\u2500".repeat(r)}\u2500\u2534\u2500${"\u2500".repeat(u)}\u2500\u2534\u2500${"\u2500".repeat(f)}\u2500\u2524${E}`);let g=`Took ${t(this.total)}`;b.push(`\u2502 ${g}${" ".repeat(p-g.length)} \u2502${E}`);let y=`${this.readCount} reads, ${this.writeCount} writes`;return b.push(`\u2502 ${y}${" ".repeat(p-y.length)} \u2502${E}`),b.push(`\u2570\u2500${"\u2500".repeat(p)}\u2500\u256F${E}`),b.join("")}},ze=typeof global<"u"&&global.Buffer?global.Buffer.allocUnsafe||(e=>new global.Buffer(e)):e=>new Uint8Array(e);function Hn(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 r=ze(n);for(n=a=0;a<s;)r.set(this[a],n),n+=this[a].length,++a;return r},t.toString=function(){let n=this.toBuffer();return Tn.read(n,0,n.length)},t}var wt={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,St as compileString,qn as configToArguments,Hn as createMemoryStream,Wn as default,Be as defaultOptimizeLevel,Se as defaultShrinkLevel,Bt as definitionFiles,X as libraryFiles,P as libraryPrefix,we as main,zt as options,wt as tscOptions,Xn as version};
24457
- //# sourceMappingURL=asc.js.map
24473
+ `,jn=Kn?"\\":"/",_=".ts",_t=`.d${_}`,hn=new RegExp("\\"+_+"$"),Tt=new RegExp("^(?!.*\\.d\\"+_+"$).*\\"+_+"$");function Te(e){return e.replace(/-/g,"_").toUpperCase()}function Ct(e){return typeof e=="string"&&e!==""}var Xn=ve,zt=Y,P=Ee,X=Ae,Bt=_e,Be=3,Se=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(r=>{t.push(`--${n}`,String(r))}):t.push(`--${n}`,String(a))}),t}async function St(e,t={}){typeof e=="string"&&(e={[`input${_}`]:e});let n=["--outFile","binary","--textFile","text"];qn(t,n);let a={},s=await we(n.concat(Object.keys(e)),{readFile:r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:null,writeFile:(r,u)=>{a[r]=u},listFiles:()=>[]});return Object.assign(s,a)}async function we(e,t){Array.isArray(e)||(e=qn(e)),t||(t={});let n=t.stats||new Cn,a=n.begin(),s=0,r=0,u=0,f=(Xn||"").split(".");f.length===3&&(r=parseInt(f[0])|0,s=parseInt(f[1])|0,u=parseInt(f[2])|0);let p=t.stdout||Hn(),b=t.stderr||Hn(),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 nn(p),j=new nn(b);i.noColors&&(zn.enabled=!1,j.enabled=!1);let Yn=m.unknown;Yn.length&&Yn.forEach(o=>{b.write(`${j.yellow("WARNING ")}Unknown option '${o}'${E}`)});let Zn=m.trailing;Zn.length&&b.write(`${j.yellow("WARNING ")}Unsupported trailing arguments: ${Zn.join(" ")}${E}`);let H=null,R=null,z=(o,l={})=>(o&&b.write(`${j.red("FAILURE ")}${o.stack.replace(/^ERROR: /i,"")}${E}`),R&&R.dispose(),n.total||(n.total=n.end(a)),Object.assign({error:o,stdout:p,stderr:b,stats:n},l));if(i.version)return p.write(`Version ${Xn}${E}`),z(null);let B=v.normalize(i.baseDir||"."),K=en(i.config||"toilconfig.json",B),Bn=v.basename(K),Z=v.dirname(K),k=await Ce(Bn,Z,d),De=k!=null&&Array.isArray(k.entries)&&k.entries.length;if(i.help||!e.length&&!De){let o=i.help?p:b,l=i.help?zn:j;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(Fe(Y,24,E)).join(E)+E),z(null)}if(!(G.promises&&G.promises.readFile)){if(d===ee)throw Error("'options.readFile' must be specified");if(g===te)throw Error("'options.writeFile' must be specified");if(y===ie)throw Error("'options.listFiles' must be specified")}let Sn=new Set;Sn.add(K);let Ie=i.target||"release";for(;k;){if(k.targets){let l=k.targets[Ie];l&&(i=Mn(Y,i,l,Z))}let o=k.options;if(o&&(i=Mn(Y,i,o,Z)),k.entries)for(let l of k.entries)e.push(en(l,Z));if(k.extends){if(K=en(k.extends,Z,!0),Bn=v.basename(K),Z=v.dirname(K),Sn.has(K))break;Sn.add(K),k=await Ce(Bn,Z,d)}else break}if(Un(Y,i),i.showConfig)return b.write(JSON.stringify({options:i,entries:e},null,2)),z(null);function $n(o){return[...new Set(o)]}let S,tn,mn,T=h.newOptions();switch(i.runtime){case"stub":tn=0;break;case"minimal":tn=1;break;case"memory":tn=3;break;default:tn=2;break}switch(i.uncheckedBehavior){default:mn=0;break;case"never":mn=1;break;case"always":mn=2;break}if(h.setTarget(T,0),h.setDebugInfo(T,!!i.debug),h.setRuntime(T,tn),h.setNoAssert(T,i.noAssert),h.setExportMemory(T,!i.noExportMemory),h.setImportMemory(T,i.importMemory),h.setInitialMemory(T,i.initialMemory>>>0),h.setMaximumMemory(T,i.maximumMemory>>>0),h.setSharedMemory(T,i.sharedMemory),h.setImportTable(T,i.importTable),h.setExportTable(T,i.exportTable),i.exportStart!=null&&h.setExportStart(T,Ct(i.exportStart)?i.exportStart:"_start"),h.setMemoryBase(T,i.memoryBase>>>0),h.setTableBase(T,i.tableBase>>>0),h.setSourceMap(T,i.sourceMap!=null),h.setUncheckedBehavior(T,mn),h.setNoUnsafe(T,i.noUnsafe),h.setPedantic(T,i.pedantic),h.setLowMemoryLimit(T,i.lowMemoryLimit>>>0),h.setExportRuntime(T,i.exportRuntime),h.setBundleVersion(T,r,s,u),!i.stackSize&&tn===2&&(i.stackSize=h.DEFAULT_STACK_SIZE),h.setStackSize(T,i.stackSize),h.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 x=o[l],A=x.indexOf("=");if(A<0)return z(Error(`Global alias '${x}' is invalid.`));let F=x.substring(0,A).trim(),C=x.substring(A+1).trim();if(!F.length)return z(Error(`Global alias '${x}' is invalid.`));h.addGlobalAlias(T,F,C)}}let N;if((N=i.disable)!=null){typeof N=="string"&&(N=N.split(","));for(let o=0,l=N.length;o<l;++o){let c=N[o].trim(),x=h[`FEATURE_${Te(c)}`];if(!x)return z(Error(`Feature '${c}' is unknown.`));h.setFeature(T,x,!1)}}if((N=i.enable)!=null){typeof N=="string"&&(N=N.split(","));for(let o=0,l=N.length;o<l;++o){let c=N[o].trim(),x=h[`FEATURE_${Te(c)}`];if(!x)return z(Error(`Feature '${c}' is unknown.`));h.setFeature(T,x,!0)}}let $=0,J=0;i.optimize&&($=Be,J=Se),typeof i.optimizeLevel=="number"&&($=i.optimizeLevel),typeof i.shrinkLevel=="number"&&(J=i.shrinkLevel),$=Math.min(Math.max($,0),3),J=Math.min(Math.max(J,0),2),h.setOptimizeLevelHints(T,$,J),S=h.newProgram(T);let rn=[];if(Array.isArray(t.transforms)&&rn.push(...t.transforms),i.transform){let o=$n(i.transform);for(let l=0,c=o.length;l<c;++l){let x=o[l].trim(),A,F;if(Vn.resolve)try{A=Vn.resolve(x,{paths:[U.cwd(),B]}),F=await import(dn.pathToFileURL(A)),F.default&&(F=F.default)}catch(C){try{F=Vn(A)}catch{return z(C)}}else try{F=await import(new URL(x,import.meta.url)),F.default&&(F=F.default)}catch(C){return z(C)}if(!F||typeof F!="function"&&typeof F!="object")return z(Error("not a transform: "+o[l]));rn.push(F)}}try{rn=rn.map(o=>(typeof o=="function"&&(Object.assign(o.prototype,{program:S,binaryen:pn,baseDir:B,stdout:p,stderr:b,log:console.error,readFile:d,writeFile:g,listFiles:y}),o=new o),o))}catch(o){return z(o)}async function wn(o,...l){for(let c=0,x=rn.length;c<x;++c){let A=rn[c];if(typeof A[o]=="function")try{let F=n.begin();n.transformCount++,await A[o](...l),n.transformTime+=n.end(F)}catch(F){return F}}}Object.keys(X).forEach(o=>{if(o.includes("/"))return;let l=n.begin();n.parseCount++,h.parse(S,X[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=$n(on);for(let l=0,c=on.length;l<c;++l){let x=on[l],A;x.endsWith(_)?(A=[v.basename(x)],x=v.dirname(x)):A=await y(x,B)||[];for(let F of A){let C=await d(F,x);if(C==null)return z(Error(`Library file '${F}' not found.`));X[F.replace(hn,"")]=C;let I=n.begin();n.parseCount++,h.parse(S,C,P+F,!1),n.parseTime+=n.end(I)}}}i.path=i.path||[];let bn=new Map;async function Oe(o,l){let c=null,x=null;if(!o.startsWith(P))(c=await d(x=o+_,B))==null&&(c=await d(x=o+"/index"+_,B))==null&&(x=o+_,c=await d(o+_t,B));else{let A=o.substring(P.length),F=`${A}/index`;if(Object.prototype.hasOwnProperty.call(X,A))c=X[A],x=P+A+_;else if(Object.prototype.hasOwnProperty.call(X,F))c=X[F],x=P+F+_;else{for(let C of on)if((c=await d(A+_,C))!=null){x=P+A+_;break}else if((c=await d(F+_,C))!=null){x=P+F+_;break}if(c==null){let C=o.match(/^~lib\/((?:@[^/]+\/)?[^/]+)(?:\/(.+))?/);if(C){let I=C[1],q=C[2]||"index",vn=bn.has(l)?bn.get(l):".",M=[],D=v.resolve(B,vn).split(jn);for(let w=D.length,O=Kn?1:0;w>=O;--w)D[w-1]!=="node_modules"&&M.push(`${D.slice(0,w).join(jn)}${jn}node_modules`);M.push(...i.path);for(let w of M.map(O=>v.relative(B,O))){let O=q;if((c=await d(v.join(w,I,O+_),B))!=null){x=`${P}${I}/${O}${_}`,bn.set(x.replace(hn,""),v.join(w,I));break}let un=`${q}/index`;if((c=await d(v.join(w,I,un+_),B))!=null){x=`${P}${I}/${un}${_}`,bn.set(x.replace(hn,""),v.join(w,I));break}}}}}}return c==null?null:{sourceText:c,sourcePath:x}}function Le(o=[]){do{let l=h.nextFile(S);if(l==null)break;o.push(l)}while(!0);return o}async function Jn(){let o;for(;(o=Le()).length;){let c=[];for(let x of o){let A=h.getDependee(S,x);c.push(Oe(x,A))}c=await Promise.all(c);for(let x=0,A=o.length;x<A;++x){let F=o[x],C=c[x],I=n.begin();n.parseCount++,C?h.parse(S,C.sourceText,C.sourcePath,!1):h.parse(S,null,F+_,!1),n.parseTime+=n.end(I)}}let l=gn(S,b,i.disableWarning,t.reportDiagnostic,j.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=X[l];if(c==null){if(l=o,c=await d(l+_,B),c==null)return z(Error(`Runtime '${v.resolve(B,l+_)}' is not found.`))}else l=`~lib/${l}`;let x=n.begin();n.parseCount++,h.parse(S,c,l+_,!0),n.parseTime+=n.end(x)}for(let o=0,l=e.length;o<l;++o){let c=String(e[o]),x=v.isAbsolute(c)?v.relative(B,c):v.normalize(c);x=x.replace(/\\/g,"/").replace(hn,"").replace(/\/$/,"");let A=await d(x+_,B);if(A==null){let C=`${x}/index${_}`;A=await d(C,B),A!=null?x=C:x+=_}else x+=_;let F=n.begin();n.parseCount++,h.parse(S,A,x,!0),n.parseTime+=n.end(F)}{let o=await Jn();if(o)return o}{let o=await wn("afterParse",S.parser);if(o)return z(o)}{let o=await Jn();if(o)return o}{let o=n.begin();n.initializeCount++;try{h.initializeProgram(S)}catch(l){L("initialize",l)}n.initializeTime+=n.end(o)}{let o=await wn("afterInitialize",S);if(o)return z(o)}{let o=n.begin();n.compileCount++;try{H=h.compile(S)}catch(l){let c=gn(S,b,i.disableWarning,t.reportDiagnostic,j.enabled);if(c){let x=Error(`${c} compile error(s)`);return x.stack=x.message,z(x)}L("compile",l)}n.compileTime+=n.end(o)}R=pn.wrapModule(typeof H=="number"||H instanceof Number?h.getBinaryenModuleRef(H):H.ref);let ln=gn(S,b,i.disableWarning,t.reportDiagnostic,j.enabled);if(ln){let o=Error(`${ln} compile error(s)`);return o.stack=o.message,z(o)}{let o=await wn("afterCompile",R);if(o)return z(o)}if(ln=gn(S,b,i.disableWarning,t.reportDiagnostic,j.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=h.validate(H);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){L("runPasses",l)}n.compileTime+=n.end(o)}else if(i.trapMode!=="allow")return z(Error("Unsupported trap mode"));let Qn=i.debug,Re=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++,h.optimize(H,$,J,Qn,ne)}catch(l){L("optimize",l)}try{R.runPasses(yn)}catch(l){L("runPasses",l)}if(Re){let l;try{let c=n.begin();n.emitCount++,l=R.emitBinary(),n.emitTime+=n.end(c)}catch(c){L("emitBinary (converge)",c)}do{try{n.optimizeCount++,h.optimize(H,$,J,Qn,ne)}catch(x){L("optimize (converge)",x)}try{R.runPasses(yn)}catch(x){L("runPasses (converge)",x)}let c;try{let x=n.begin();n.emitCount++,c=R.emitBinary(),n.emitTime+=n.end(x)}catch(x){L("emitBinary (converge)",x)}if(c.length>=l.length){c.length>l.length&&b.write(`Last converge was suboptimal.${E}`);break}l=c}while(!0)}n.optimizeTime+=n.end(o)}let an=[];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,x=i.textFile!=null,A=c||x,F=c&&i.outFile.length>0||x&&i.textFile.length>0,C=F?(i.outFile||i.textFile).replace(/\.\w+$/,""):null,I=F?v.basename(C):"output";if(h.setBasenameHint(T,I),i.outFile!=null){let M=i.sourceMap!=null?i.sourceMap.length?i.sourceMap:`./${I}.wasm.map`:null,D=n.begin();n.emitCount++;let w;try{w=R.emitBinary(M)}catch(O){L("emitBinary",O)}if(n.emitTime+=n.end(D),i.outFile.length?an.push(g(i.outFile,w.binary,B)):(l=!0,Fn(w.binary)),w.sourceMap!="")if(i.outFile.length){let O=JSON.parse(w.sourceMap);O.sourceRoot=`./${I}`;let un=[];for(let En=0,ke=O.sources.length;En<ke;++En){let re=O.sources[En],oe=h.getSource(S,re.replace(hn,""));if(oe==null)return z(Error(`Source of file '${re}' not found.`));un[En]=oe}O.sourcesContent=un,an.push(g(v.join(v.dirname(i.outFile),v.basename(M)).replace(/^\.\//,""),JSON.stringify(O),B))}else b.write(`Skipped source map (no output path)${E}`)}if(i.textFile!=null||!A){let M=n.begin();n.emitCount++;let D;try{pn.setOptimizeStackIR(!0),D=i.textFile?.endsWith(".wast")?R.emitText():R.emitStackIR()}catch(w){L("emitText",w)}n.emitTime+=n.end(M),i.textFile!=null&&i.textFile.length?an.push(g(i.textFile,D,B)):l||Fn(D)}let q=o.includes("esm"),vn=!q&&o.includes("raw");if(q||vn)if(C){let M=n.begin();n.emitCount++;let D;try{D=h.buildTSD(S,q)}catch(w){L("buildTSD",w)}n.emitTime+=n.end(M),an.push(g(C+".d.ts",D,B))}else b.write(`Skipped TypeScript binding (no output path)${E}`);if(q||vn)if(C){let M=n.begin();n.emitCount++;let D;try{D=h.buildJS(S,q)}catch(w){L("buildJS",w)}n.emitTime+=n.end(M),an.push(g(C+".js",D,B))}else b.write(`Skipped JavaScript binding (no output path)${E}`)}try{await Promise.all(an)}catch(o){return z(o)}return n.total=n.end(a),i.stats&&b.write(n.toString()),z(null);async function ee(o,l){let c=v.resolve(l,o);try{return n.readCount++,await G.promises.readFile(c,"utf8")}catch{return null}}async function te(o,l,c){try{n.writeCount++;let x=v.resolve(c,v.dirname(o)),A=v.join(x,v.basename(o));return await G.promises.mkdir(x,{recursive:!0}),await G.promises.writeFile(A,l),!0}catch{return!1}}async function ie(o,l){try{return n.readCount++,(await G.promises.readdir(v.join(l,o))).filter(c=>Tt.test(c))}catch{return null}}function Fn(o){Fn.used||(Fn.used=!0,n.writeCount++),p.write(o)}function L(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("")),U.exit(1)}}function Gn(e){return Object.prototype.toString.call(e)==="[object Object]"}async function Ce(e,t,n){let a=await n(e,t),s=v.join(t,e);if(!a)return null;let r;try{r=JSON.parse(a)}catch(u){throw new Error(`Toilconfig is not valid json: ${s}`,{cause:u})}if(r.options&&!Gn(r.options))throw new Error(`Toilconfig.options is not an object: ${s}`);if(r.include&&!Array.isArray(r.include))throw new Error(`Toilconfig.include is not an array: ${s}`);if(r.targets){if(!Gn(r.targets))throw new Error(`Toilconfig.targets is not an object: ${s}`);let u=Object.keys(r.targets);for(let f=0;f<u.length;f++){let p=u[f];if(!Gn(r.targets[p]))throw new Error(`Toilconfig.targets.${p} is not an object: ${s}`)}}if(r.extends&&typeof r.extends!="string")throw new Error(`Toilconfig.extends is not a string: ${s}`);return r}function gn(e,t,n,a,s){typeof s>"u"&&t&&(s=t.isTTY);let r=0;do{let p=h.nextDiagnostic(e);if(!p)break;if(t){let b=d=>{if(n==null)return!1;if(!n.length)return!0;let g=h.getDiagnosticCode(d);return n.includes(g)};(h.isError(p)||!b(p))&&t.write(h.formatDiagnostic(p,s,!0)+E+E)}if(a){let b=function(g){return g&&{start:h.getRangeStart(g),end:h.getRangeEnd(g),source:d(h.getRangeSource(g))}||null},d=function(g){return g&&{normalizedPath:h.getSourceNormalizedPath(g)}||null};var u=b,f=d;a({message:h.getDiagnosticMessage(p),code:h.getDiagnosticCode(p),category:h.getDiagnosticCategory(p),range:b(h.getDiagnosticRange(p)),relatedRange:b(h.getDiagnosticRelatedRange(p))})}h.isError(p)&&++r}while(!0);return r}var Cn=class{readCount=0;writeCount=0;parseTime=0;parseCount=0;initializeTime=0;initializeCount=0;compileTime=0;compileCount=0;emitTime=0;emitCount=0;validateTime=0;validateCount=0;optimizeTime=0;optimizeCount=0;transformTime=0;transformCount=0;begin(){return U.hrtime()}end(t){let n=U.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()),r=n.reduce((m,i)=>Math.max(i.length,m),0),u=a.reduce((m,i)=>Math.max(i.length,m),0),f=s.reduce((m,i)=>Math.max(i.length,m),0),p=r+u+f+6,b=[];b.push(`\u256D\u2500${"\u2500".repeat(p)}\u2500\u256E${E}`);let d="Stats";b.push(`\u2502 ${d}${" ".repeat(p-d.length)} \u2502${E}`),b.push(`\u255E\u2550${"\u2550".repeat(r)}\u2550\u2564\u2550${"\u2550".repeat(u)}\u2550\u2564\u2550${"\u2550".repeat(f)}\u2550\u2561${E}`);for(let m=0,i=n.length;m<i;++m)b.push(`\u2502 ${n[m].padEnd(r)} \u2502 ${a[m].padStart(u)} \u2502 ${s[m].padStart(f)} \u2502${E}`);b.push(`\u251C\u2500${"\u2500".repeat(r)}\u2500\u2534\u2500${"\u2500".repeat(u)}\u2500\u2534\u2500${"\u2500".repeat(f)}\u2500\u2524${E}`);let g=`Took ${t(this.total)}`;b.push(`\u2502 ${g}${" ".repeat(p-g.length)} \u2502${E}`);let y=`${this.readCount} reads, ${this.writeCount} writes`;return b.push(`\u2502 ${y}${" ".repeat(p-y.length)} \u2502${E}`),b.push(`\u2570\u2500${"\u2500".repeat(p)}\u2500\u256F${E}`),b.join("")}},ze=typeof global<"u"&&global.Buffer?global.Buffer.allocUnsafe||(e=>new global.Buffer(e)):e=>new Uint8Array(e);function Hn(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 r=ze(n);for(n=a=0;a<s;)r.set(this[a],n),n+=this[a].length,++a;return r},t.toString=function(){let n=this.toBuffer();return Tn.read(n,0,n.length)},t}var wt={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,St as compileString,qn as configToArguments,Hn as createMemoryStream,Wn as default,Be as defaultOptimizeLevel,Se as defaultShrinkLevel,Bt as definitionFiles,X as libraryFiles,P as libraryPrefix,we as main,zt as options,wt as tscOptions,Xn as version};
24474
+ //# sourceMappingURL=cli.js.map