sommark 4.1.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import path from "node:path";
1
+ import path from "pathe";
2
2
  import fs from "node:fs/promises";
3
3
  import { pathToFileURL } from "node:url";
4
4
 
@@ -40,7 +40,7 @@ export async function findAndLoadConfig(targetPath) {
40
40
  try {
41
41
  const absoluteTarget = path.resolve(cwd, targetPath);
42
42
  const stats = await fs.stat(absoluteTarget);
43
-
43
+
44
44
  // If target is a .js file, it might be an explicit config (legacy/internal support)
45
45
  if (stats.isFile() && absoluteTarget.endsWith(".js") && !absoluteTarget.endsWith("smark.config.js")) {
46
46
  configPath = absoluteTarget;
@@ -74,7 +74,7 @@ export async function findAndLoadConfig(targetPath) {
74
74
  // No config found in CWD
75
75
  }
76
76
  }
77
-
77
+
78
78
  const defaultConfig = {
79
79
  outputFile: "output",
80
80
  outputDir: startDir,
@@ -97,12 +97,12 @@ export async function findAndLoadConfig(targetPath) {
97
97
  if (loadedConfig) {
98
98
  // Support both mapperFile and mappingFile (backwards compatibility)
99
99
  const finalMapper = loadedConfig.mapperFile || loadedConfig.mappingFile || defaultConfig.mapperFile;
100
-
101
- const finalConfig = {
102
- ...defaultConfig,
103
- ...loadedConfig,
100
+
101
+ const finalConfig = {
102
+ ...defaultConfig,
103
+ ...loadedConfig,
104
104
  mapperFile: finalMapper,
105
- resolvedConfigPath: configPath
105
+ resolvedConfigPath: configPath
106
106
  };
107
107
  if (loadedConfig.outputDir) {
108
108
  const configDir = path.dirname(configPath);
@@ -18,10 +18,7 @@ export function registerHostSettings(settings) {
18
18
  hostSettings = settings || {};
19
19
  }
20
20
 
21
- const manualVersion = "4.1.0";
22
- const version = await import(new URL("../../package.json", import.meta.url), { with: { type: "json" } })
23
- .then(pkg => pkg.default.version || manualVersion)
24
- .catch(() => manualVersion);
21
+ const version = "4.3.0";
25
22
 
26
23
  const SomMark = {
27
24
  version,
@@ -1,9 +1,24 @@
1
- import path from "node:path";
2
- import fs from "node:fs";
1
+ import path from "pathe";
3
2
  import * as acorn from "acorn";
4
3
  import evaluator from "../evaluator.js";
5
4
  import { transpilerError } from "../errors.js";
6
5
 
6
+ let _nodeFsCache;
7
+ async function getNodeFs() {
8
+ if (_nodeFsCache !== undefined) return _nodeFsCache;
9
+ try {
10
+ const m = await import("node:fs");
11
+ const raw = m.default || m;
12
+ _nodeFsCache = {
13
+ exists: (p) => raw.promises.access(p).then(() => true).catch(() => false),
14
+ readFile: (p, enc) => raw.promises.readFile(p, enc),
15
+ };
16
+ } catch {
17
+ _nodeFsCache = null;
18
+ }
19
+ return _nodeFsCache;
20
+ }
21
+
7
22
  /**
8
23
  * Preprocesses a runtime JS block, parsing it with Acorn to locate
9
24
  * SomMark.static("...") and SomMark.import("...") calls, evaluating/loading them,
@@ -14,7 +29,7 @@ import { transpilerError } from "../errors.js";
14
29
  * @param {Object} security - Security restrictions from the engine configuration.
15
30
  * @returns {Promise<string>} - The preprocessed code.
16
31
  */
17
- export async function preprocessRuntimeLogic(code, filename = null, security = {}) {
32
+ export async function preprocessRuntimeLogic(code, filename = null, security = {}, instance = null) {
18
33
  let ast;
19
34
  try {
20
35
  ast = acorn.parse(code, { ecmaVersion: "latest", sourceType: "module" });
@@ -121,14 +136,16 @@ export async function preprocessRuntimeLogic(code, filename = null, security = {
121
136
  }
122
137
 
123
138
  // Resolve the file path relative to the template's base directory
124
- let baseDir = process.cwd();
139
+ let baseDir = instance?.cwd || "/";
125
140
  if (filename && filename !== "anonymous") {
126
141
  baseDir = path.dirname(path.resolve(filename));
127
142
  }
128
143
  const resolvedPath = path.resolve(baseDir, argValue);
129
144
 
145
+ const fsImpl = instance?.fs || await getNodeFs();
146
+
130
147
  // File presence validation
131
- if (!fs.existsSync(resolvedPath)) {
148
+ if (!fsImpl || !await fsImpl.exists(resolvedPath)) {
132
149
  transpilerError([
133
150
  `<$red:SomMark.import File Error:$> File not found: <$magenta:${argValue}$>{line}`,
134
151
  `<$yellow:Resolved Path:$> <$blue:${resolvedPath}$>{line}`
@@ -145,7 +162,7 @@ export async function preprocessRuntimeLogic(code, filename = null, security = {
145
162
  }
146
163
 
147
164
  let serialized = "";
148
- const content = fs.readFileSync(resolvedPath, "utf-8");
165
+ const content = await fsImpl.readFile(resolvedPath, "utf-8");
149
166
 
150
167
  if (ext === ".json") {
151
168
  // Validate JSON structure
@@ -0,0 +1,12 @@
1
+ export function fileURLToPath(url) {
2
+ if (typeof url !== "string") return url;
3
+ if (url.startsWith("file://")) {
4
+ let p = url.slice(7);
5
+ // On Windows (starts with /C:/ or similar), remove the leading slash:
6
+ if (/^\/[a-zA-Z]:/.test(p)) {
7
+ p = p.slice(1);
8
+ }
9
+ return p;
10
+ }
11
+ return url;
12
+ }
package/core/modules.js CHANGED
@@ -1,6 +1,5 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { fileURLToPath } from "node:url";
1
+ import path from "pathe";
2
+ import { fileURLToPath } from "./helpers/url.js";
4
3
  import { runtimeError } from "./errors.js";
5
4
  import { IMPORT, USE_MODULE, TEXT, BLOCK, COMMENT, SLOT } from "./labels.js";
6
5
 
@@ -8,6 +7,9 @@ import { IMPORT, USE_MODULE, TEXT, BLOCK, COMMENT, SLOT } from "./labels.js";
8
7
  * Resolves a module path relative to a base directory.
9
8
  */
10
9
  const resolveModulePath = (filePath, currentBaseDir) => {
10
+ if (/^https?:\/\//.test(currentBaseDir)) {
11
+ return new URL(filePath, currentBaseDir.endsWith("/") ? currentBaseDir : currentBaseDir + "/").href;
12
+ }
11
13
  return path.resolve(currentBaseDir, filePath);
12
14
  };
13
15
 
@@ -18,13 +20,13 @@ const resolveModulePath = (filePath, currentBaseDir) => {
18
20
  * @param {Object} [aliases={}] - Custom path aliases for modules.
19
21
  * @returns {string} - The corrected absolute path.
20
22
  */
21
- const normalizePath = (filename, aliases = {}) => {
22
- if (!filename || filename === "anonymous") return process.cwd();
23
+ const normalizePath = (filename, aliases = {}, cwd = "/") => {
24
+ if (!filename || filename === "anonymous") return cwd;
23
25
 
24
26
  // Handle Aliases (like @/components)
25
27
  for (const [prefix, replacement] of Object.entries(aliases)) {
26
28
  if (filename.startsWith(prefix)) {
27
- const resolvedPath = path.resolve(process.cwd(), filename.replace(prefix, replacement));
29
+ const resolvedPath = path.resolve(cwd, filename.replace(prefix, replacement));
28
30
  return resolvedPath;
29
31
  }
30
32
  }
@@ -37,7 +39,7 @@ const normalizePath = (filename, aliases = {}) => {
37
39
  }
38
40
  }
39
41
 
40
- return path.resolve(process.cwd(), filename);
42
+ return path.resolve(cwd, filename);
41
43
  };
42
44
 
43
45
  const VAR_PATTERN = /SOMMARK_UNRESOLVED_v_(.+?)_SOMMARK/g;
@@ -135,7 +137,7 @@ export async function resolveModules(ast, context) {
135
137
  const modules = new Map();
136
138
  const filename = context.filename || "anonymous";
137
139
  const importAliases = context.instance.importAliases || {};
138
- const absFilename = normalizePath(filename, importAliases);
140
+ const absFilename = normalizePath(filename, importAliases, context.instance.cwd || "/");
139
141
 
140
142
  // baseDir can be a local path
141
143
  const baseDir = context.instance.baseDir || ((filename === "anonymous") ? absFilename : path.dirname(absFilename));
@@ -231,7 +233,7 @@ export async function resolveModules(ast, context) {
231
233
  let resolvedPath = filePath;
232
234
  for (const [prefix, replacement] of Object.entries(importAliases)) {
233
235
  if (filePath.startsWith(prefix)) {
234
- resolvedPath = path.resolve(process.cwd(), filePath.replace(prefix, replacement));
236
+ resolvedPath = path.resolve(context.instance.cwd || "/", filePath.replace(prefix, replacement));
235
237
  break;
236
238
  }
237
239
  }
@@ -241,11 +243,11 @@ export async function resolveModules(ast, context) {
241
243
 
242
244
  // Local Path Resolution with Auto-Extension
243
245
  let localPath = absolutePath;
244
- if (!fs.existsSync(localPath) && !localPath.endsWith(".smark")) {
246
+ if (!await context.instance.fs.exists(localPath) && !localPath.endsWith(".smark")) {
245
247
  const withSmark = localPath + ".smark";
246
- if (fs.existsSync(withSmark)) localPath = withSmark;
248
+ if (await context.instance.fs.exists(withSmark)) localPath = withSmark;
247
249
  }
248
- if (!fs.existsSync(localPath)) {
250
+ if (!await context.instance.fs.exists(localPath)) {
249
251
  runtimeError([`<$red:Module Path Error:$> File not found: <$magenta:${filePath}$> at line <$yellow:${node.range.start.line + 1}$>`]);
250
252
  }
251
253
  let mod = { path: absolutePath, localPath: localPath, type: "smark" };
@@ -289,7 +291,7 @@ export async function resolveModules(ast, context) {
289
291
  if (cached) {
290
292
  expandedNodes = trimAst(cloneAst(cached));
291
293
  } else {
292
- const content = fs.readFileSync(mod.localPath, "utf-8");
294
+ const content = await context.instance.fs.readFile(mod.localPath, "utf-8");
293
295
  const SomMark = context.instance.constructor;
294
296
  const subSmark = new SomMark({
295
297
  src: content,
@@ -347,7 +349,7 @@ export async function resolveModules(ast, context) {
347
349
  if (cached) {
348
350
  subAst = cloneAst(cached);
349
351
  } else {
350
- const content = fs.readFileSync(mod.localPath, "utf-8");
352
+ const content = await context.instance.fs.readFile(mod.localPath, "utf-8");
351
353
  const SomMark = context.instance.constructor;
352
354
  const subSmark = new SomMark({
353
355
  src: content,
@@ -1,4 +1,3 @@
1
- import crypto from "node:crypto";
2
1
  import { BLOCK, TEXT, INLINE, ATBLOCK, COMMENT, COMMENT_BLOCK, STATIC_LOGIC, RUNTIME_LOGIC, FOR_EACH } from "./labels.js";
3
2
  import { transpilerError } from "./errors.js";
4
3
  import evaluator from "./evaluator.js";
@@ -7,13 +6,13 @@ import { dedentBy } from "../helpers/dedent.js";
7
6
  import { preprocessRuntimeLogic } from "./helpers/preprocessor.js";
8
7
  import { wrapRuntimeLogic } from "./helpers/runtimeOutput.js";
9
8
 
10
- /**
11
- * SomMark Transpiler
12
- * This engine converts the AST into its final text format (like HTML or Markdown)
13
- * using rules provided by a mapper.
14
- */
9
+ const randomBytesHex = (size) => {
10
+ const arr = new Uint8Array(size);
11
+ globalThis.crypto.getRandomValues(arr);
12
+ return Array.from(arr).map(b => b.toString(16).padStart(2, "0")).join("");
13
+ };
15
14
 
16
- const BODY_PLACEHOLDER = `SOMMARKBODYPLACEHOLDER${crypto.randomBytes(8).toString("hex")}SOMMARK`;
15
+ const BODY_PLACEHOLDER = `SOMMARKBODYPLACEHOLDER${randomBytesHex(8)}SOMMARK`;
17
16
 
18
17
  /**
19
18
  * Extracts all plain text from a node and its children.
@@ -46,7 +45,7 @@ function getNodeText(node) {
46
45
  * @param {Object} mapper_file - The rules for how to convert each node.
47
46
  * @returns {Promise<string>} - The final text for this node.
48
47
  */
49
- async function generateOutput(ast, i, format, mapper_file, security = {}, parentId = null, generateRuntimeOutput = false, hideRuntimeOutput = false) {
48
+ async function generateOutput(ast, i, format, mapper_file, security = {}, parentId = null, generateRuntimeOutput = false, hideRuntimeOutput = false, instance = null) {
50
49
  const node = Array.isArray(ast) ? ast[i] : ast;
51
50
  if (!node) return "";
52
51
 
@@ -61,7 +60,7 @@ async function generateOutput(ast, i, format, mapper_file, security = {}, parent
61
60
  if (node.body) {
62
61
  evaluator.pushScope();
63
62
  for (let j = 0; j < node.body.length; j++) {
64
- bodyOutput += await generateOutput(node.body, j, format, mapper_file, security, parentId, generateRuntimeOutput, hideRuntimeOutput);
63
+ bodyOutput += await generateOutput(node.body, j, format, mapper_file, security, parentId, generateRuntimeOutput, hideRuntimeOutput, instance);
65
64
  }
66
65
  await evaluator.popScope();
67
66
  }
@@ -86,7 +85,7 @@ async function generateOutput(ast, i, format, mapper_file, security = {}, parent
86
85
  }
87
86
 
88
87
  if (node.type === RUNTIME_LOGIC) {
89
- const preprocessed = await preprocessRuntimeLogic(node.code, mapper_file?.options?.filename, security);
88
+ const preprocessed = await preprocessRuntimeLogic(node.code, mapper_file?.options?.filename, security, instance);
90
89
  if (hideRuntimeOutput) {
91
90
  return "";
92
91
  }
@@ -169,7 +168,7 @@ async function generateOutput(ast, i, format, mapper_file, security = {}, parent
169
168
  });
170
169
 
171
170
  for (let j = 0; j < cleanedBody.length; j++) {
172
- output += await generateOutput(cleanedBody, j, format, mapper_file, security, parentId, generateRuntimeOutput, hideRuntimeOutput);
171
+ output += await generateOutput(cleanedBody, j, format, mapper_file, security, parentId, generateRuntimeOutput, hideRuntimeOutput, instance);
173
172
  }
174
173
 
175
174
  await evaluator.popScope();
@@ -192,7 +191,7 @@ async function generateOutput(ast, i, format, mapper_file, security = {}, parent
192
191
 
193
192
  const hasRuntime = node.body?.some(child => child.type === RUNTIME_LOGIC);
194
193
  if (hasRuntime) {
195
- secretId = `sommark-${node.id.toLowerCase()}-${crypto.randomBytes(4).toString("hex")}`;
194
+ secretId = `sommark-${node.id.toLowerCase()}-${randomBytesHex(4)}`;
196
195
  }
197
196
  }
198
197
 
@@ -248,7 +247,7 @@ async function generateOutput(ast, i, format, mapper_file, security = {}, parent
248
247
  let resolvedBody = "";
249
248
  evaluator.pushScope();
250
249
  for (let j = 0; j < node.body.length; j++) {
251
- resolvedBody += await generateOutput(node.body, j, format, mapper_file, security, parentId, generateRuntimeOutput, hideRuntimeOutput);
250
+ resolvedBody += await generateOutput(node.body, j, format, mapper_file, security, parentId, generateRuntimeOutput, hideRuntimeOutput, instance);
252
251
  }
253
252
  await evaluator.popScope();
254
253
  content = dedentBy(resolvedBody, node.range?.start?.character || 0);
@@ -258,7 +257,7 @@ async function generateOutput(ast, i, format, mapper_file, security = {}, parent
258
257
  let childrenOutput = "";
259
258
  if (node.body) {
260
259
  for (let j = 0; j < node.body.length; j++) {
261
- childrenOutput += await generateOutput(node.body, j, format, mapper_file, security, secretId || parentId, generateRuntimeOutput, hideRuntimeOutput);
260
+ childrenOutput += await generateOutput(node.body, j, format, mapper_file, security, secretId || parentId, generateRuntimeOutput, hideRuntimeOutput, instance);
262
261
  }
263
262
  }
264
263
  return childrenOutput;
@@ -306,8 +305,8 @@ async function generateOutput(ast, i, format, mapper_file, security = {}, parent
306
305
  switch (body_node.type) {
307
306
  case TEXT:
308
307
  const text = String(body_node.text || "");
309
- // Dedent text relative to the parent block's indentation
310
- const localDedentedText = dedentBy(text, node.range?.start?.character || 0);
308
+ // Only dedent multi-line text inline spaces (no newlines) are separators, not indentation
309
+ const localDedentedText = text.includes("\n") ? dedentBy(text, node.range?.start?.character || 0) : text;
311
310
  let bodyTextVal = mapper_file ? mapper_file.text(localDedentedText, { ...target?.options, escape: parentEscape }) : localDedentedText;
312
311
  if (parentEscape === false && security?.sanitize && typeof security.sanitize === "function") {
313
312
  bodyTextVal = security.sanitize(bodyTextVal);
@@ -370,11 +369,11 @@ async function generateOutput(ast, i, format, mapper_file, security = {}, parent
370
369
 
371
370
  case FOR_EACH:
372
371
  case BLOCK:
373
- bodyOutput = await generateOutput(body_node, 0, format, mapper_file, security, secretId || parentId, generateRuntimeOutput, hideRuntimeOutput);
372
+ bodyOutput = await generateOutput(body_node, 0, format, mapper_file, security, secretId || parentId, generateRuntimeOutput, hideRuntimeOutput, instance);
374
373
  break;
375
374
 
376
375
  case RUNTIME_LOGIC:
377
- const preprocessedBody = await preprocessRuntimeLogic(body_node.code, mapper_file?.options?.filename, security);
376
+ const preprocessedBody = await preprocessRuntimeLogic(body_node.code, mapper_file?.options?.filename, security, instance);
378
377
  if (hideRuntimeOutput) {
379
378
  bodyOutput = "";
380
379
  } else {
@@ -483,6 +482,11 @@ export async function transpiler(optionsOrAst, format, mapperFile) {
483
482
  if (!body || !Array.isArray(body)) return "";
484
483
 
485
484
  const settings = optionsOrAst?.settings || { format: targetFormat || "html" };
485
+ const instance = optionsOrAst?.instance;
486
+ if (instance) {
487
+ settings.instance = instance;
488
+ settings.fs = instance.fs;
489
+ }
486
490
 
487
491
  // Initialize Logic Sandbox
488
492
  await evaluator.init(null, security, settings, targetMapper);
@@ -500,7 +504,7 @@ export async function transpiler(optionsOrAst, format, mapperFile) {
500
504
  try {
501
505
  for (let i = 0; i < body.length; i++) {
502
506
  const node = body[i];
503
- const blockOutput = await generateOutput(body, i, targetFormat, targetMapper, security, null, generateRuntimeOutput, hideRuntimeOutput);
507
+ const blockOutput = await generateOutput(body, i, targetFormat, targetMapper, security, null, generateRuntimeOutput, hideRuntimeOutput, instance);
504
508
 
505
509
  let finalBlockOutput = blockOutput;
506
510
  if (prev_was_silent && node.type === TEXT) {
@@ -0,0 +1,24 @@
1
+ async function QuickJSRaw(moduleArg={}){var moduleRtn;var c=moduleArg,aa=!!globalThis.window,n=!!globalThis.WorkerGlobalScope;function q(a){a={log:a||function(){}};for(const d of q.Pa)d(a);return c.quickJSEmscriptenExtensions=a}q.Pa=[];c.quickjsEmscriptenInit=q;q.Pa.push(a=>{a.getWasmMemory=function(){return r};});var t="./this.program",ba=import.meta.url,u="",v,w;
2
+ if(aa||n){try{u=(new URL(".",ba)).href;}catch{}n&&(w=a=>{var d=new XMLHttpRequest;d.open("GET",a,false);d.responseType="arraybuffer";d.send(null);return new Uint8Array(d.response)});v=async a=>{a=await fetch(a,{credentials:"same-origin"});if(a.ok)return a.arrayBuffer();throw Error(a.status+" : "+a.url);};}var y=console.log.bind(console),z=console.error.bind(console),A,B=false,C,D,E,F,G,H,I,J=false;
3
+ function K(){var a=r.buffer;c.HEAP8=F=new Int8Array(a);c.HEAPU8=G=new Uint8Array(a);H=new Int32Array(a);I=new Uint32Array(a);new BigInt64Array(a);new BigUint64Array(a);}function L(a){c.onAbort?.(a);a="Aborted("+a+")";z(a);B=true;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");E?.(a);throw a;}var M;
4
+ async function ca(a){if(!A)try{var d=await v(a);return new Uint8Array(d)}catch{}if(a==M&&A)a=new Uint8Array(A);else if(w)a=w(a);else throw "both async and sync fetching of the wasm failed";return a}async function da(a,d){try{var b=await ca(a);return await WebAssembly.instantiate(b,d)}catch(e){z(`failed to asynchronously prepare wasm: ${e}`),L(e);}}
5
+ async function ea(a){var d=M;if(!A)try{var b=fetch(d,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(b,a)}catch(e){z(`wasm streaming compile failed: ${e}`),z("falling back to ArrayBuffer instantiation");}return da(d,a)}class N{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a;}}
6
+ var O=a=>{for(;0<a.length;)a.shift()(c);},P=[],fa=[],ha=()=>{var a=c.preRun.shift();fa.push(a);},Q=true,r,ia=new TextDecoder,ja=(a,d,b,e)=>{b=d+b;if(e)return b;for(;a[d]&&!(d>=b);)++d;return d},R=(a,d,b)=>a?ia.decode(G.subarray(a,ja(G,a,d,b))):"",S=0,ka=[0,31,60,91,121,152,182,213,244,274,305,335],la=[0,31,59,90,120,151,181,212,243,273,304,334],T={},ma=a=>{if(!(a instanceof N||"unwind"==a))throw a;},na=a=>{C=a;Q||0<S||(c.onExit?.(a),B=true);throw new N(a);},oa=a=>{if(!B)try{a();}catch(d){ma(d);}finally{if(!(Q||
7
+ 0<S))try{C=a=C,na(a);}catch(d){ma(d);}}},U=(a,d,b)=>{var e=G;if(!(0<b))return 0;var f=d;b=d+b-1;for(var g=0;g<a.length;++g){var h=a.codePointAt(g);if(127>=h){if(d>=b)break;e[d++]=h;}else if(2047>=h){if(d+1>=b)break;e[d++]=192|h>>6;e[d++]=128|h&63;}else if(65535>=h){if(d+2>=b)break;e[d++]=224|h>>12;e[d++]=128|h>>6&63;e[d++]=128|h&63;}else {if(d+3>=b)break;e[d++]=240|h>>18;e[d++]=128|h>>12&63;e[d++]=128|h>>6&63;e[d++]=128|h&63;g++;}}e[d]=0;return d-f},V={},pa=()=>{if(!W){var a={USER:"web_user",LOGNAME:"web_user",
8
+ PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:t||"./this.program"},d;for(d in V) void 0===V[d]?delete a[d]:a[d]=V[d];var b=[];for(d in a)b.push(`${d}=${a[d]}`);W=b;}return W},W,X=a=>{for(var d=0,b=0;b<a.length;++b){var e=a.charCodeAt(b);127>=e?d++:2047>=e?d+=2:55296<=e&&57343>=e?(d+=4,++b):d+=3;}return d},qa=[null,[],[]],ta=(a,d,b,e)=>{var f={string:k=>{var l=0;if(null!==k&&void 0!==k&&0!==k){l=X(k)+1;var p=Y(l);U(k,p,l);l=p;}return l},array:k=>
9
+ {var l=Y(k.length);F.set(k,l);return l}};a=c["_"+a];var g=[],h=0;if(e)for(var m=0;m<e.length;m++){var x=f[b[m]];x?(0===h&&(h=ra()),g[m]=x(e[m])):g[m]=e[m];}b=a(...g);return b=function(k){0!==h&&sa(h);return "string"===d?R(k):"boolean"===d?!!k:k}(b)};c.wasmMemory?r=c.wasmMemory:r=new WebAssembly.Memory({initial:(c.INITIAL_MEMORY||16777216)/65536,maximum:32768});K();c.noExitRuntime&&(Q=c.noExitRuntime);c.print&&(y=c.print);c.printErr&&(z=c.printErr);c.wasmBinary&&(A=c.wasmBinary);c.thisProgram&&(t=c.thisProgram);
10
+ if(c.preInit)for("function"==typeof c.preInit&&(c.preInit=[c.preInit]);0<c.preInit.length;)c.preInit.shift()();c.cwrap=(a,d,b,e)=>{var f=!b||b.every(g=>"number"===g||"boolean"===g);return "string"!==d&&f&&!e?c["_"+a]:(...g)=>ta(a,d,b,g)};c.UTF8ToString=R;c.stringToUTF8=(a,d,b)=>U(a,d,b);c.lengthBytesUTF8=X;
11
+ var ua,sa,Y,ra,va={b:(a,d,b,e)=>L(`Assertion failed: ${R(a)}, at: `+[d?R(d):"unknown filename",b,e?R(e):"unknown function"]),q:()=>L(""),l:()=>{Q=false;S=0;},m:function(a,d){a=-9007199254740992>a||9007199254740992<a?NaN:Number(a);a=new Date(1E3*a);H[d>>2]=a.getSeconds();H[d+4>>2]=a.getMinutes();H[d+8>>2]=a.getHours();H[d+12>>2]=a.getDate();H[d+16>>2]=a.getMonth();H[d+20>>2]=a.getFullYear()-1900;H[d+24>>2]=a.getDay();var b=a.getFullYear();H[d+28>>2]=(0!==b%4||0===b%100&&0!==b%400?la:ka)[a.getMonth()]+
12
+ a.getDate()-1|0;H[d+36>>2]=-(60*a.getTimezoneOffset());b=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();var e=(new Date(a.getFullYear(),0,1)).getTimezoneOffset();H[d+32>>2]=(b!=e&&a.getTimezoneOffset()==Math.min(e,b))|0;},j:(a,d)=>{T[a]&&(clearTimeout(T[a].id),delete T[a]);if(!d)return 0;var b=setTimeout(()=>{delete T[a];oa(()=>ua(a,performance.now()));},d);T[a]={id:b,Qa:d};return 0},n:(a,d,b,e)=>{var f=(new Date).getFullYear(),g=(new Date(f,0,1)).getTimezoneOffset();f=(new Date(f,6,1)).getTimezoneOffset();
13
+ I[a>>2]=60*Math.max(g,f);H[d>>2]=Number(g!=f);d=h=>{var m=Math.abs(h);return `UTC${0<=h?"-":"+"}${String(Math.floor(m/60)).padStart(2,"0")}${String(m%60).padStart(2,"0")}`};a=d(g);d=d(f);f<g?(U(a,b,17),U(d,e,17)):(U(a,e,17),U(d,b,17));},p:()=>Date.now(),k:a=>{var d=G.length;a>>>=0;if(2147483648<a)return false;for(var b=1;4>=b;b*=2){var e=d*(1+.2/b);e=Math.min(e,a+100663296);a:{e=(Math.min(2147483648,65536*Math.ceil(Math.max(a,e)/65536))-r.buffer.byteLength+65535)/65536|0;try{r.grow(e);K();var f=1;break a}catch(g){}f=
14
+ void 0;}if(f)return true}return false},e:(a,d)=>{var b=0,e=0,f;for(f of pa()){var g=d+b;I[a+e>>2]=g;b+=U(f,g,Infinity)+1;e+=4;}return 0},f:(a,d)=>{var b=pa();I[a>>2]=b.length;a=0;for(var e of b)a+=X(e)+1;I[d>>2]=a;return 0},d:()=>52,o:function(){return 70},c:(a,d,b,e)=>{for(var f=0,g=0;g<b;g++){var h=I[d>>2],m=I[d+4>>2];d+=8;for(var x=0;x<m;x++){var k=a,l=G[h+x],p=qa[k];0===l||10===l?(k=1===k?y:z,l=ja(p,0),l=ia.decode(p.buffer?p.subarray(0,l):new Uint8Array(p.slice(0,l))),k(l),p.length=0):p.push(l);}f+=m;}I[e>>
15
+ 2]=f;return 0},a:r,r:na,s:function(a,d,b,e,f){return c.callbacks.callFunction(void 0,a,d,b,e,f)},i:function(a){return c.callbacks.shouldInterrupt(void 0,a)},h:function(a,d,b){b=R(b);return c.callbacks.loadModuleSource(void 0,a,d,b)},g:function(a,d,b,e){b=R(b);e=R(e);return c.callbacks.normalizeModule(void 0,a,d,b,e)},t:function(a,d){c.callbacks.freeHostRef(void 0,a,d);}},Z;
16
+ Z=await (async function(){function a(b){b=Z=b.exports;c._malloc=b.v;c._QTS_Throw=b.w;c._QTS_NewError=b.x;c._QTS_RuntimeSetMemoryLimit=b.y;c._QTS_RuntimeComputeMemoryUsage=b.z;c._QTS_RuntimeDumpMemoryUsage=b.A;c._QTS_RecoverableLeakCheck=b.B;c._QTS_BuildIsSanitizeLeak=b.C;c._QTS_RuntimeSetMaxStackSize=b.D;c._QTS_GetUndefined=b.E;c._QTS_GetNull=b.F;c._QTS_GetFalse=b.G;c._QTS_GetTrue=b.H;c._QTS_NewHostRef=b.I;c._QTS_GetHostRefId=b.J;c._QTS_NewRuntime=b.K;c._QTS_FreeRuntime=b.L;c._free=b.M;
17
+ c._QTS_NewContext=b.N;c._QTS_FreeContext=b.O;c._QTS_FreeValuePointer=b.P;c._QTS_FreeValuePointerRuntime=b.Q;c._QTS_FreeVoidPointer=b.R;c._QTS_FreeCString=b.S;c._QTS_DupValuePointer=b.T;c._QTS_NewObject=b.U;c._QTS_NewObjectProto=b.V;c._QTS_NewArray=b.W;c._QTS_NewArrayBuffer=b.X;c._QTS_NewFloat64=b.Y;c._QTS_GetFloat64=b.Z;c._QTS_NewString=b._;c._QTS_GetString=b.$;c._QTS_GetArrayBuffer=b.aa;c._QTS_GetArrayBufferLength=b.ba;c._QTS_NewSymbol=b.ca;c._QTS_GetSymbolDescriptionOrKey=b.da;c._QTS_IsGlobalSymbol=
18
+ b.ea;c._QTS_IsJobPending=b.fa;c._QTS_ExecutePendingJob=b.ga;c._QTS_GetProp=b.ha;c._QTS_GetPropNumber=b.ia;c._QTS_SetProp=b.ja;c._QTS_DefineProp=b.ka;c._QTS_GetOwnPropertyNames=b.la;c._QTS_Call=b.ma;c._QTS_ResolveException=b.na;c._QTS_Dump=b.oa;c._QTS_Eval=b.pa;c._QTS_GetModuleNamespace=b.qa;c._QTS_Typeof=b.ra;c._QTS_GetLength=b.sa;c._QTS_IsEqual=b.ta;c._QTS_GetGlobalObject=b.ua;c._QTS_NewPromiseCapability=b.va;c._QTS_PromiseState=b.wa;c._QTS_PromiseResult=b.xa;c._QTS_TestStringArg=b.ya;c._QTS_GetDebugLogEnabled=
19
+ b.za;c._QTS_SetDebugLogEnabled=b.Aa;c._QTS_BuildIsDebug=b.Ba;c._QTS_BuildIsAsyncify=b.Ca;c._QTS_NewFunction=b.Da;c._QTS_ArgvGetJSValueConstPointer=b.Ea;c._QTS_RuntimeEnableInterruptHandler=b.Fa;c._QTS_RuntimeDisableInterruptHandler=b.Ga;c._QTS_RuntimeEnableModuleLoader=b.Ha;c._QTS_RuntimeDisableModuleLoader=b.Ia;c._QTS_bjson_encode=b.Ja;c._QTS_bjson_decode=b.Ka;ua=b.La;sa=b.Ma;Y=b.Na;ra=b.Oa;return Z}var d={a:va};if(c.instantiateWasm)return new Promise(b=>{c.instantiateWasm(d,(e,f)=>{b(a(e));});});
20
+ M??=c.locateFile?c.locateFile?c.locateFile("emscripten-module.wasm",u):u+"emscripten-module.wasm":(new URL(new URL('assets/emscripten-module-uFzwHH0Y.wasm', import.meta.url).href, import.meta.url)).href;return a((await ea(d)).instance)}());
21
+ (function(){function a(){c.calledRun=true;if(!B){J=true;Z.u();D?.(c);c.onRuntimeInitialized?.();if(c.postRun)for("function"==typeof c.postRun&&(c.postRun=[c.postRun]);c.postRun.length;){var d=c.postRun.shift();P.push(d);}O(P);}}if(c.preRun)for("function"==typeof c.preRun&&(c.preRun=[c.preRun]);c.preRun.length;)ha();O(fa);c.setStatus?(c.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>c.setStatus(""),1);a();},1)):a();})();J?moduleRtn=c:moduleRtn=new Promise((a,d)=>{D=a;E=d;});
22
+ return moduleRtn}
23
+
24
+ export { QuickJSRaw as default };
@@ -0,0 +1,3 @@
1
+ var QuickJSFFI=class{constructor(module){this.module=module;this.DEBUG=false;this.QTS_Throw=this.module.cwrap("QTS_Throw","number",["number","number"]);this.QTS_NewError=this.module.cwrap("QTS_NewError","number",["number"]);this.QTS_RuntimeSetMemoryLimit=this.module.cwrap("QTS_RuntimeSetMemoryLimit",null,["number","number"]);this.QTS_RuntimeComputeMemoryUsage=this.module.cwrap("QTS_RuntimeComputeMemoryUsage","number",["number","number"]);this.QTS_RuntimeDumpMemoryUsage=this.module.cwrap("QTS_RuntimeDumpMemoryUsage","number",["number"]);this.QTS_RecoverableLeakCheck=this.module.cwrap("QTS_RecoverableLeakCheck","number",[]);this.QTS_BuildIsSanitizeLeak=this.module.cwrap("QTS_BuildIsSanitizeLeak","number",[]);this.QTS_RuntimeSetMaxStackSize=this.module.cwrap("QTS_RuntimeSetMaxStackSize",null,["number","number"]);this.QTS_GetUndefined=this.module.cwrap("QTS_GetUndefined","number",[]);this.QTS_GetNull=this.module.cwrap("QTS_GetNull","number",[]);this.QTS_GetFalse=this.module.cwrap("QTS_GetFalse","number",[]);this.QTS_GetTrue=this.module.cwrap("QTS_GetTrue","number",[]);this.QTS_NewHostRef=this.module.cwrap("QTS_NewHostRef","number",["number","number"]);this.QTS_GetHostRefId=this.module.cwrap("QTS_GetHostRefId","number",["number"]);this.QTS_NewRuntime=this.module.cwrap("QTS_NewRuntime","number",[]);this.QTS_FreeRuntime=this.module.cwrap("QTS_FreeRuntime",null,["number"]);this.QTS_NewContext=this.module.cwrap("QTS_NewContext","number",["number","number"]);this.QTS_FreeContext=this.module.cwrap("QTS_FreeContext",null,["number"]);this.QTS_FreeValuePointer=this.module.cwrap("QTS_FreeValuePointer",null,["number","number"]);this.QTS_FreeValuePointerRuntime=this.module.cwrap("QTS_FreeValuePointerRuntime",null,["number","number"]);this.QTS_FreeVoidPointer=this.module.cwrap("QTS_FreeVoidPointer",null,["number","number"]);this.QTS_FreeCString=this.module.cwrap("QTS_FreeCString",null,["number","number"]);this.QTS_DupValuePointer=this.module.cwrap("QTS_DupValuePointer","number",["number","number"]);this.QTS_NewObject=this.module.cwrap("QTS_NewObject","number",["number"]);this.QTS_NewObjectProto=this.module.cwrap("QTS_NewObjectProto","number",["number","number"]);this.QTS_NewArray=this.module.cwrap("QTS_NewArray","number",["number"]);this.QTS_NewArrayBuffer=this.module.cwrap("QTS_NewArrayBuffer","number",["number","number","number"]);this.QTS_NewFloat64=this.module.cwrap("QTS_NewFloat64","number",["number","number"]);this.QTS_GetFloat64=this.module.cwrap("QTS_GetFloat64","number",["number","number"]);this.QTS_NewString=this.module.cwrap("QTS_NewString","number",["number","number"]);this.QTS_GetString=this.module.cwrap("QTS_GetString","number",["number","number"]);this.QTS_GetArrayBuffer=this.module.cwrap("QTS_GetArrayBuffer","number",["number","number"]);this.QTS_GetArrayBufferLength=this.module.cwrap("QTS_GetArrayBufferLength","number",["number","number"]);this.QTS_NewSymbol=this.module.cwrap("QTS_NewSymbol","number",["number","number","number"]);this.QTS_GetSymbolDescriptionOrKey=this.module.cwrap("QTS_GetSymbolDescriptionOrKey","number",["number","number"]);this.QTS_IsGlobalSymbol=this.module.cwrap("QTS_IsGlobalSymbol","number",["number","number"]);this.QTS_IsJobPending=this.module.cwrap("QTS_IsJobPending","number",["number"]);this.QTS_ExecutePendingJob=this.module.cwrap("QTS_ExecutePendingJob","number",["number","number","number"]);this.QTS_GetProp=this.module.cwrap("QTS_GetProp","number",["number","number","number"]);this.QTS_GetPropNumber=this.module.cwrap("QTS_GetPropNumber","number",["number","number","number"]);this.QTS_SetProp=this.module.cwrap("QTS_SetProp",null,["number","number","number","number"]);this.QTS_DefineProp=this.module.cwrap("QTS_DefineProp",null,["number","number","number","number","number","number","boolean","boolean","boolean"]);this.QTS_GetOwnPropertyNames=this.module.cwrap("QTS_GetOwnPropertyNames","number",["number","number","number","number","number"]);this.QTS_Call=this.module.cwrap("QTS_Call","number",["number","number","number","number","number"]);this.QTS_ResolveException=this.module.cwrap("QTS_ResolveException","number",["number","number"]);this.QTS_Dump=this.module.cwrap("QTS_Dump","number",["number","number"]);this.QTS_Eval=this.module.cwrap("QTS_Eval","number",["number","number","number","string","number","number"]);this.QTS_GetModuleNamespace=this.module.cwrap("QTS_GetModuleNamespace","number",["number","number"]);this.QTS_Typeof=this.module.cwrap("QTS_Typeof","number",["number","number"]);this.QTS_GetLength=this.module.cwrap("QTS_GetLength","number",["number","number","number"]);this.QTS_IsEqual=this.module.cwrap("QTS_IsEqual","number",["number","number","number","number"]);this.QTS_GetGlobalObject=this.module.cwrap("QTS_GetGlobalObject","number",["number"]);this.QTS_NewPromiseCapability=this.module.cwrap("QTS_NewPromiseCapability","number",["number","number"]);this.QTS_PromiseState=this.module.cwrap("QTS_PromiseState","number",["number","number"]);this.QTS_PromiseResult=this.module.cwrap("QTS_PromiseResult","number",["number","number"]);this.QTS_TestStringArg=this.module.cwrap("QTS_TestStringArg",null,["string"]);this.QTS_GetDebugLogEnabled=this.module.cwrap("QTS_GetDebugLogEnabled","number",["number"]);this.QTS_SetDebugLogEnabled=this.module.cwrap("QTS_SetDebugLogEnabled",null,["number","number"]);this.QTS_BuildIsDebug=this.module.cwrap("QTS_BuildIsDebug","number",[]);this.QTS_BuildIsAsyncify=this.module.cwrap("QTS_BuildIsAsyncify","number",[]);this.QTS_NewFunction=this.module.cwrap("QTS_NewFunction","number",["number","string","number","boolean","number"]);this.QTS_ArgvGetJSValueConstPointer=this.module.cwrap("QTS_ArgvGetJSValueConstPointer","number",["number","number"]);this.QTS_RuntimeEnableInterruptHandler=this.module.cwrap("QTS_RuntimeEnableInterruptHandler",null,["number"]);this.QTS_RuntimeDisableInterruptHandler=this.module.cwrap("QTS_RuntimeDisableInterruptHandler",null,["number"]);this.QTS_RuntimeEnableModuleLoader=this.module.cwrap("QTS_RuntimeEnableModuleLoader",null,["number","number"]);this.QTS_RuntimeDisableModuleLoader=this.module.cwrap("QTS_RuntimeDisableModuleLoader",null,["number"]);this.QTS_bjson_encode=this.module.cwrap("QTS_bjson_encode","number",["number","number"]);this.QTS_bjson_decode=this.module.cwrap("QTS_bjson_decode","number",["number","number"]);}};
2
+
3
+ export { QuickJSFFI };
@@ -0,0 +1,10 @@
1
+ var EvalFlags={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},IntrinsicsFlags={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},JSPromiseStateEnum={Pending:0,Fulfilled:1,Rejected:2},GetOwnPropertyNamesFlags={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},IsEqualOp={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2};
2
+
3
+ var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true});};function debugLog(...args){}var errors_exports={};__export(errors_exports,{QuickJSAsyncifyError:()=>QuickJSAsyncifyError,QuickJSAsyncifySuspended:()=>QuickJSAsyncifySuspended,QuickJSEmptyGetOwnPropertyNames:()=>QuickJSEmptyGetOwnPropertyNames,QuickJSEmscriptenModuleError:()=>QuickJSEmscriptenModuleError,QuickJSHostRefInvalid:()=>QuickJSHostRefInvalid,QuickJSHostRefRangeExceeded:()=>QuickJSHostRefRangeExceeded,QuickJSMemoryLeakDetected:()=>QuickJSMemoryLeakDetected,QuickJSNotImplemented:()=>QuickJSNotImplemented,QuickJSPromisePending:()=>QuickJSPromisePending,QuickJSUnknownIntrinsic:()=>QuickJSUnknownIntrinsic,QuickJSUnwrapError:()=>QuickJSUnwrapError,QuickJSUseAfterFree:()=>QuickJSUseAfterFree,QuickJSWrongOwner:()=>QuickJSWrongOwner});var QuickJSUnwrapError=class extends Error{constructor(cause,context){let message=typeof cause=="object"&&cause&&"message"in cause?String(cause.message):String(cause);super(message);this.cause=cause;this.context=context;this.name="QuickJSUnwrapError";}},QuickJSWrongOwner=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner";}},QuickJSUseAfterFree=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree";}},QuickJSNotImplemented=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented";}},QuickJSAsyncifyError=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError";}},QuickJSAsyncifySuspended=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended";}},QuickJSMemoryLeakDetected=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected";}},QuickJSEmscriptenModuleError=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError";}},QuickJSUnknownIntrinsic=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic";}},QuickJSPromisePending=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending";}},QuickJSEmptyGetOwnPropertyNames=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames";}},QuickJSHostRefRangeExceeded=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded";}},QuickJSHostRefInvalid=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid";}};function*awaitYield(value){return yield value}function awaitYieldOf(generator){return awaitYield(awaitEachYieldedPromise(generator))}var AwaitYield=awaitYield;AwaitYield.of=awaitYieldOf;function maybeAsyncFn(that,fn){return (...args)=>{let generator=fn.call(that,AwaitYield,...args);return awaitEachYieldedPromise(generator)}}function maybeAsync(that,startGenerator){let generator=startGenerator.call(that,AwaitYield);return awaitEachYieldedPromise(generator)}function awaitEachYieldedPromise(gen){function handleNextStep(step){return step.done?step.value:step.value instanceof Promise?step.value.then(value=>handleNextStep(gen.next(value)),error=>handleNextStep(gen.throw(error))):handleNextStep(gen.next(step.value))}return handleNextStep(gen.next())}var UsingDisposable=class{[Symbol.dispose](){return this.dispose()}},SymbolDispose=Symbol.dispose??Symbol.for("Symbol.dispose"),prototypeAsAny=UsingDisposable.prototype;prototypeAsAny[SymbolDispose]||(prototypeAsAny[SymbolDispose]=function(){return this.dispose()});var Lifetime=class _Lifetime extends UsingDisposable{constructor(_value,copier,disposer,_owner){super();this._value=_value;this.copier=copier;this.disposer=disposer;this._owner=_owner;this._alive=true;this._constructorStack=void 0;}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return !!this.copier}dup(){if(this.assertAlive(),!this.copier)throw new Error("Non-dupable lifetime");return new _Lifetime(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(map){this.assertAlive();let result=map(this);return this.dispose(),result}map(map){return this.assertAlive(),map(this)}tap(fn){return fn(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=false;}assertAlive(){if(!this.alive)throw this._constructorStack?new QuickJSUseAfterFree(`Lifetime not alive
4
+ ${this._constructorStack}
5
+ Lifetime used`):new QuickJSUseAfterFree("Lifetime not alive")}},StaticLifetime=class extends Lifetime{constructor(value,owner){super(value,void 0,void 0,owner);}get dupable(){return true}dup(){return this}dispose(){}},WeakLifetime=class extends Lifetime{constructor(value,copier,disposer,owner){super(value,copier,disposer,owner);}dispose(){this._alive=false;}};function scopeFinally(scope,blockError){let disposeError;try{scope.dispose();}catch(error){disposeError=error;}if(blockError&&disposeError)throw Object.assign(blockError,{message:`${blockError.message}
6
+ Then, failed to dispose scope: ${disposeError.message}`,disposeError}),blockError;if(blockError||disposeError)throw blockError||disposeError}var Scope=class _Scope extends UsingDisposable{constructor(){super(...arguments);this._disposables=new Lifetime(new Set);this.manage=lifetime=>(this._disposables.value.add(lifetime),lifetime);}static withScope(block){let scope=new _Scope,blockError;try{return block(scope)}catch(error){throw blockError=error,error}finally{scopeFinally(scope,blockError);}}static withScopeMaybeAsync(_this,block){return maybeAsync(void 0,function*(awaited){let scope=new _Scope,blockError;try{return yield*awaited.of(block.call(_this,awaited,scope))}catch(error){throw blockError=error,error}finally{scopeFinally(scope,blockError);}})}static async withScopeAsync(block){let scope=new _Scope,blockError;try{return await block(scope)}catch(error){throw blockError=error,error}finally{scopeFinally(scope,blockError);}}get alive(){return this._disposables.alive}dispose(){let lifetimes=Array.from(this._disposables.value.values()).reverse();for(let lifetime of lifetimes)lifetime.alive&&lifetime.dispose();this._disposables.dispose();}};function createDisposableArray(items){let array=items?Array.from(items):[];function disposeAlive(){return array.forEach(disposable=>disposable.alive?disposable.dispose():void 0)}function someIsAlive(){return array.some(disposable=>disposable.alive)}return Object.defineProperty(array,SymbolDispose,{configurable:true,enumerable:false,value:disposeAlive}),Object.defineProperty(array,"dispose",{configurable:true,enumerable:false,value:disposeAlive}),Object.defineProperty(array,"alive",{configurable:true,enumerable:false,get:someIsAlive}),array}function isDisposable(value){return !!(value&&(typeof value=="object"||typeof value=="function")&&"alive"in value&&typeof value.alive=="boolean"&&"dispose"in value&&typeof value.dispose=="function")}var AbstractDisposableResult=class _AbstractDisposableResult extends UsingDisposable{static success(value){return new DisposableSuccess(value)}static fail(error,onUnwrap){return new DisposableFail(error,onUnwrap)}static is(result){return result instanceof _AbstractDisposableResult}},DisposableSuccess=class extends AbstractDisposableResult{constructor(value){super();this.value=value;}get alive(){return isDisposable(this.value)?this.value.alive:true}dispose(){isDisposable(this.value)&&this.value.dispose();}unwrap(){return this.value}unwrapOr(_fallback){return this.value}},DisposableFail=class extends AbstractDisposableResult{constructor(error,onUnwrap){super();this.error=error;this.onUnwrap=onUnwrap;}get alive(){return isDisposable(this.error)?this.error.alive:true}dispose(){isDisposable(this.error)&&this.error.dispose();}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(fallback){return fallback}},DisposableResult=AbstractDisposableResult;var QuickJSDeferredPromise=class extends UsingDisposable{constructor(args){super();this.resolve=value=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,value||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled());};this.reject=value=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,value||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled());};this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers();};this.context=args.context,this.owner=args.context.runtime,this.handle=args.promiseHandle,this.settled=new Promise(resolve=>{this.onSettled=resolve;}),this.resolveHandle=args.resolveHandle,this.rejectHandle=args.rejectHandle;}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose();}};var ModuleMemory=class{constructor(module){this.module=module;}toPointerArray(handleArray){let typedArray=new Int32Array(handleArray.map(handle=>handle.value)),numBytes=typedArray.length*typedArray.BYTES_PER_ELEMENT,ptr=this.module._malloc(numBytes);return new Uint8Array(this.module.HEAPU8.buffer,ptr,numBytes).set(new Uint8Array(typedArray.buffer)),new Lifetime(ptr,void 0,ptr2=>this.module._free(ptr2))}newTypedArray(kind,length){let zeros=new kind(new Array(length).fill(0)),numBytes=zeros.length*zeros.BYTES_PER_ELEMENT,ptr=this.module._malloc(numBytes),typedArray=new kind(this.module.HEAPU8.buffer,ptr,length);return typedArray.set(zeros),new Lifetime({typedArray,ptr},void 0,value=>this.module._free(value.ptr))}newMutablePointerArray(length){return this.newTypedArray(Int32Array,length)}newHeapCharPointer(string){let strlen=this.module.lengthBytesUTF8(string),dataBytes=strlen+1,ptr=this.module._malloc(dataBytes);return this.module.stringToUTF8(string,ptr,dataBytes),new Lifetime({ptr,strlen},void 0,value=>this.module._free(value.ptr))}newHeapBufferPointer(buffer){let numBytes=buffer.byteLength,ptr=this.module._malloc(numBytes);return this.module.HEAPU8.set(buffer,ptr),new Lifetime({pointer:ptr,numBytes},void 0,value=>this.module._free(value.pointer))}consumeHeapCharPointer(ptr){let str=this.module.UTF8ToString(ptr);return this.module._free(ptr),str}};function intrinsicsToFlags(intrinsics){if(!intrinsics)return 0;let result=0;for(let[maybeIntrinsicName,enabled]of Object.entries(intrinsics)){if(!(maybeIntrinsicName in IntrinsicsFlags))throw new QuickJSUnknownIntrinsic(maybeIntrinsicName);enabled&&(result|=IntrinsicsFlags[maybeIntrinsicName]);}return result}function evalOptionsToFlags(evalOptions){if(typeof evalOptions=="number")return evalOptions;if(evalOptions===void 0)return 0;let{type,strict,strip,compileOnly,backtraceBarrier}=evalOptions,flags=0;return type==="global"&&(flags|=EvalFlags.JS_EVAL_TYPE_GLOBAL),type==="module"&&(flags|=EvalFlags.JS_EVAL_TYPE_MODULE),strict&&(flags|=EvalFlags.JS_EVAL_FLAG_STRICT),strip&&(flags|=EvalFlags.JS_EVAL_FLAG_STRIP),compileOnly&&(flags|=EvalFlags.JS_EVAL_FLAG_COMPILE_ONLY),backtraceBarrier&&(flags|=EvalFlags.JS_EVAL_FLAG_BACKTRACE_BARRIER),flags}function getOwnPropertyNamesOptionsToFlags(options){if(typeof options=="number")return options;if(options===void 0)return 0;let{strings:includeStrings,symbols:includeSymbols,quickjsPrivate:includePrivate,onlyEnumerable,numbers:includeNumbers,numbersAsStrings}=options,flags=0;return includeStrings&&(flags|=GetOwnPropertyNamesFlags.JS_GPN_STRING_MASK),includeSymbols&&(flags|=GetOwnPropertyNamesFlags.JS_GPN_SYMBOL_MASK),includePrivate&&(flags|=GetOwnPropertyNamesFlags.JS_GPN_PRIVATE_MASK),onlyEnumerable&&(flags|=GetOwnPropertyNamesFlags.JS_GPN_ENUM_ONLY),includeNumbers&&(flags|=GetOwnPropertyNamesFlags.QTS_GPN_NUMBER_MASK),numbersAsStrings&&(flags|=GetOwnPropertyNamesFlags.QTS_STANDARD_COMPLIANT_NUMBER),flags}function concat(...values){let result=[];for(let value of values)value!==void 0&&(result=result.concat(value));return result}var QuickJSIterator=class extends UsingDisposable{constructor(handle,context){super();this.handle=handle;this.context=context;this._isDone=false;this.owner=context.runtime;}[Symbol.iterator](){return this}next(value){if(!this.alive||this._isDone)return {done:true,value:void 0};let nextMethod=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(nextMethod,value)}return(value){if(!this.alive)return {done:true,value:void 0};let returnMethod=this.context.getProp(this.handle,"return");if(returnMethod===this.context.undefined&&value===void 0)return this.dispose(),{done:true,value:void 0};let result=this.callIteratorMethod(returnMethod,value);return returnMethod.dispose(),this.dispose(),result}throw(e){if(!this.alive)return {done:true,value:void 0};let errorHandle=e instanceof Lifetime?e:this.context.newError(e),throwMethod=this.context.getProp(this.handle,"throw"),result=this.callIteratorMethod(throwMethod,e);return errorHandle.alive&&errorHandle.dispose(),throwMethod.dispose(),this.dispose(),result}get alive(){return this.handle.alive}dispose(){this._isDone=true,this.handle.dispose(),this._next?.dispose();}callIteratorMethod(method,input){let callResult=input?this.context.callFunction(method,this.handle,input):this.context.callFunction(method,this.handle);if(callResult.error)return this.dispose(),{value:callResult};let done=this.context.getProp(callResult.value,"done").consume(v=>this.context.dump(v)),value=this.context.getProp(callResult.value,"value");return callResult.value.dispose(),done&&this.dispose(),{value:DisposableResult.success(value),done}}};var INT32_MIN=-2147483648,INT32_MAX=2147483647,INVALID_HOST_REF_ID=0;function getGroupId(id){return id>>8}var HostRefMap=class{constructor(){this.nextId=INT32_MIN;this.freelist=[];this.groups=new Map;}put(value){let id=this.allocateId(),groupId=getGroupId(id),group=this.groups.get(groupId);return group||(group=new Map,this.groups.set(groupId,group)),group.set(id,value),id}get(id){if(id===INVALID_HOST_REF_ID)throw new QuickJSHostRefInvalid("no host reference id defined");let groupId=getGroupId(id),group=this.groups.get(groupId);if(!group)throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);let value=group.get(id);if(!value)throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);return value}delete(id){if(id===INVALID_HOST_REF_ID)throw new QuickJSHostRefInvalid("no host reference id defined");let groupId=getGroupId(id),group=this.groups.get(groupId);if(!group)throw new QuickJSHostRefInvalid(`host reference id ${id} is not defined`);group.delete(id),group.size===0&&this.groups.delete(groupId),this.freelist.push(id);}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===INVALID_HOST_REF_ID&&this.nextId++,this.nextId>INT32_MAX)throw new QuickJSHostRefRangeExceeded(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${INT32_MAX-INT32_MIN}`);return this.nextId++}},HostRef=class extends UsingDisposable{constructor(runtime,handle,id){if(id===INVALID_HOST_REF_ID)throw new QuickJSHostRefInvalid("cannot create HostRef with undefined id");super();this.runtime=runtime;this.handle=handle;this.id=id;}get alive(){return this.handle.alive}dispose(){this.handle.dispose();}get value(){return this.runtime.hostRefs.get(this.id)}};var ContextMemory=class extends ModuleMemory{constructor(args){super(args.module);this.scope=new Scope;this.copyJSValue=ptr=>this.ffi.QTS_DupValuePointer(this.ctx.value,ptr);this.freeJSValue=ptr=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,ptr);};args.ownedLifetimes?.forEach(lifetime=>this.scope.manage(lifetime)),this.owner=args.owner,this.module=args.module,this.ffi=args.ffi,this.rt=args.rt,this.ctx=this.scope.manage(args.ctx);}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(lifetime){return this.scope.manage(lifetime)}consumeJSCharPointer(ptr){let str=this.module.UTF8ToString(ptr);return this.ffi.QTS_FreeCString(this.ctx.value,ptr),str}heapValueHandle(ptr,extraDispose){let dispose=extraDispose?val=>{extraDispose(),this.freeJSValue(val);}:this.freeJSValue;return new Lifetime(ptr,this.copyJSValue,dispose,this.owner)}staticHeapValueHandle(ptr){return this.manage(this.heapValueHandle(ptr)),new StaticLifetime(ptr,this.owner)}},QuickJSContext=class extends UsingDisposable{constructor(args){super();this._undefined=void 0;this._null=void 0;this._false=void 0;this._true=void 0;this._global=void 0;this._BigInt=void 0;this._Symbol=void 0;this._SymbolIterator=void 0;this._SymbolAsyncIterator=void 0;this.cToHostCallbacks={callFunction:(ctx,this_ptr,argc,argv,fn_id)=>{if(ctx!==this.ctx.value)throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");let fn=this.getFunction(fn_id);return Scope.withScopeMaybeAsync(this,function*(awaited,scope){let thisHandle=scope.manage(new WeakLifetime(this_ptr,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),argHandles=new Array(argc);for(let i=0;i<argc;i++){let ptr=this.ffi.QTS_ArgvGetJSValueConstPointer(argv,i);argHandles[i]=scope.manage(new WeakLifetime(ptr,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime));}try{let result=yield*awaited(fn.apply(thisHandle,argHandles));if(result){if("error"in result&&result.error)throw this.runtime.debugLog("throw error",result.error),result.error;let handle=scope.manage(result instanceof Lifetime?result:result.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,handle.value)}return 0}catch(error){return this.errorToHandle(error).consume(errorHandle=>this.ffi.QTS_Throw(this.ctx.value,errorHandle.value))}})}};this.runtime=args.runtime,this.module=args.module,this.ffi=args.ffi,this.rt=args.rt,this.ctx=args.ctx,this.memory=new ContextMemory({...args,owner:this.runtime}),args.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1));}get alive(){return this.memory.alive}dispose(){this.memory.dispose();}get undefined(){if(this._undefined)return this._undefined;let ptr=this.ffi.QTS_GetUndefined();return this._undefined=new StaticLifetime(ptr)}get null(){if(this._null)return this._null;let ptr=this.ffi.QTS_GetNull();return this._null=new StaticLifetime(ptr)}get true(){if(this._true)return this._true;let ptr=this.ffi.QTS_GetTrue();return this._true=new StaticLifetime(ptr)}get false(){if(this._false)return this._false;let ptr=this.ffi.QTS_GetFalse();return this._false=new StaticLifetime(ptr)}get global(){if(this._global)return this._global;let ptr=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(ptr),this._global}newNumber(num){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,num))}newString(str){let ptr=this.memory.newHeapCharPointer(str).consume(charHandle=>this.ffi.QTS_NewString(this.ctx.value,charHandle.value.ptr));return this.memory.heapValueHandle(ptr)}newUniqueSymbol(description){let key=(typeof description=="symbol"?description.description:description)??"",ptr=this.memory.newHeapCharPointer(key).consume(charHandle=>this.ffi.QTS_NewSymbol(this.ctx.value,charHandle.value.ptr,0));return this.memory.heapValueHandle(ptr)}newSymbolFor(key){let description=(typeof key=="symbol"?key.description:key)??"",ptr=this.memory.newHeapCharPointer(description).consume(charHandle=>this.ffi.QTS_NewSymbol(this.ctx.value,charHandle.value.ptr,1));return this.memory.heapValueHandle(ptr)}getWellKnownSymbol(name){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,name)}newBigInt(num){if(!this._BigInt){let bigIntHandle2=this.getProp(this.global,"BigInt");this.memory.manage(bigIntHandle2),this._BigInt=new StaticLifetime(bigIntHandle2.value,this.runtime);}let bigIntHandle=this._BigInt,asString=String(num);return this.newString(asString).consume(handle=>this.unwrapResult(this.callFunction(bigIntHandle,this.undefined,handle)))}newObject(prototype){prototype&&this.runtime.assertOwned(prototype);let ptr=prototype?this.ffi.QTS_NewObjectProto(this.ctx.value,prototype.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(ptr)}newArray(){let ptr=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(ptr)}newArrayBuffer(buffer){let array=new Uint8Array(buffer),handle=this.memory.newHeapBufferPointer(array),ptr=this.ffi.QTS_NewArrayBuffer(this.ctx.value,handle.value.pointer,array.length);return this.memory.heapValueHandle(ptr)}newPromise(value){let deferredPromise=Scope.withScope(scope=>{let mutablePointerArray=scope.manage(this.memory.newMutablePointerArray(2)),promisePtr=this.ffi.QTS_NewPromiseCapability(this.ctx.value,mutablePointerArray.value.ptr),promiseHandle=this.memory.heapValueHandle(promisePtr),[resolveHandle,rejectHandle]=Array.from(mutablePointerArray.value.typedArray).map(jsvaluePtr=>this.memory.heapValueHandle(jsvaluePtr));return new QuickJSDeferredPromise({context:this,promiseHandle,resolveHandle,rejectHandle})});return value&&typeof value=="function"&&(value=new Promise(value)),value&&Promise.resolve(value).then(deferredPromise.resolve,error=>error instanceof Lifetime?deferredPromise.reject(error):this.newError(error).consume(deferredPromise.reject)),deferredPromise}newFunction(nameOrFn,maybeFn){let fn=typeof nameOrFn=="function"?nameOrFn:maybeFn;if(!fn)throw new TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof nameOrFn=="string"?nameOrFn:void 0,length:fn.length,isConstructor:false,fn})}newConstructorFunction(nameOrFn,maybeFn){let fn=typeof nameOrFn=="function"?nameOrFn:maybeFn;if(!fn)throw new TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof nameOrFn=="string"?nameOrFn:void 0,length:fn.length,isConstructor:true,fn})}newFunctionWithOptions(args){let{name,length,isConstructor,fn}=args,refId=this.runtime.hostRefs.put(fn);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,name??"",length,isConstructor,refId))}catch(error){throw this.runtime.hostRefs.delete(refId),error}}newError(error){let errorHandle=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return error&&typeof error=="object"?(error.name!==void 0&&this.newString(error.name).consume(handle=>this.setProp(errorHandle,"name",handle)),error.message!==void 0&&this.newString(error.message).consume(handle=>this.setProp(errorHandle,"message",handle))):typeof error=="string"?this.newString(error).consume(handle=>this.setProp(errorHandle,"message",handle)):error!==void 0&&this.newString(String(error)).consume(handle=>this.setProp(errorHandle,"message",handle)),errorHandle}newHostRef(value){let id=this.runtime.hostRefs.put(value);try{let handle=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,id));return new HostRef(this.runtime,handle,id)}catch(error){throw this.runtime.hostRefs.delete(id),error}}toHostRef(handle){let id=this.ffi.QTS_GetHostRefId(handle.value);if(id!==0)return this.runtime.hostRefs.get(id),new HostRef(this.runtime,handle.dup(),id)}unwrapHostRef(handle){let id=this.ffi.QTS_GetHostRefId(handle.value);if(id===0)throw new QuickJSHostRefInvalid("handle is not a HostRef");return this.runtime.hostRefs.get(id)}typeof(handle){return this.runtime.assertOwned(handle),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,handle.value))}getNumber(handle){return this.runtime.assertOwned(handle),this.ffi.QTS_GetFloat64(this.ctx.value,handle.value)}getString(handle){return this.runtime.assertOwned(handle),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,handle.value))}getSymbol(handle){this.runtime.assertOwned(handle);let key=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,handle.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,handle.value)?Symbol.for(key):Symbol(key)}getBigInt(handle){this.runtime.assertOwned(handle);let asString=this.getString(handle);return BigInt(asString)}getArrayBuffer(handle){this.runtime.assertOwned(handle);let len=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,handle.value),ptr=this.ffi.QTS_GetArrayBuffer(this.ctx.value,handle.value);if(!ptr)throw new Error("Couldn't allocate memory to get ArrayBuffer");return new Lifetime(this.module.HEAPU8.subarray(ptr,ptr+len),void 0,()=>this.module._free(ptr))}getPromiseState(handle){this.runtime.assertOwned(handle);let state=this.ffi.QTS_PromiseState(this.ctx.value,handle.value);if(state<0)return {type:"fulfilled",value:handle,notAPromise:true};if(state===JSPromiseStateEnum.Pending)return {type:"pending",get error(){return new QuickJSPromisePending("Cannot unwrap a pending promise")}};let ptr=this.ffi.QTS_PromiseResult(this.ctx.value,handle.value),result=this.memory.heapValueHandle(ptr);if(state===JSPromiseStateEnum.Fulfilled)return {type:"fulfilled",value:result};if(state===JSPromiseStateEnum.Rejected)return {type:"rejected",error:result};throw result.dispose(),new Error(`Unknown JSPromiseStateEnum: ${state}`)}resolvePromise(promiseLikeHandle){this.runtime.assertOwned(promiseLikeHandle);let vmResolveResult=Scope.withScope(scope=>{let vmPromise=scope.manage(this.getProp(this.global,"Promise")),vmPromiseResolve=scope.manage(this.getProp(vmPromise,"resolve"));return this.callFunction(vmPromiseResolve,vmPromise,promiseLikeHandle)});return vmResolveResult.error?Promise.resolve(vmResolveResult):new Promise(resolve=>{Scope.withScope(scope=>{let resolveHandle=scope.manage(this.newFunction("resolve",value=>{resolve(this.success(value&&value.dup()));})),rejectHandle=scope.manage(this.newFunction("reject",error=>{resolve(this.fail(error&&error.dup()));})),promiseHandle=scope.manage(vmResolveResult.value),promiseThenHandle=scope.manage(this.getProp(promiseHandle,"then"));this.callFunction(promiseThenHandle,promiseHandle,resolveHandle,rejectHandle).unwrap().dispose();});})}isEqual(a,b,equalityType=IsEqualOp.IsStrictlyEqual){if(a===b)return true;this.runtime.assertOwned(a),this.runtime.assertOwned(b);let result=this.ffi.QTS_IsEqual(this.ctx.value,a.value,b.value,equalityType);if(result===-1)throw new QuickJSNotImplemented("WASM variant does not expose equality");return !!result}eq(handle,other){return this.isEqual(handle,other,IsEqualOp.IsStrictlyEqual)}sameValue(handle,other){return this.isEqual(handle,other,IsEqualOp.IsSameValue)}sameValueZero(handle,other){return this.isEqual(handle,other,IsEqualOp.IsSameValueZero)}getProp(handle,key){this.runtime.assertOwned(handle);let ptr;return typeof key=="number"&&key>=0?ptr=this.ffi.QTS_GetPropNumber(this.ctx.value,handle.value,key):ptr=this.borrowPropertyKey(key).consume(quickJSKey=>this.ffi.QTS_GetProp(this.ctx.value,handle.value,quickJSKey.value)),this.memory.heapValueHandle(ptr)}getLength(handle){if(this.runtime.assertOwned(handle),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,handle.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(handle,options={strings:true,numbersAsStrings:true}){this.runtime.assertOwned(handle),handle.value;let flags=getOwnPropertyNamesOptionsToFlags(options);if(flags===0)throw new QuickJSEmptyGetOwnPropertyNames("No options set, will return an empty array");return Scope.withScope(scope=>{let outPtr=scope.manage(this.memory.newMutablePointerArray(1)),errorPtr=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,outPtr.value.ptr,this.uint32Out.value.ptr,handle.value,flags);if(errorPtr)return this.fail(this.memory.heapValueHandle(errorPtr));let len=this.uint32Out.value.typedArray[0],ptr=outPtr.value.typedArray[0],pointerArray=new Uint32Array(this.module.HEAP8.buffer,ptr,len),handles=Array.from(pointerArray).map(ptr2=>this.memory.heapValueHandle(ptr2));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,ptr),this.success(createDisposableArray(handles))})}getIterator(iterableHandle){let SymbolIterator=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return Scope.withScope(scope=>{let methodHandle=scope.manage(this.getProp(iterableHandle,SymbolIterator)),iteratorCallResult=this.callFunction(methodHandle,iterableHandle);return iteratorCallResult.error?iteratorCallResult:this.success(new QuickJSIterator(iteratorCallResult.value,this))})}setProp(handle,key,value){this.runtime.assertOwned(handle),this.borrowPropertyKey(key).consume(quickJSKey=>this.ffi.QTS_SetProp(this.ctx.value,handle.value,quickJSKey.value,value.value));}defineProp(handle,key,descriptor){this.runtime.assertOwned(handle),Scope.withScope(scope=>{let quickJSKey=scope.manage(this.borrowPropertyKey(key)),value=descriptor.value||this.undefined,configurable=!!descriptor.configurable,enumerable=!!descriptor.enumerable,hasValue=!!descriptor.value,get=descriptor.get?scope.manage(this.newFunction(descriptor.get.name,descriptor.get)):this.undefined,set=descriptor.set?scope.manage(this.newFunction(descriptor.set.name,descriptor.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,handle.value,quickJSKey.value,value.value,get.value,set.value,configurable,enumerable,hasValue);});}callFunction(func,thisVal,...restArgs){this.runtime.assertOwned(func);let args,firstArg=restArgs[0];firstArg===void 0||Array.isArray(firstArg)?args=firstArg??[]:args=restArgs;let resultPtr=this.memory.toPointerArray(args).consume(argsArrayPtr=>this.ffi.QTS_Call(this.ctx.value,func.value,thisVal.value,args.length,argsArrayPtr.value)),errorPtr=this.ffi.QTS_ResolveException(this.ctx.value,resultPtr);return errorPtr?(this.ffi.QTS_FreeValuePointer(this.ctx.value,resultPtr),this.fail(this.memory.heapValueHandle(errorPtr))):this.success(this.memory.heapValueHandle(resultPtr))}callMethod(thisHandle,key,args=[]){return this.getProp(thisHandle,key).consume(func=>this.callFunction(func,thisHandle,args))}evalCode(code,filename="eval.js",options){let detectModule=options===void 0?1:0,flags=evalOptionsToFlags(options),resultPtr=this.memory.newHeapCharPointer(code).consume(charHandle=>this.ffi.QTS_Eval(this.ctx.value,charHandle.value.ptr,charHandle.value.strlen,filename,detectModule,flags)),errorPtr=this.ffi.QTS_ResolveException(this.ctx.value,resultPtr);return errorPtr?(this.ffi.QTS_FreeValuePointer(this.ctx.value,resultPtr),this.fail(this.memory.heapValueHandle(errorPtr))):this.success(this.memory.heapValueHandle(resultPtr))}throw(error){return this.errorToHandle(error).consume(handle=>this.ffi.QTS_Throw(this.ctx.value,handle.value))}borrowPropertyKey(key){return typeof key=="number"?this.newNumber(key):typeof key=="string"?this.newString(key):new StaticLifetime(key.value,this.runtime)}getMemory(rt){if(rt===this.rt.value)return this.memory;throw new Error("Private API. Cannot get memory from a different runtime")}dump(handle){this.runtime.assertOwned(handle);let type=this.typeof(handle);if(type==="string")return this.getString(handle);if(type==="number")return this.getNumber(handle);if(type==="bigint")return this.getBigInt(handle);if(type==="undefined")return;if(type==="symbol")return this.getSymbol(handle);let asPromiseState=this.getPromiseState(handle);if(asPromiseState.type==="fulfilled"&&!asPromiseState.notAPromise)return handle.dispose(),{type:asPromiseState.type,value:asPromiseState.value.consume(this.dump)};if(asPromiseState.type==="pending")return handle.dispose(),{type:asPromiseState.type};if(asPromiseState.type==="rejected")return handle.dispose(),{type:asPromiseState.type,error:asPromiseState.error.consume(this.dump)};let str=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,handle.value));try{return JSON.parse(str)}catch{return str}}unwrapResult(result){if(result.error){let context="context"in result.error?result.error.context:this,cause=result.error.consume(error=>this.dump(error));if(cause&&typeof cause=="object"&&typeof cause.message=="string"){let{message,name,stack,...rest}=cause,exception=new QuickJSUnwrapError(cause,context);typeof name=="string"&&(exception.name=cause.name),exception.message=message;let hostStack=exception.stack;throw typeof stack=="string"&&(exception.stack=`${name}: ${message}
7
+ ${cause.stack}Host: ${hostStack}`),Object.assign(exception,rest),exception}throw new QuickJSUnwrapError(cause)}return result.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(fn_id){let fn=this.runtime.hostRefs.get(fn_id);if(typeof fn!="function")throw new Error(`Host reference ${fn_id} is not a function`);return fn}errorToHandle(error){return error instanceof Lifetime?error:this.newError(error)}encodeBinaryJSON(handle){let ptr=this.ffi.QTS_bjson_encode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}decodeBinaryJSON(handle){let ptr=this.ffi.QTS_bjson_decode(this.ctx.value,handle.value);return this.memory.heapValueHandle(ptr)}success(value){return DisposableResult.success(value)}fail(error){return DisposableResult.fail(error,error2=>this.unwrapResult(error2))}};var QuickJSRuntime=class extends UsingDisposable{constructor(args){super();this.scope=new Scope;this.contextMap=new Map;this.hostRefs=new HostRefMap;this._debugMode=false;this.cToHostCallbacks={freeHostRef:(rt,host_ref_id)=>{if(rt!==this.rt.value)throw new Error("Runtime pointer mismatch");this.hostRefs.delete(host_ref_id);},shouldInterrupt:rt=>{if(rt!==this.rt.value)throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let fn=this.interruptHandler;if(!fn)throw new Error("QuickJSContext had no interrupt handler");return fn(this)?1:0},loadModuleSource:maybeAsyncFn(this,function*(awaited,rt,ctx,moduleName){let moduleLoader=this.moduleLoader;if(!moduleLoader)throw new Error("Runtime has no module loader");if(rt!==this.rt.value)throw new Error("Runtime pointer mismatch");let context=this.contextMap.get(ctx)??this.newContext({contextPointer:ctx});try{let result=yield*awaited(moduleLoader(moduleName,context));if(typeof result=="object"&&"error"in result&&result.error)throw this.debugLog("cToHostLoadModule: loader returned error",result.error),result.error;let moduleSource=typeof result=="string"?result:"value"in result?result.value:result;return this.memory.newHeapCharPointer(moduleSource).value.ptr}catch(error){return this.debugLog("cToHostLoadModule: caught error",error),context.throw(error),0}}),normalizeModule:maybeAsyncFn(this,function*(awaited,rt,ctx,baseModuleName,moduleNameRequest){let moduleNormalizer=this.moduleNormalizer;if(!moduleNormalizer)throw new Error("Runtime has no module normalizer");if(rt!==this.rt.value)throw new Error("Runtime pointer mismatch");let context=this.contextMap.get(ctx)??this.newContext({contextPointer:ctx});try{let result=yield*awaited(moduleNormalizer(baseModuleName,moduleNameRequest,context));if(typeof result=="object"&&"error"in result&&result.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",result.error),result.error;let name=typeof result=="string"?result:result.value;return context.getMemory(this.rt.value).newHeapCharPointer(name).value.ptr}catch(error){return this.debugLog("normalizeModule: caught error",error),context.throw(error),0}})};args.ownedLifetimes?.forEach(lifetime=>this.scope.manage(lifetime)),this.module=args.module,this.memory=new ModuleMemory(this.module),this.ffi=args.ffi,this.rt=args.rt,this.callbacks=args.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this);}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(options={}){let intrinsics=intrinsicsToFlags(options.intrinsics),ctx=new Lifetime(options.contextPointer||this.ffi.QTS_NewContext(this.rt.value,intrinsics),void 0,ctx_ptr=>{this.contextMap.delete(ctx_ptr),this.callbacks.deleteContext(ctx_ptr),this.ffi.QTS_FreeContext(ctx_ptr);}),context=new QuickJSContext({module:this.module,ctx,ffi:this.ffi,rt:this.rt,ownedLifetimes:options.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(ctx.value,context),context}setModuleLoader(moduleLoader,moduleNormalizer){this.moduleLoader=moduleLoader,this.moduleNormalizer=moduleNormalizer,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0);}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value);}hasPendingJob(){return !!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(cb){let prevInterruptHandler=this.interruptHandler;this.interruptHandler=cb,prevInterruptHandler||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value);}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0);}executePendingJobs(maxJobsToExecute=-1){let ctxPtrOut=this.memory.newMutablePointerArray(1),valuePtr=this.ffi.QTS_ExecutePendingJob(this.rt.value,maxJobsToExecute??-1,ctxPtrOut.value.ptr),ctxPtr=ctxPtrOut.value.typedArray[0];if(ctxPtrOut.dispose(),ctxPtr===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,valuePtr),DisposableResult.success(0);let context=this.contextMap.get(ctxPtr)??this.newContext({contextPointer:ctxPtr}),resultValue=context.getMemory(this.rt.value).heapValueHandle(valuePtr);if(context.typeof(resultValue)==="number"){let executedJobs=context.getNumber(resultValue);return resultValue.dispose(),DisposableResult.success(executedJobs)}else {let error=Object.assign(resultValue,{context});return DisposableResult.fail(error,error2=>context.unwrapResult(error2))}}setMemoryLimit(limitBytes){if(limitBytes<0&&limitBytes!==-1)throw new Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,limitBytes);}computeMemoryUsage(){let serviceContextMemory=this.getSystemContext().getMemory(this.rt.value);return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,serviceContextMemory.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(stackSize){if(stackSize<0)throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,stackSize);}assertOwned(handle){if(handle.owner&&handle.owner.rt!==this.rt)throw new QuickJSWrongOwner(`Handle is not owned by this runtime: ${handle.owner.rt.value} != ${this.rt.value}`)}setDebugMode(enabled){this._debugMode=enabled,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,enabled?1:0);}isDebugMode(){return this._debugMode}debugLog(...msg){this._debugMode&&console.log("quickjs-emscripten:",...msg);}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}};var QuickJSEmscriptenModuleCallbacks=class{constructor(args){this.freeHostRef=args.freeHostRef,this.callFunction=args.callFunction,this.shouldInterrupt=args.shouldInterrupt,this.loadModuleSource=args.loadModuleSource,this.normalizeModule=args.normalizeModule;}},QuickJSModuleCallbacks=class{constructor(module){this.contextCallbacks=new Map;this.runtimeCallbacks=new Map;this.suspendedCount=0;this.cToHostCallbacks=new QuickJSEmscriptenModuleCallbacks({freeHostRef:(_asyncify,rt,host_ref_id)=>{let runtimeCallbacks=this.runtimeCallbacks.get(rt);if(!runtimeCallbacks)throw new Error(`QuickJSRuntime(rt = ${rt}) not found when trying to free HostRef(id = ${host_ref_id})`);runtimeCallbacks.freeHostRef(rt,host_ref_id);},callFunction:(asyncify,ctx,this_ptr,argc,argv,fn_id)=>this.handleAsyncify(asyncify,()=>{try{let vm=this.contextCallbacks.get(ctx);if(!vm)throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);return vm.callFunction(ctx,this_ptr,argc,argv,fn_id)}catch(error){return console.error("[C to host error: returning null]",error),0}}),shouldInterrupt:(asyncify,rt)=>this.handleAsyncify(asyncify,()=>{try{let vm=this.runtimeCallbacks.get(rt);if(!vm)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);return vm.shouldInterrupt(rt)}catch(error){return console.error("[C to host interrupt: returning error]",error),1}}),loadModuleSource:(asyncify,rt,ctx,moduleName)=>this.handleAsyncify(asyncify,()=>{try{let runtimeCallbacks=this.runtimeCallbacks.get(rt);if(!runtimeCallbacks)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);let loadModule=runtimeCallbacks.loadModuleSource;if(!loadModule)throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);return loadModule(rt,ctx,moduleName)}catch(error){return console.error("[C to host module loader error: returning null]",error),0}}),normalizeModule:(asyncify,rt,ctx,moduleBaseName,moduleName)=>this.handleAsyncify(asyncify,()=>{try{let runtimeCallbacks=this.runtimeCallbacks.get(rt);if(!runtimeCallbacks)throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);let normalizeModule=runtimeCallbacks.normalizeModule;if(!normalizeModule)throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);return normalizeModule(rt,ctx,moduleBaseName,moduleName)}catch(error){return console.error("[C to host module loader error: returning null]",error),0}})});this.module=module,this.module.callbacks=this.cToHostCallbacks;}setRuntimeCallbacks(rt,callbacks){this.runtimeCallbacks.set(rt,callbacks);}deleteRuntime(rt){this.runtimeCallbacks.delete(rt);}setContextCallbacks(ctx,callbacks){this.contextCallbacks.set(ctx,callbacks);}deleteContext(ctx){this.contextCallbacks.delete(ctx);}handleAsyncify(asyncify,fn){if(asyncify)return asyncify.handleSleep(done=>{try{let result=fn();if(!(result instanceof Promise)){debugLog("asyncify.handleSleep: not suspending:",result),done(result);return}if(this.suspended)throw new QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}
8
+ Attempted to suspend at:`);this.suspended=new QuickJSAsyncifySuspended(`(${this.suspendedCount++})`),debugLog("asyncify.handleSleep: suspending:",this.suspended),result.then(resolvedResult=>{this.suspended=void 0,debugLog("asyncify.handleSleep: resolved:",resolvedResult),done(resolvedResult);},error=>{debugLog("asyncify.handleSleep: rejected:",error),console.error("QuickJS: cannot handle error in suspended function",error),this.suspended=void 0;});}catch(error){throw this.suspended=void 0,error}});let value=fn();if(value instanceof Promise)throw new Error("Promise return value not supported in non-asyncify context.");return value}};function applyBaseRuntimeOptions(runtime,options){options.interruptHandler&&runtime.setInterruptHandler(options.interruptHandler),options.maxStackSizeBytes!==void 0&&runtime.setMaxStackSize(options.maxStackSizeBytes),options.memoryLimitBytes!==void 0&&runtime.setMemoryLimit(options.memoryLimitBytes);}function applyModuleEvalRuntimeOptions(runtime,options){options.moduleLoader&&runtime.setModuleLoader(options.moduleLoader),options.shouldInterrupt&&runtime.setInterruptHandler(options.shouldInterrupt),options.memoryLimitBytes!==void 0&&runtime.setMemoryLimit(options.memoryLimitBytes),options.maxStackSizeBytes!==void 0&&runtime.setMaxStackSize(options.maxStackSizeBytes);}var QuickJSWASMModule=class{constructor(module,ffi){this.module=module,this.ffi=ffi,this.callbacks=new QuickJSModuleCallbacks(module);}newRuntime(options={}){let rt=new Lifetime(this.ffi.QTS_NewRuntime(),void 0,rt_ptr=>{this.ffi.QTS_FreeRuntime(rt_ptr),this.callbacks.deleteRuntime(rt_ptr);}),runtime=new QuickJSRuntime({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt});return applyBaseRuntimeOptions(runtime,options),options.moduleLoader&&runtime.setModuleLoader(options.moduleLoader),runtime}newContext(options={}){let runtime=this.newRuntime(),context=runtime.newContext({...options,ownedLifetimes:concat(runtime,options.ownedLifetimes)});return runtime.context=context,context}evalCode(code,options={}){return Scope.withScope(scope=>{let vm=scope.manage(this.newContext());applyModuleEvalRuntimeOptions(vm.runtime,options);let result=vm.evalCode(code,"eval.js");if(options.memoryLimitBytes!==void 0&&vm.runtime.setMemoryLimit(-1),result.error)throw vm.dump(scope.manage(result.error));return vm.dump(scope.manage(result.value))})}getWasmMemory(){let memory=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!memory)throw new Error("Variant does not support getting WebAssembly.Memory");return memory}getFFI(){return this.ffi}};
9
+
10
+ export { QuickJSModuleCallbacks, QuickJSWASMModule, applyBaseRuntimeOptions, applyModuleEvalRuntimeOptions };