sandboxedjs 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,26 @@
1
1
  import { DependencyInstaller } from '@scelar/nodepod';
2
- import { parse as parse$1 } from 'acorn';
2
+ import { Parser as Parser$1, parse as parse$1 } from 'acorn';
3
+ import EventEmitter3 from 'events';
4
+ import jsx from 'acorn-jsx';
5
+ import { exports as exports$1, imports } from 'resolve.exports';
6
+ import { Buffer as Buffer$1 } from 'buffer';
7
+ import pathModule from 'path-browserify';
8
+ import streamModule3 from 'stream-browserify';
9
+ import utilModule from 'util';
10
+ import assertModule from 'assert';
11
+ import processShim from 'process';
12
+ import zlibModule from 'browserify-zlib';
13
+ import querystringModule from 'querystring-es3';
14
+ import stringDecoderModule from 'string_decoder';
15
+ import timersModule from 'timers-browserify';
16
+ import urlModule from 'url';
17
+ import { sha1 as sha1$1, md5 } from '@noble/hashes/legacy';
18
+ import { sha256, sha224 } from '@noble/hashes/sha256';
19
+ import { sha512, sha384 } from '@noble/hashes/sha512';
20
+ import { hmac } from '@noble/hashes/hmac';
21
+ import { ungzip } from 'pako';
22
+ import { sha1 } from '@noble/hashes/sha1';
23
+ import { valid, maxSatisfying } from 'semver';
3
24
 
4
25
  var __defProp = Object.defineProperty;
5
26
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -1065,16 +1086,16 @@ function tokenize(src) {
1065
1086
  out.push({ kind: "eof", value: "" });
1066
1087
  return out;
1067
1088
  }
1068
- function parseInBase(text, base) {
1089
+ function parseInBase(text2, base) {
1069
1090
  let value = 0;
1070
- for (const ch of text) {
1091
+ for (const ch of text2) {
1071
1092
  let digit;
1072
1093
  if (base <= 36) {
1073
1094
  digit = DIGITS.toLowerCase().indexOf(ch.toLowerCase());
1074
1095
  } else {
1075
1096
  digit = DIGITS.indexOf(ch);
1076
1097
  }
1077
- if (digit < 0 || digit >= base) throw new ArithError(`value too great for base (error token is "${text}")`);
1098
+ if (digit < 0 || digit >= base) throw new ArithError(`value too great for base (error token is "${text2}")`);
1078
1099
  value = value * base + digit;
1079
1100
  }
1080
1101
  return value;
@@ -1410,8 +1431,8 @@ function ifsOf(ctx) {
1410
1431
  const raw = ctx.vars.get("IFS");
1411
1432
  return raw === void 0 ? IFS_DEFAULT : raw;
1412
1433
  }
1413
- function escapeGlob(text) {
1414
- return text.replace(/[*?[\]\\]/g, "\\$&");
1434
+ function escapeGlob(text2) {
1435
+ return text2.replace(/[*?[\]\\]/g, "\\$&");
1415
1436
  }
1416
1437
  function braceExpand(word) {
1417
1438
  const open = findUnquotedBrace(word);
@@ -1567,12 +1588,12 @@ async function expandFragments(word, ctx, opts = {}) {
1567
1588
  literalGlob = true;
1568
1589
  }
1569
1590
  };
1570
- const pushLiteral = (text, globActive) => {
1591
+ const pushLiteral = (text2, globActive) => {
1571
1592
  if (globActive !== literalGlob) {
1572
1593
  flushLiteral();
1573
1594
  literalGlob = globActive;
1574
1595
  }
1575
- literal += text;
1596
+ literal += text2;
1576
1597
  };
1577
1598
  while (i < word.length) {
1578
1599
  const c = word[i];
@@ -1919,8 +1940,8 @@ async function expandBracedParameter(body, ctx, quoted) {
1919
1940
  }
1920
1941
  return valueFragments(name, ctx, quoted);
1921
1942
  }
1922
- function frag(text, quoted) {
1923
- return { text, split: !quoted, glob: false };
1943
+ function frag(text2, quoted) {
1944
+ return { text: text2, split: !quoted, glob: false };
1924
1945
  }
1925
1946
  function stripAffix(value, pattern, op, ctx) {
1926
1947
  const opts = { pathname: false, dot: true, extglob: ctx.extglob !== false };
@@ -2016,26 +2037,26 @@ function splitOnUnquotedColon(spec) {
2016
2037
  out.push(current);
2017
2038
  return out;
2018
2039
  }
2019
- function findUnescaped(text, ch) {
2020
- for (let i = 0; i < text.length; i++) {
2021
- if (text[i] === "\\") {
2040
+ function findUnescaped(text2, ch) {
2041
+ for (let i = 0; i < text2.length; i++) {
2042
+ if (text2[i] === "\\") {
2022
2043
  i++;
2023
2044
  continue;
2024
2045
  }
2025
- if (text[i] === ch) return i;
2046
+ if (text2[i] === ch) return i;
2026
2047
  }
2027
2048
  return -1;
2028
2049
  }
2029
- function matchParen(text, open) {
2050
+ function matchParen(text2, open) {
2030
2051
  let depth = 0;
2031
- for (let i = open; i < text.length; i++) {
2032
- const c = text[i];
2052
+ for (let i = open; i < text2.length; i++) {
2053
+ const c = text2[i];
2033
2054
  if (c === "\\") {
2034
2055
  i++;
2035
2056
  continue;
2036
2057
  }
2037
2058
  if (c === "'") {
2038
- const end = text.indexOf("'", i + 1);
2059
+ const end = text2.indexOf("'", i + 1);
2039
2060
  if (end < 0) return -1;
2040
2061
  i = end;
2041
2062
  continue;
@@ -2048,10 +2069,10 @@ function matchParen(text, open) {
2048
2069
  }
2049
2070
  return -1;
2050
2071
  }
2051
- function matchDoubleParen(text, open) {
2072
+ function matchDoubleParen(text2, open) {
2052
2073
  let depth = 0;
2053
- for (let i = open; i < text.length; i++) {
2054
- const c = text[i];
2074
+ for (let i = open; i < text2.length; i++) {
2075
+ const c = text2[i];
2055
2076
  if (c === "\\") {
2056
2077
  i++;
2057
2078
  continue;
@@ -2064,21 +2085,21 @@ function matchDoubleParen(text, open) {
2064
2085
  }
2065
2086
  return -1;
2066
2087
  }
2067
- function findBacktick(text, from) {
2068
- for (let i = from + 1; i < text.length; i++) {
2069
- if (text[i] === "\\") {
2088
+ function findBacktick(text2, from) {
2089
+ for (let i = from + 1; i < text2.length; i++) {
2090
+ if (text2[i] === "\\") {
2070
2091
  i++;
2071
2092
  continue;
2072
2093
  }
2073
- if (text[i] === "`") return i;
2094
+ if (text2[i] === "`") return i;
2074
2095
  }
2075
- return text.length;
2096
+ return text2.length;
2076
2097
  }
2077
- function unescapeBacktick(text) {
2078
- return text.replace(/\\([`$\\])/g, "$1");
2098
+ function unescapeBacktick(text2) {
2099
+ return text2.replace(/\\([`$\\])/g, "$1");
2079
2100
  }
2080
- function stripTrailingNewlines(text) {
2081
- return text.replace(/\n+$/, "");
2101
+ function stripTrailingNewlines(text2) {
2102
+ return text2.replace(/\n+$/, "");
2082
2103
  }
2083
2104
  function fieldSplit(fragments, ifs) {
2084
2105
  if (fragments.length === 0) return [];
@@ -2101,9 +2122,9 @@ function fieldSplit(fragments, ifs) {
2101
2122
  }
2102
2123
  let buffer = "";
2103
2124
  let i = 0;
2104
- const text = fragment.text;
2105
- while (i < text.length) {
2106
- const c = text[i];
2125
+ const text2 = fragment.text;
2126
+ while (i < text2.length) {
2127
+ const c = text2[i];
2107
2128
  if (whitespace.includes(c) || others.includes(c)) {
2108
2129
  if (buffer !== "" || current.length > 0) {
2109
2130
  if (buffer !== "") current.push({ ...fragment, text: buffer });
@@ -2113,8 +2134,8 @@ function fieldSplit(fragments, ifs) {
2113
2134
  }
2114
2135
  let consumedNonWs = others.includes(c);
2115
2136
  i++;
2116
- while (i < text.length) {
2117
- const d = text[i];
2137
+ while (i < text2.length) {
2138
+ const d = text2[i];
2118
2139
  if (whitespace.includes(d)) {
2119
2140
  i++;
2120
2141
  continue;
@@ -2802,13 +2823,13 @@ function builtinEcho({ argv, io }) {
2802
2823
  }
2803
2824
  args = args.slice(1);
2804
2825
  }
2805
- let text = args.join(" ");
2826
+ let text2 = args.join(" ");
2806
2827
  if (interpret) {
2807
- const decoded = decodeEscapes(text, { stopAtC: true });
2808
- text = decoded.text;
2828
+ const decoded = decodeEscapes(text2, { stopAtC: true });
2829
+ text2 = decoded.text;
2809
2830
  if (decoded.stopped) newline = false;
2810
2831
  }
2811
- io.stdout.write(newline ? text + "\n" : text);
2832
+ io.stdout.write(newline ? text2 + "\n" : text2);
2812
2833
  return 0;
2813
2834
  }
2814
2835
  function builtinPrintf({ argv, io }) {
@@ -2825,9 +2846,9 @@ function builtinPrintf({ argv, io }) {
2825
2846
  return 2;
2826
2847
  }
2827
2848
  try {
2828
- const text = formatPrintf(format, args.slice(start + 1));
2849
+ const text2 = formatPrintf(format, args.slice(start + 1));
2829
2850
  if (varName) return 0;
2830
- io.stdout.write(text);
2851
+ io.stdout.write(text2);
2831
2852
  return 0;
2832
2853
  } catch (e) {
2833
2854
  io.stderr.write(`printf: ${e instanceof PrintfError ? e.message : String(e)}
@@ -2910,9 +2931,9 @@ async function builtinSource({ shell, argv, io }) {
2910
2931
  const found = shell.kernel.which(target, shell.cwd, shell.vars.environment(), shell.cred);
2911
2932
  if (found) path = found;
2912
2933
  }
2913
- let text;
2934
+ let text2;
2914
2935
  try {
2915
- text = shell.kernel.vfs.readText(path, shell.cred);
2936
+ text2 = shell.kernel.vfs.readText(path, shell.cred);
2916
2937
  } catch {
2917
2938
  io.stderr.write(`${argv[0]}: ${target}: No such file or directory
2918
2939
  `);
@@ -2921,7 +2942,7 @@ async function builtinSource({ shell, argv, io }) {
2921
2942
  const savedPositional = shell.positional;
2922
2943
  if (argv.length > 2) shell.positional = argv.slice(2);
2923
2944
  try {
2924
- return await shell.execute(text, io);
2945
+ return await shell.execute(text2, io);
2925
2946
  } finally {
2926
2947
  shell.positional = savedPositional;
2927
2948
  }
@@ -4223,9 +4244,9 @@ var init_ffmpeg_core = __esm({
4223
4244
  }
4224
4245
  var wasmMemory;
4225
4246
  var ABORT = false;
4226
- function assert(condition, text) {
4247
+ function assert(condition, text2) {
4227
4248
  if (!condition) {
4228
- abort(text);
4249
+ abort(text2);
4229
4250
  }
4230
4251
  }
4231
4252
  var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPF64;
@@ -6716,8 +6737,8 @@ var init_ffmpeg_core = __esm({
6716
6737
  };
6717
6738
  function handleMessage(data) {
6718
6739
  if (typeof data == "string") {
6719
- var encoder6 = new TextEncoder();
6720
- data = encoder6.encode(data);
6740
+ var encoder7 = new TextEncoder();
6741
+ data = encoder7.encode(data);
6721
6742
  } else {
6722
6743
  assert(data.byteLength !== void 0);
6723
6744
  if (data.byteLength == 0) {
@@ -8800,15 +8821,15 @@ async function buildPatchedWorker() {
8800
8821
  function ensureEsbuild() {`)
8801
8822
  ].join("\n");
8802
8823
  const fingerprint = crypto2.createHash("sha256").update(`${source.length}:${wasmStat.size}:${patched.length}`).digest("hex").slice(0, 16);
8803
- const cached = path.join(os.tmpdir(), `sandboxedjs-worker-${fingerprint}.js`);
8824
+ const cached2 = path.join(os.tmpdir(), `sandboxedjs-worker-${fingerprint}.js`);
8804
8825
  try {
8805
- await fs.access(cached);
8826
+ await fs.access(cached2);
8806
8827
  } catch {
8807
- const staging = `${cached}.${process.pid}.tmp`;
8828
+ const staging = `${cached2}.${process.pid}.tmp`;
8808
8829
  await fs.writeFile(staging, patched, "utf8");
8809
- await fs.rename(staging, cached);
8830
+ await fs.rename(staging, cached2);
8810
8831
  }
8811
- return cached;
8832
+ return cached2;
8812
8833
  }
8813
8834
  var INIT_HELPER = `let __sandboxedjsWasmUrl = null;
8814
8835
  async function __sandboxedjsEsbuildInit(wasmPath, wasmUrl) {
@@ -10393,16 +10414,16 @@ function createContext(init) {
10393
10414
  path(p) {
10394
10415
  return resolve(cwd, p);
10395
10416
  },
10396
- write(text) {
10417
+ write(text2) {
10397
10418
  try {
10398
- stdout.write(text);
10419
+ stdout.write(text2);
10399
10420
  } catch (e) {
10400
10421
  if (isSysError(e) && e.code === "EPIPE") proc.deliver("SIGPIPE");
10401
10422
  else throw e;
10402
10423
  }
10403
10424
  },
10404
- line(text = "") {
10405
- ctx.write(encoder3.encode(text + "\n"));
10425
+ line(text2 = "") {
10426
+ ctx.write(encoder3.encode(text2 + "\n"));
10406
10427
  },
10407
10428
  warn(message) {
10408
10429
  try {
@@ -11279,8 +11300,8 @@ function createProcProvider(kernel) {
11279
11300
  loadavg: () => textFile(() => {
11280
11301
  const running = kernel.procs.list().filter((p) => p.state === "R").length;
11281
11302
  const total = kernel.procs.list().length;
11282
- const load = (running / kernel.cpus).toFixed(2);
11283
- return `${load} ${load} ${load} ${running}/${total} ${kernel.procs.list().length + 1}
11303
+ const load2 = (running / kernel.cpus).toFixed(2);
11304
+ return `${load2} ${load2} ${load2} ${running}/${total} ${kernel.procs.list().length + 1}
11284
11305
  `;
11285
11306
  }),
11286
11307
  meminfo: () => textFile(() => {
@@ -11536,13 +11557,13 @@ var NetworkStack = class {
11536
11557
  /** Resolve through `/etc/hosts`; returns null when the name is not local. */
11537
11558
  resolve(host2) {
11538
11559
  if (/^\d+\.\d+\.\d+\.\d+$/.test(host2)) return host2;
11539
- let text = "";
11560
+ let text2 = "";
11540
11561
  try {
11541
- text = this.vfs.readText("/etc/hosts");
11562
+ text2 = this.vfs.readText("/etc/hosts");
11542
11563
  } catch {
11543
11564
  return null;
11544
11565
  }
11545
- for (const line of text.split("\n")) {
11566
+ for (const line of text2.split("\n")) {
11546
11567
  const clean2 = line.split("#")[0].trim();
11547
11568
  if (clean2 === "") continue;
11548
11569
  const [addr, ...names] = clean2.split(/\s+/);
@@ -11901,9 +11922,9 @@ var Lexer = class _Lexer {
11901
11922
  }
11902
11923
  }
11903
11924
  if (i >= this.src.length) throw new IncompleteInputError(`unexpected EOF while looking for matching \`${close}'`, start);
11904
- const text = prefix + this.src.slice(openIdx, i + 1);
11925
+ const text2 = prefix + this.src.slice(openIdx, i + 1);
11905
11926
  this.pos = i + 1;
11906
- return text;
11927
+ return text2;
11907
11928
  }
11908
11929
  skipDoubleQuoted(from) {
11909
11930
  for (let i = from + 1; i < this.src.length; i++) {
@@ -12743,8 +12764,8 @@ var Shell = class _Shell {
12743
12764
  async makeProcessSubstitution(command, direction) {
12744
12765
  const path = `/tmp/.sbx-procsub-${this.proc.pid}-${this.tempFileCounter++}`;
12745
12766
  if (direction === "in") {
12746
- const text = await this.captureSubshell(command);
12747
- this.kernel.vfs.writeFile(path, text, { cred: this.cred, mode: 384 });
12767
+ const text2 = await this.captureSubshell(command);
12768
+ this.kernel.vfs.writeFile(path, text2, { cred: this.cred, mode: 384 });
12748
12769
  } else {
12749
12770
  this.kernel.vfs.writeFile(path, "", { cred: this.cred, mode: 384 });
12750
12771
  }
@@ -13525,12 +13546,12 @@ sys ${fmt2(Math.floor(ms * 0.2))}
13525
13546
  return finished;
13526
13547
  }
13527
13548
  };
13528
- function splitAliasWords(text) {
13549
+ function splitAliasWords(text2) {
13529
13550
  const out = [];
13530
13551
  let current = "";
13531
13552
  let quote2 = null;
13532
- for (let i = 0; i < text.length; i++) {
13533
- const c = text[i];
13553
+ for (let i = 0; i < text2.length; i++) {
13554
+ const c = text2[i];
13534
13555
  if (quote2) {
13535
13556
  if (c === quote2) quote2 = null;
13536
13557
  else current += c;
@@ -13718,10 +13739,10 @@ async function readInputs(ctx, operands, opts = {}) {
13718
13739
  return { sources, ok };
13719
13740
  }
13720
13741
  function splitLines(bytes) {
13721
- const text = decoder3.decode(bytes);
13722
- if (text === "") return { lines: [], trailingNewline: true };
13723
- const trailingNewline = text.endsWith("\n");
13724
- const body = trailingNewline ? text.slice(0, -1) : text;
13742
+ const text2 = decoder3.decode(bytes);
13743
+ if (text2 === "") return { lines: [], trailingNewline: true };
13744
+ const trailingNewline = text2.endsWith("\n");
13745
+ const body = trailingNewline ? text2.slice(0, -1) : text2;
13725
13746
  return { lines: body.split("\n"), trailingNewline };
13726
13747
  }
13727
13748
  function joinLines(lines, trailingNewline = true) {
@@ -13777,9 +13798,9 @@ function columnize(items, width, gap = 2) {
13777
13798
  }
13778
13799
  return out;
13779
13800
  }
13780
- function displayWidth(text) {
13801
+ function displayWidth(text2) {
13781
13802
  let width = 0;
13782
- for (const ch of text) {
13803
+ for (const ch of text2) {
13783
13804
  const code = ch.codePointAt(0);
13784
13805
  if (code >= 4352 && (code <= 4447 || code >= 11904 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65135 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510)) {
13785
13806
  width += 2;
@@ -14055,9 +14076,9 @@ var cat = defineCommand({
14055
14076
  ctx.write(bytes);
14056
14077
  continue;
14057
14078
  }
14058
- const text = new TextDecoder().decode(bytes);
14059
- const hadTrailing = text.endsWith("\n");
14060
- const parts = (hadTrailing ? text.slice(0, -1) : text).split("\n");
14079
+ const text2 = new TextDecoder().decode(bytes);
14080
+ const hadTrailing = text2.endsWith("\n");
14081
+ const parts = (hadTrailing ? text2.slice(0, -1) : text2).split("\n");
14061
14082
  for (const raw of parts) {
14062
14083
  if (args.has("squeeze-blank")) {
14063
14084
  if (raw === "" && lastWasBlank) continue;
@@ -14917,11 +14938,11 @@ function describeFile(ctx, abs, st, mime) {
14917
14938
  if (magic[0] === 31 && magic[1] === 139) return mime ? "application/gzip" : "gzip compressed data";
14918
14939
  if (magic[0] === 80 && magic[1] === 75) return mime ? "application/zip" : "Zip archive data";
14919
14940
  if (magic[0] === 137 && magic[1] === 80) return mime ? "image/png" : "PNG image data";
14920
- const text = new TextDecoder().decode(bytes);
14921
- const printable = [...text].every((c) => c === "\n" || c === " " || c === "\r" || c >= " " && c <= "~" || c.charCodeAt(0) > 127);
14941
+ const text2 = new TextDecoder().decode(bytes);
14942
+ const printable = [...text2].every((c) => c === "\n" || c === " " || c === "\r" || c >= " " && c <= "~" || c.charCodeAt(0) > 127);
14922
14943
  if (!printable) return mime ? "application/octet-stream" : "data";
14923
- if (text.startsWith("#!")) {
14924
- const interp = text.slice(2, text.indexOf("\n")).trim();
14944
+ if (text2.startsWith("#!")) {
14945
+ const interp = text2.slice(2, text2.indexOf("\n")).trim();
14925
14946
  return mime ? "text/x-shellscript" : `a ${interp} script, ASCII text executable`;
14926
14947
  }
14927
14948
  const ext = extname(abs);
@@ -14974,13 +14995,13 @@ var echo = defineCommand({
14974
14995
  }
14975
14996
  args = args.slice(1);
14976
14997
  }
14977
- let text = args.join(" ");
14998
+ let text2 = args.join(" ");
14978
14999
  if (interpret) {
14979
- const decoded = decodeEscapes(text, { stopAtC: true });
14980
- text = decoded.text;
15000
+ const decoded = decodeEscapes(text2, { stopAtC: true });
15001
+ text2 = decoded.text;
14981
15002
  if (decoded.stopped) newline = false;
14982
15003
  }
14983
- ctx.write(newline ? text + "\n" : text);
15004
+ ctx.write(newline ? text2 + "\n" : text2);
14984
15005
  return 0;
14985
15006
  }
14986
15007
  });
@@ -15051,8 +15072,8 @@ var yesCmd = defineCommand({
15051
15072
  path: "/usr/bin/yes",
15052
15073
  summary: "output a string repeatedly until killed",
15053
15074
  async run(ctx) {
15054
- const text = (ctx.args.length ? ctx.args.join(" ") : "y") + "\n";
15055
- const block = text.repeat(512);
15075
+ const text2 = (ctx.args.length ? ctx.args.join(" ") : "y") + "\n";
15076
+ const block = text2.repeat(512);
15056
15077
  for (let i = 0; i < 1e5 && !ctx.signal.aborted && !ctx.stdout.closed; i++) {
15057
15078
  ctx.write(block);
15058
15079
  await new Promise((r) => setTimeout(r, 0));
@@ -15094,8 +15115,8 @@ var seq = defineCommand({
15094
15115
  if (increment > 0) for (let v = first; v <= last + 1e-9; v += increment) values.push(v);
15095
15116
  else for (let v = first; v >= last - 1e-9; v += increment) values.push(v);
15096
15117
  const rendered = values.map((v) => {
15097
- const text = Number.isInteger(v) ? String(v) : String(Number(v.toFixed(10)));
15098
- return format ? formatPrintf(format, [String(v)]) : text;
15118
+ const text2 = Number.isInteger(v) ? String(v) : String(Number(v.toFixed(10)));
15119
+ return format ? formatPrintf(format, [String(v)]) : text2;
15099
15120
  });
15100
15121
  const width = args.has("equal-width") ? Math.max(0, ...rendered.map((r) => r.length)) : 0;
15101
15122
  const out = rendered.map((r) => width ? r.padStart(width, "0") : r);
@@ -16081,8 +16102,8 @@ var ScriptParser = class {
16081
16102
  return { type: "y", range, from: [...unescape(from)], to: [...unescape(to)] };
16082
16103
  }
16083
16104
  };
16084
- function unescape(text) {
16085
- return text.replace(/\\(.)/g, (_, c) => ({ n: "\n", t: " ", r: "\r", "\\": "\\" })[c] ?? c);
16105
+ function unescape(text2) {
16106
+ return text2.replace(/\\(.)/g, (_, c) => ({ n: "\n", t: " ", r: "\r", "\\": "\\" })[c] ?? c);
16086
16107
  }
16087
16108
  function toJsRegex(pattern, extended) {
16088
16109
  let out = "";
@@ -16188,15 +16209,15 @@ var BRACKET_CLASSES = {
16188
16209
  xdigit: "0-9A-Fa-f",
16189
16210
  word: "A-Za-z0-9_"
16190
16211
  };
16191
- function translateBracket(text) {
16192
- return text.replace(/\[:([a-z]+):\]/g, (_, name) => BRACKET_CLASSES[name] ?? "");
16212
+ function translateBracket(text2) {
16213
+ return text2.replace(/\[:([a-z]+):\]/g, (_, name) => BRACKET_CLASSES[name] ?? "");
16193
16214
  }
16194
16215
  function applyReplacement(replacement, match) {
16195
16216
  let out = "";
16196
16217
  let caseMode = null;
16197
16218
  let oneShot = null;
16198
- const emit = (text) => {
16199
- let value = text;
16219
+ const emit = (text2) => {
16220
+ let value = text2;
16200
16221
  if (oneShot && value.length > 0) {
16201
16222
  value = (oneShot === "u" ? value[0].toUpperCase() : value[0].toLowerCase()) + value.slice(1);
16202
16223
  oneShot = null;
@@ -16326,20 +16347,20 @@ async function runSed(ctx) {
16326
16347
  flushAppends(state);
16327
16348
  if (state.quit !== null) break;
16328
16349
  }
16329
- const text = joinLines(state.output, trailingNewline || state.output.length > 0);
16350
+ const text2 = joinLines(state.output, trailingNewline || state.output.length > 0);
16330
16351
  if (inPlace && source.name !== "-" && source.name !== "standard input") {
16331
16352
  const abs = ctx.path(source.name);
16332
16353
  if (suffix) ctx.vfs.writeFile(ctx.path(source.name + suffix), source.bytes, { cred: ctx.cred });
16333
- ctx.vfs.writeFile(abs, text, { cred: ctx.cred });
16354
+ ctx.vfs.writeFile(abs, text2, { cred: ctx.cred });
16334
16355
  } else {
16335
- ctx.write(text);
16356
+ ctx.write(text2);
16336
16357
  }
16337
16358
  if (state.quit !== null && state.quit !== 0) status = state.quit;
16338
16359
  }
16339
16360
  return status;
16340
16361
  }
16341
16362
  function flushAppends(state) {
16342
- for (const text of state.appendQueue) state.output.push(text);
16363
+ for (const text2 of state.appendQueue) state.output.push(text2);
16343
16364
  state.appendQueue = [];
16344
16365
  }
16345
16366
  function resetRanges(program) {
@@ -16525,8 +16546,8 @@ function substitute2(input, regex, replacement, global, occurrence) {
16525
16546
  out += input.slice(last);
16526
16547
  return { text: out, changed };
16527
16548
  }
16528
- function escapeForL(text) {
16529
- return [...text].map((ch) => {
16549
+ function escapeForL(text2) {
16550
+ return [...text2].map((ch) => {
16530
16551
  const code = ch.charCodeAt(0);
16531
16552
  if (ch === "\\") return "\\\\";
16532
16553
  if (ch === " ") return "\\t";
@@ -16738,10 +16759,10 @@ function tokenize2(src) {
16738
16759
  i += 2;
16739
16760
  continue;
16740
16761
  }
16741
- const octal = /^[0-7]{1,3}/.exec(src.slice(i + 1));
16742
- if (octal) {
16743
- value += String.fromCharCode(parseInt(octal[0], 8));
16744
- i += 1 + octal[0].length;
16762
+ const octal2 = /^[0-7]{1,3}/.exec(src.slice(i + 1));
16763
+ if (octal2) {
16764
+ value += String.fromCharCode(parseInt(octal2[0], 8));
16765
+ i += 1 + octal2[0].length;
16745
16766
  continue;
16746
16767
  }
16747
16768
  value += next;
@@ -17493,9 +17514,9 @@ var Interpreter = class {
17493
17514
  return this.numToStr(v.num, this.toStrRaw(this.globals.get("OFMT")));
17494
17515
  }
17495
17516
  // ── output ────────────────────────────────────────────────────────────────
17496
- emit(text, redirect) {
17517
+ emit(text2, redirect) {
17497
17518
  if (!redirect) {
17498
- this.pendingOutput += text;
17519
+ this.pendingOutput += text2;
17499
17520
  if (this.pendingOutput.length > 8192) this.flush();
17500
17521
  return;
17501
17522
  }
@@ -17505,7 +17526,7 @@ var Interpreter = class {
17505
17526
  target = this.openOutput(name, redirect.op);
17506
17527
  this.outputs.set(name, target);
17507
17528
  }
17508
- target.write(text);
17529
+ target.write(text2);
17509
17530
  }
17510
17531
  flush() {
17511
17532
  if (this.pendingOutput !== "") {
@@ -17519,8 +17540,8 @@ var Interpreter = class {
17519
17540
  const ctx = this.ctx;
17520
17541
  const self2 = this;
17521
17542
  return {
17522
- write: (text) => {
17523
- buffer += text;
17543
+ write: (text2) => {
17544
+ buffer += text2;
17524
17545
  },
17525
17546
  close: () => {
17526
17547
  self2.flush();
@@ -17538,18 +17559,18 @@ var Interpreter = class {
17538
17559
  };
17539
17560
  }
17540
17561
  if (name === "/dev/stdout" || name === "-") {
17541
- return { write: (text) => this.ctx.write(text), close: () => {
17562
+ return { write: (text2) => this.ctx.write(text2), close: () => {
17542
17563
  } };
17543
17564
  }
17544
17565
  if (name === "/dev/stderr") {
17545
- return { write: (text) => this.ctx.stderr.write(text), close: () => {
17566
+ return { write: (text2) => this.ctx.stderr.write(text2), close: () => {
17546
17567
  } };
17547
17568
  }
17548
17569
  const abs = this.ctx.path(name);
17549
17570
  if (op === ">") this.ctx.vfs.writeFile(abs, "", { cred: this.ctx.cred });
17550
17571
  else if (!this.ctx.vfs.lexists(abs)) this.ctx.vfs.writeFile(abs, "", { cred: this.ctx.cred });
17551
17572
  return {
17552
- write: (text) => this.ctx.vfs.appendFile(abs, text, { cred: this.ctx.cred }),
17573
+ write: (text2) => this.ctx.vfs.appendFile(abs, text2, { cred: this.ctx.cred }),
17553
17574
  close: () => {
17554
17575
  }
17555
17576
  };
@@ -17911,8 +17932,8 @@ var Interpreter = class {
17911
17932
  let handle = this.inputs.get(name);
17912
17933
  if (!handle) {
17913
17934
  try {
17914
- const text = this.ctx.vfs.readText(this.ctx.path(name), this.ctx.cred);
17915
- handle = { lines: splitLines(new TextEncoder().encode(text)).lines, index: 0 };
17935
+ const text2 = this.ctx.vfs.readText(this.ctx.path(name), this.ctx.cred);
17936
+ handle = { lines: splitLines(new TextEncoder().encode(text2)).lines, index: 0 };
17916
17937
  } catch {
17917
17938
  return Value.fromNumber(-1);
17918
17939
  }
@@ -17951,8 +17972,8 @@ var Interpreter = class {
17951
17972
  case "print": {
17952
17973
  const ofs = this.toStr(this.getVar("OFS"));
17953
17974
  const ors = this.toStr(this.getVar("ORS"));
17954
- const text = stmt.args.length === 0 ? this.toStr(this.getField(0)) : stmt.args.map((a) => this.outputStr(this.evaluate(a))).join(ofs);
17955
- this.emit(text + ors, stmt.redirect);
17975
+ const text2 = stmt.args.length === 0 ? this.toStr(this.getField(0)) : stmt.args.map((a) => this.outputStr(this.evaluate(a))).join(ofs);
17976
+ this.emit(text2 + ors, stmt.redirect);
17956
17977
  return;
17957
17978
  }
17958
17979
  case "printf": {
@@ -18437,13 +18458,13 @@ var wc = defineCommand({
18437
18458
  const totals = { lines: 0, words: 0, bytes: 0, chars: 0, maxLine: 0 };
18438
18459
  const rows = [];
18439
18460
  for (const source of sources) {
18440
- const text = decoder4.decode(source.bytes);
18461
+ const text2 = decoder4.decode(source.bytes);
18441
18462
  const counts = {
18442
- lines: (text.match(/\n/g) ?? []).length,
18443
- words: text.split(/\s+/).filter((w) => w !== "").length,
18463
+ lines: (text2.match(/\n/g) ?? []).length,
18464
+ words: text2.split(/\s+/).filter((w) => w !== "").length,
18444
18465
  bytes: source.bytes.length,
18445
- chars: [...text].length,
18446
- maxLine: Math.max(0, ...text.split("\n").map((l) => displayWidth(l)))
18466
+ chars: [...text2].length,
18467
+ maxLine: Math.max(0, ...text2.split("\n").map((l) => displayWidth(l)))
18447
18468
  };
18448
18469
  totals.lines += counts.lines;
18449
18470
  totals.words += counts.words;
@@ -18510,15 +18531,15 @@ var sort = defineCommand({
18510
18531
  const slice = fields.slice(start, end === void 0 ? void 0 : end);
18511
18532
  return slice.join(separator ?? " ");
18512
18533
  };
18513
- const normalize2 = (line) => {
18534
+ const normalize3 = (line) => {
18514
18535
  let value = keys.length ? fieldOf(line, keys[0]) : line;
18515
18536
  if (args.has("ignore-leading-blanks")) value = value.replace(/^\s+/, "");
18516
18537
  if (args.has("ignore-case")) value = value.toLowerCase();
18517
18538
  return value;
18518
18539
  };
18519
18540
  const compare = (a, b) => {
18520
- const x = normalize2(a);
18521
- const y = normalize2(b);
18541
+ const x = normalize3(a);
18542
+ const y = normalize3(b);
18522
18543
  if (args.has("numeric-sort") || args.has("general-numeric-sort")) {
18523
18544
  const nx = parseFloat(x) || 0;
18524
18545
  const ny = parseFloat(y) || 0;
@@ -18609,9 +18630,9 @@ var uniq = defineCommand({
18609
18630
  }
18610
18631
  out.push(args.has("count") ? `${String(group.count).padStart(7)} ${group.line}` : group.line);
18611
18632
  }
18612
- const text = joinLines(out, true);
18613
- if (output) ctx.vfs.writeFile(ctx.path(output), text, { cred: ctx.cred });
18614
- else ctx.write(text);
18633
+ const text2 = joinLines(out, true);
18634
+ if (output) ctx.vfs.writeFile(ctx.path(output), text2, { cred: ctx.cred });
18635
+ else ctx.write(text2);
18615
18636
  return ok ? 0 : 1;
18616
18637
  }
18617
18638
  });
@@ -18721,11 +18742,11 @@ var tr = defineCommand({
18721
18742
  if (set1Raw === void 0) return ctx.fail("missing operand", 1);
18722
18743
  const set1 = expandSet(set1Raw);
18723
18744
  const set2 = set2Raw === void 0 ? [] : expandSet(set2Raw);
18724
- const text = decoder4.decode(await ctx.stdin.readAll());
18745
+ const text2 = decoder4.decode(await ctx.stdin.readAll());
18725
18746
  const inSet1 = (ch) => args.has("complement") ? !set1.includes(ch) : set1.includes(ch);
18726
18747
  let out = "";
18727
18748
  let lastEmitted = "";
18728
- for (const ch of text) {
18749
+ for (const ch of text2) {
18729
18750
  if (args.has("delete") && inSet1(ch)) continue;
18730
18751
  let mapped = ch;
18731
18752
  if (!args.has("delete") && set2.length && inSet1(ch)) {
@@ -19396,12 +19417,12 @@ var grep = defineCommand({
19396
19417
  }
19397
19418
  continue;
19398
19419
  }
19399
- let text = lines[i];
19420
+ let text2 = lines[i];
19400
19421
  if (useColor && isMatchLine && !args.has("invert-match")) {
19401
19422
  regex.lastIndex = 0;
19402
- text = text.replace(regex, (m) => `\x1B[1;31m${m}\x1B[0m`);
19423
+ text2 = text2.replace(regex, (m) => `\x1B[1;31m${m}\x1B[0m`);
19403
19424
  }
19404
- ctx.line(prefix + text);
19425
+ ctx.line(prefix + text2);
19405
19426
  lastPrinted = i;
19406
19427
  }
19407
19428
  }
@@ -19409,8 +19430,8 @@ var grep = defineCommand({
19409
19430
  return anyMatch ? status === 2 ? 2 : 0 : status === 2 ? 2 : 1;
19410
19431
  }
19411
19432
  });
19412
- function escapeLiteral(text) {
19413
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19433
+ function escapeLiteral(text2) {
19434
+ return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19414
19435
  }
19415
19436
  var find = defineCommand({
19416
19437
  name: "find",
@@ -19759,7 +19780,7 @@ var diff = defineCommand({
19759
19780
  if (a === void 0 || b === void 0) return ctx.fail("missing operand", 2);
19760
19781
  const { sources, ok } = await readInputs(ctx, [a, b]);
19761
19782
  if (!ok || sources.length < 2) return 2;
19762
- const normalize2 = (line) => {
19783
+ const normalize3 = (line) => {
19763
19784
  let value = line;
19764
19785
  if (args.has("ignore-all-space")) value = value.replace(/\s+/g, "");
19765
19786
  else if (args.has("ignore-space-change")) value = value.replace(/\s+/g, " ").trim();
@@ -19768,7 +19789,7 @@ var diff = defineCommand({
19768
19789
  };
19769
19790
  const left = splitLines(sources[0].bytes).lines;
19770
19791
  const right = splitLines(sources[1].bytes).lines;
19771
- const script = diffLines(left.map(normalize2), right.map(normalize2));
19792
+ const script = diffLines(left.map(normalize3), right.map(normalize3));
19772
19793
  if (script.length === 0) return 0;
19773
19794
  if (args.has("brief")) {
19774
19795
  ctx.line(`Files ${a} and ${b} differ`);
@@ -19931,8 +19952,8 @@ function writeString(block, offset, value, length) {
19931
19952
  for (let i = 0; i < length; i++) block[offset + i] = i < bytes.length ? bytes[i] : 0;
19932
19953
  }
19933
19954
  function writeOctal(block, offset, value, length) {
19934
- const text = value.toString(8).padStart(length - 1, "0");
19935
- writeString(block, offset, text, length);
19955
+ const text2 = value.toString(8).padStart(length - 1, "0");
19956
+ writeString(block, offset, text2, length);
19936
19957
  }
19937
19958
  function readString(block, offset, length) {
19938
19959
  let end = offset;
@@ -19940,8 +19961,8 @@ function readString(block, offset, length) {
19940
19961
  return decoder6.decode(block.subarray(offset, end));
19941
19962
  }
19942
19963
  function readOctal(block, offset, length) {
19943
- const text = readString(block, offset, length).trim();
19944
- return text === "" ? 0 : parseInt(text, 8) || 0;
19964
+ const text2 = readString(block, offset, length).trim();
19965
+ return text2 === "" ? 0 : parseInt(text2, 8) || 0;
19945
19966
  }
19946
19967
  function createTar(entries) {
19947
19968
  const blocks = [];
@@ -20336,9 +20357,9 @@ var base64Cmd = defineCommand({
20336
20357
  const { sources, ok } = await readInputs(ctx, args.positional);
20337
20358
  for (const source of sources) {
20338
20359
  if (args.has("decode")) {
20339
- const text = new TextDecoder().decode(source.bytes).replace(/\s+/g, "");
20360
+ const text2 = new TextDecoder().decode(source.bytes).replace(/\s+/g, "");
20340
20361
  try {
20341
- ctx.write(new Uint8Array(Buffer.from(text, "base64")));
20362
+ ctx.write(new Uint8Array(Buffer.from(text2, "base64")));
20342
20363
  } catch {
20343
20364
  return ctx.fail("invalid input");
20344
20365
  }
@@ -20365,11 +20386,11 @@ var base32Cmd = defineCommand({
20365
20386
  const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
20366
20387
  for (const source of sources) {
20367
20388
  if (args.has("decode")) {
20368
- const text = new TextDecoder().decode(source.bytes).replace(/[\s=]/g, "").toUpperCase();
20389
+ const text2 = new TextDecoder().decode(source.bytes).replace(/[\s=]/g, "").toUpperCase();
20369
20390
  const out2 = [];
20370
20391
  let bits2 = 0;
20371
20392
  let value2 = 0;
20372
- for (const ch of text) {
20393
+ for (const ch of text2) {
20373
20394
  const idx = ALPHABET.indexOf(ch);
20374
20395
  if (idx < 0) continue;
20375
20396
  value2 = value2 << 5 | idx;
@@ -21412,8 +21433,8 @@ var man = defineCommand({
21412
21433
  return 0;
21413
21434
  }
21414
21435
  });
21415
- function capitalize(text) {
21416
- return text.length ? text[0].toUpperCase() + text.slice(1) : text;
21436
+ function capitalize(text2) {
21437
+ return text2.length ? text2[0].toUpperCase() + text2.slice(1) : text2;
21417
21438
  }
21418
21439
  var whatis = defineCommand({
21419
21440
  name: "whatis",
@@ -21578,7 +21599,8 @@ async function execute(ctx, invocation) {
21578
21599
  try {
21579
21600
  const proc = await pod.spawn("node", [invocation.script], {
21580
21601
  cwd: ctx.cwd,
21581
- env: { ...ctx.env, PWD: ctx.cwd }
21602
+ env: { ...ctx.env, PWD: ctx.cwd },
21603
+ argv: ["/usr/bin/node", invocation.argvPath ?? invocation.script, ...invocation.argv]
21582
21604
  });
21583
21605
  proc.on("output", (chunk) => {
21584
21606
  try {
@@ -21757,7 +21779,7 @@ Error: Cannot find module '${ctx.path(scriptArg)}'
21757
21779
  mode: 384
21758
21780
  });
21759
21781
  temps.push(sibling);
21760
- return await execute(ctx, { script: sibling, argv: scriptArgs, temps });
21782
+ return await execute(ctx, { script: sibling, argvPath: script, argv: scriptArgs, temps });
21761
21783
  } catch {
21762
21784
  return await execute(ctx, { script, argv: scriptArgs, temps });
21763
21785
  }
@@ -22158,6 +22180,8 @@ var RESERVED_FOR_INTERPRETER = /* @__PURE__ */ new Set(["lib", "dev", "proc"]);
22158
22180
  var pyodideModule = null;
22159
22181
  var indexUrl;
22160
22182
  var moduleUrl;
22183
+ var DEFAULT_BROWSER_INDEX_URL = "https://cdn.jsdelivr.net/pyodide/v0.28.3/full/";
22184
+ var isNode2 = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
22161
22185
  function configureCPython(options = {}) {
22162
22186
  if (options.indexURL !== void 0) indexUrl = options.indexURL;
22163
22187
  if (options.moduleURL !== void 0) {
@@ -22167,19 +22191,27 @@ function configureCPython(options = {}) {
22167
22191
  }
22168
22192
  function importPyodide() {
22169
22193
  if (!pyodideModule) {
22170
- const specifier = moduleUrl ?? ["py", "odide"].join("");
22171
- pyodideModule = import(
22172
- /* @vite-ignore */
22173
- /* webpackIgnore: true */
22174
- specifier
22175
- );
22194
+ if (moduleUrl) {
22195
+ pyodideModule = import(
22196
+ /* @vite-ignore */
22197
+ /* webpackIgnore: true */
22198
+ moduleUrl
22199
+ );
22200
+ } else if (isNode2) {
22201
+ pyodideModule = nodeOnlyModule("pyodide");
22202
+ } else {
22203
+ pyodideModule = import(
22204
+ /* @vite-ignore */
22205
+ /* webpackIgnore: true */
22206
+ `${DEFAULT_BROWSER_INDEX_URL}pyodide.mjs`
22207
+ );
22208
+ }
22176
22209
  }
22177
22210
  return pyodideModule;
22178
22211
  }
22179
- var isNode2 = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
22180
22212
  async function resolveIndexUrl() {
22181
22213
  if (indexUrl) return indexUrl;
22182
- if (!isNode2) return void 0;
22214
+ if (!isNode2) return DEFAULT_BROWSER_INDEX_URL;
22183
22215
  try {
22184
22216
  const { createRequire } = await nodeBuiltin("module");
22185
22217
  const path = await nodeBuiltin("path");
@@ -22304,8 +22336,8 @@ function reportError(ctx, error) {
22304
22336
  ctx.stderr.write("KeyboardInterrupt\n");
22305
22337
  return 130;
22306
22338
  }
22307
- const text = message.replace(/^PythonError:\s*/, "");
22308
- ctx.stderr.write(text.endsWith("\n") ? text : `${text}
22339
+ const text2 = message.replace(/^PythonError:\s*/, "");
22340
+ ctx.stderr.write(text2.endsWith("\n") ? text2 : `${text2}
22309
22341
  `);
22310
22342
  return 1;
22311
22343
  }
@@ -22330,7 +22362,7 @@ async function runCPythonProgram(ctx, source, argv, scriptDir, stdinText) {
22330
22362
  });
22331
22363
  } catch {
22332
22364
  }
22333
- const encoder6 = new TextEncoder();
22365
+ const encoder7 = new TextEncoder();
22334
22366
  const decoder7 = new TextDecoder();
22335
22367
  py.setStdout({
22336
22368
  write: (buffer) => {
@@ -22345,7 +22377,7 @@ async function runCPythonProgram(ctx, source, argv, scriptDir, stdinText) {
22345
22377
  }
22346
22378
  });
22347
22379
  if (stdinText !== null) {
22348
- const bytes = encoder6.encode(stdinText);
22380
+ const bytes = encoder7.encode(stdinText);
22349
22381
  let offset = 0;
22350
22382
  py.setStdin({
22351
22383
  read: (buffer) => {
@@ -22718,8 +22750,8 @@ function renameShadowedExports(source) {
22718
22750
  const replacement = freshName(source);
22719
22751
  let out = source;
22720
22752
  for (const target of [...targets].sort((a, b) => b.start - a.start)) {
22721
- const text = target.shorthand ? `${NAME}: ${replacement}` : replacement;
22722
- out = out.slice(0, target.start) + text + out.slice(target.end);
22753
+ const text2 = target.shorthand ? `${NAME}: ${replacement}` : replacement;
22754
+ out = out.slice(0, target.start) + text2 + out.slice(target.end);
22723
22755
  }
22724
22756
  return out;
22725
22757
  function visit(node2, scope) {
@@ -22938,11 +22970,11 @@ function splitPackageSpec(spec) {
22938
22970
  return { name: spec.slice(0, at), version: spec.slice(at + 1) };
22939
22971
  }
22940
22972
  async function installPackages(ctx, specs, opts) {
22941
- const installer = opts.cwd === "/" ? ctx.kernel.pod.packages : new DependencyInstaller(ctx.vfs.volume, { cwd: opts.cwd });
22973
+ const installer = opts.cwd === "/" ? ctx.kernel.pod.packages : ctx.kernel.pod.packages.forCwd?.(opts.cwd) ?? new DependencyInstaller(ctx.vfs.volume, { cwd: opts.cwd });
22942
22974
  const onProgress = (message) => {
22943
22975
  if (!opts.quiet) ctx.stderr.write(message.endsWith("\n") ? message : message + "\n");
22944
22976
  };
22945
- const note = (text) => opts.quiet ? ctx.stderr.write(text + "\n") : ctx.line(text);
22977
+ const note = (text2) => opts.quiet ? ctx.stderr.write(text2 + "\n") : ctx.line(text2);
22946
22978
  if (!ctx.kernel.net.options.allowOutbound) {
22947
22979
  ctx.warn("npm error code ENOTFOUND");
22948
22980
  ctx.warn("npm error network request to https://registry.npmjs.org failed");
@@ -22997,7 +23029,13 @@ var npm = defineCommand({
22997
23029
  case "version":
22998
23030
  ctx.line(NPM_VERSION);
22999
23031
  return 0;
23032
+ /* `npm create vite@latest` and `npm init vite` are the same command, and
23033
+ * both are `npx` against a conventionally-named package. Only a bare
23034
+ * `npm init` with no initializer writes a package.json. */
23035
+ case "create":
23036
+ return await runInitializer(ctx, rest);
23000
23037
  case "init": {
23038
+ if (rest[0] && !rest[0].startsWith("-")) return await runInitializer(ctx, rest);
23001
23039
  const existing = readManifest(ctx, ctx.cwd);
23002
23040
  if (existing && !rest.includes("-f") && !rest.includes("--force")) {
23003
23041
  ctx.warn("package.json already exists");
@@ -23179,9 +23217,9 @@ function normalizeBinDirectories(ctx, root) {
23179
23217
  const st = ctx.vfs.lstat(path);
23180
23218
  if (st.isDirectory()) continue;
23181
23219
  if (!st.isSymbolicLink()) {
23182
- const text = ctx.vfs.readText(path, ctx.cred);
23183
- if (!text.startsWith("#!")) {
23184
- ctx.vfs.writeFile(path, "#!/bin/sh\n" + text, { privileged: true, mode: 493 });
23220
+ const text2 = ctx.vfs.readText(path, ctx.cred);
23221
+ if (!text2.startsWith("#!")) {
23222
+ ctx.vfs.writeFile(path, "#!/bin/sh\n" + text2, { privileged: true, mode: 493 });
23185
23223
  }
23186
23224
  }
23187
23225
  ctx.vfs.chmod(path, 493, ctx.cred);
@@ -23247,6 +23285,26 @@ function findLocalBin(ctx, name) {
23247
23285
  }
23248
23286
  return null;
23249
23287
  }
23288
+ async function runInitializer(ctx, args) {
23289
+ const [spec, ...rest] = args;
23290
+ const { name, version } = splitPackageSpec(spec);
23291
+ const suffix = version ? `@${version}` : "";
23292
+ let packageName;
23293
+ if (!name.startsWith("@")) {
23294
+ packageName = `create-${name}`;
23295
+ } else if (name.includes("/")) {
23296
+ const [scope, unscoped2] = name.split("/");
23297
+ packageName = `${scope}/create-${unscoped2}`;
23298
+ } else {
23299
+ packageName = `${name}/create`;
23300
+ }
23301
+ const forwarded = rest.filter((argument) => argument !== "--");
23302
+ return await npx.run({
23303
+ ...ctx,
23304
+ args: ["-y", "--package", `${packageName}${suffix}`, basename(packageName), ...forwarded],
23305
+ argv: ["npx", ...forwarded]
23306
+ });
23307
+ }
23250
23308
  var npx = defineCommand({
23251
23309
  name: "npx",
23252
23310
  path: "/usr/bin/npx",
@@ -23691,16 +23749,16 @@ var Session = class {
23691
23749
  const combined = [];
23692
23750
  const decoder7 = new TextDecoder();
23693
23751
  const stdout = new BufferSink((chunk) => {
23694
- const text = decoder7.decode(chunk, { stream: true });
23695
- combined.push(text);
23696
- opts.onStdout?.(text);
23697
- this.hooks.onStdout?.(text);
23752
+ const text2 = decoder7.decode(chunk, { stream: true });
23753
+ combined.push(text2);
23754
+ opts.onStdout?.(text2);
23755
+ this.hooks.onStdout?.(text2);
23698
23756
  });
23699
23757
  const stderr = new BufferSink((chunk) => {
23700
- const text = decoder7.decode(chunk, { stream: true });
23701
- combined.push(text);
23702
- opts.onStderr?.(text);
23703
- this.hooks.onStderr?.(text);
23758
+ const text2 = decoder7.decode(chunk, { stream: true });
23759
+ combined.push(text2);
23760
+ opts.onStderr?.(text2);
23761
+ this.hooks.onStderr?.(text2);
23704
23762
  });
23705
23763
  if (opts.tty) {
23706
23764
  stdout.isTTY = true;
@@ -23836,9 +23894,9 @@ var KernelChildProcess = class {
23836
23894
  this.exitCode = code;
23837
23895
  this.emit("exit", code);
23838
23896
  }
23839
- append(stream, text) {
23840
- this[stream] += text;
23841
- this.emit(stream, text);
23897
+ append(stream, text2) {
23898
+ this[stream] += text2;
23899
+ this.emit(stream, text2);
23842
23900
  }
23843
23901
  };
23844
23902
  var ChildOutput = class {
@@ -23856,8 +23914,8 @@ var ChildOutput = class {
23856
23914
  }
23857
23915
  write(data) {
23858
23916
  if (this.closedState) return;
23859
- const text = typeof data === "string" ? data : this.decoder.decode(data, { stream: true });
23860
- if (text) this.child.append(this.stream, text);
23917
+ const text2 = typeof data === "string" ? data : this.decoder.decode(data, { stream: true });
23918
+ if (text2) this.child.append(this.stream, text2);
23861
23919
  }
23862
23920
  end() {
23863
23921
  if (this.closedState) return;
@@ -23883,6 +23941,3286 @@ function installNodeChildProcessBridge(pod, kernel, cred) {
23883
23941
  };
23884
23942
  }
23885
23943
 
23944
+ // src/runtime/commonjs-engine.ts
23945
+ init_path();
23946
+ var HELPERS = {
23947
+ /** Import a specifier and return an ES-module-shaped namespace. */
23948
+ import: "__sbxImport",
23949
+ /** `import(...)`, returning a promise of a namespace. */
23950
+ dynamic: "__sbxDynamicImport",
23951
+ /** `export * from` — copy live bindings onto `exports`. */
23952
+ exportAll: "__sbxExportAll",
23953
+ /** `import.meta`. */
23954
+ meta: "__sbxMeta",
23955
+ /**
23956
+ * The exports object, under a name of the engine's choosing.
23957
+ *
23958
+ * An ES module is free to declare its own top-level `exports`, `require` or
23959
+ * `__dirname` — they are ordinary identifiers there, and real packages use
23960
+ * all three (`const require = createRequire(import.meta.url)` is close to
23961
+ * idiomatic). Naming the wrapper's binding something no source would write
23962
+ * removes that entire class of collision instead of patching it up after a
23963
+ * `SyntaxError`.
23964
+ */
23965
+ exports: "__sbxExports"
23966
+ };
23967
+ var DEFAULT_LOCAL = "__sbxDefault";
23968
+ var MAYBE_ESM = /(^|[\s;}(])(?:import|export)(?:[\s({[*"']|$)|\bimport\s*\.\s*meta\b/;
23969
+ function looksLikeEsm(source) {
23970
+ return MAYBE_ESM.test(source);
23971
+ }
23972
+ function transformEsm(source, filename = "module.js") {
23973
+ if (!looksLikeEsm(source)) return null;
23974
+ let ast;
23975
+ try {
23976
+ ast = parseModule(source, filename);
23977
+ } catch {
23978
+ return null;
23979
+ }
23980
+ const body = ast.body;
23981
+ const hasModuleSyntax = body.some(
23982
+ (node2) => node2.type.startsWith("Import") || node2.type.startsWith("Export")
23983
+ );
23984
+ const usesImportMeta = !hasModuleSyntax && containsImportMeta(ast);
23985
+ const esm = hasModuleSyntax || usesImportMeta;
23986
+ if (!esm && !containsImportExpression(ast)) return null;
23987
+ const edits = [];
23988
+ const prelude = [];
23989
+ const importBindings = /* @__PURE__ */ new Map();
23990
+ const exportGetters = /* @__PURE__ */ new Map();
23991
+ let namespaceCount = 0;
23992
+ const namespaceFor = (specifier) => {
23993
+ const id = `__sbxNs${namespaceCount++}`;
23994
+ prelude.push(`var ${id} = ${HELPERS.import}(${JSON.stringify(specifier)});`);
23995
+ return id;
23996
+ };
23997
+ for (const node2 of body) {
23998
+ if (node2.type === "ImportDeclaration") collectImport(node2);
23999
+ }
24000
+ for (const node2 of body) {
24001
+ switch (node2.type) {
24002
+ case "ExportNamedDeclaration":
24003
+ collectNamedExport(node2);
24004
+ break;
24005
+ case "ExportDefaultDeclaration":
24006
+ collectDefaultExport(node2);
24007
+ break;
24008
+ case "ExportAllDeclaration":
24009
+ collectExportAll(node2);
24010
+ break;
24011
+ }
24012
+ }
24013
+ rewriteReferences();
24014
+ const header = esm ? [
24015
+ `Object.defineProperty(${HELPERS.exports}, "__esModule", { value: true });`,
24016
+ ...prelude,
24017
+ ...[...exportGetters].map(
24018
+ ([name, expression]) => `Object.defineProperty(${HELPERS.exports}, ${JSON.stringify(name)}, { enumerable: true, configurable: true, get: function () { return ${expression}; } });`
24019
+ )
24020
+ ].join("\n") : "";
24021
+ return {
24022
+ code: header ? `${header}
24023
+ ${applyEdits(source, edits)}` : applyEdits(source, edits),
24024
+ esm,
24025
+ topLevelAwait: hasTopLevelAwait(ast)
24026
+ };
24027
+ function collectImport(node2) {
24028
+ const specifier = node2.source.value;
24029
+ const specifiers = node2.specifiers ?? [];
24030
+ const id = namespaceFor(specifier);
24031
+ for (const entry of specifiers) {
24032
+ const local = entry.local.name ?? "";
24033
+ if (entry.type === "ImportDefaultSpecifier") {
24034
+ importBindings.set(local, `${id}.default`);
24035
+ } else if (entry.type === "ImportNamespaceSpecifier") {
24036
+ importBindings.set(local, id);
24037
+ } else {
24038
+ const imported = entry.imported;
24039
+ const name = imported.type === "Identifier" ? imported.name : imported.value;
24040
+ importBindings.set(local, `${id}[${JSON.stringify(name)}]`);
24041
+ }
24042
+ }
24043
+ drop(node2);
24044
+ }
24045
+ function collectNamedExport(node2) {
24046
+ const declaration = node2.declaration;
24047
+ if (declaration) {
24048
+ for (const name of declaredNames(declaration)) exportGetters.set(name, name);
24049
+ edits.push({ start: node2.start, end: declaration.start, text: "" });
24050
+ return;
24051
+ }
24052
+ const source_ = node2.source;
24053
+ const id = source_ ? namespaceFor(source_.value) : null;
24054
+ for (const entry of node2.specifiers ?? []) {
24055
+ const local = nameOf(entry.local);
24056
+ const exported = nameOf(entry.exported);
24057
+ const read = id ? `${id}[${JSON.stringify(local)}]` : importBindings.get(local) ?? local;
24058
+ exportGetters.set(exported, read);
24059
+ }
24060
+ drop(node2);
24061
+ }
24062
+ function collectDefaultExport(node2) {
24063
+ const declaration = node2.declaration;
24064
+ const isDeclaration = declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration";
24065
+ if (isDeclaration) {
24066
+ const named = declaration.id;
24067
+ if (named) {
24068
+ exportGetters.set("default", named.name);
24069
+ edits.push({ start: node2.start, end: declaration.start, text: "" });
24070
+ return;
24071
+ }
24072
+ const keyword = declaration.type === "FunctionDeclaration" ? "function" : "class";
24073
+ const keywordEnd = source.indexOf(keyword, declaration.start) + keyword.length;
24074
+ exportGetters.set("default", DEFAULT_LOCAL);
24075
+ edits.push({ start: node2.start, end: declaration.start, text: "" });
24076
+ edits.push({ start: keywordEnd, end: keywordEnd, text: ` ${DEFAULT_LOCAL}` });
24077
+ return;
24078
+ }
24079
+ exportGetters.set("default", DEFAULT_LOCAL);
24080
+ edits.push({ start: node2.start, end: declaration.start, text: `var ${DEFAULT_LOCAL} = ` });
24081
+ edits.push({ start: node2.end, end: node2.end, text: ";" });
24082
+ }
24083
+ function collectExportAll(node2) {
24084
+ const id = namespaceFor(node2.source.value);
24085
+ const exported = node2.exported;
24086
+ if (exported) exportGetters.set(nameOf(exported), id);
24087
+ else prelude.push(`${HELPERS.exportAll}(${HELPERS.exports}, ${id});`);
24088
+ drop(node2);
24089
+ }
24090
+ function drop(node2) {
24091
+ edits.push({ start: node2.start, end: node2.end, text: "" });
24092
+ }
24093
+ function rewriteReferences() {
24094
+ const programScope = { names: new Set(importBindings.keys()), parent: null };
24095
+ visit(ast, programScope, true);
24096
+ function visit(node2, scope, isProgram = false) {
24097
+ let childScope = scope;
24098
+ let skip = NOTHING2;
24099
+ switch (node2.type) {
24100
+ case "ImportDeclaration":
24101
+ case "ExportAllDeclaration":
24102
+ return;
24103
+ case "ExportNamedDeclaration":
24104
+ if (!node2.declaration) return;
24105
+ break;
24106
+ case "FunctionDeclaration":
24107
+ case "FunctionExpression":
24108
+ case "ArrowFunctionExpression": {
24109
+ const names = /* @__PURE__ */ new Set();
24110
+ for (const param of node2.params ?? []) collectPattern2(param, names);
24111
+ const id = node2.id;
24112
+ if (id && node2.type === "FunctionExpression") names.add(id.name);
24113
+ const fnBody = node2.body;
24114
+ if (fnBody?.type === "BlockStatement") {
24115
+ for (const name of hoistedNames2(fnBody.body)) names.add(name);
24116
+ }
24117
+ childScope = { names, parent: scope };
24118
+ break;
24119
+ }
24120
+ case "CatchClause": {
24121
+ const names = /* @__PURE__ */ new Set();
24122
+ if (node2.param) collectPattern2(node2.param, names);
24123
+ childScope = { names, parent: scope };
24124
+ break;
24125
+ }
24126
+ case "ClassExpression": {
24127
+ const id = node2.id;
24128
+ if (id) childScope = { names: /* @__PURE__ */ new Set([id.name]), parent: scope };
24129
+ break;
24130
+ }
24131
+ case "BlockStatement":
24132
+ case "StaticBlock":
24133
+ if (!isProgram) {
24134
+ childScope = { names: blockNames2(node2.body), parent: scope };
24135
+ }
24136
+ break;
24137
+ case "ForStatement":
24138
+ case "ForInStatement":
24139
+ case "ForOfStatement": {
24140
+ const head2 = node2.init ?? node2.left;
24141
+ if (head2?.type === "VariableDeclaration" && head2.kind !== "var") {
24142
+ const names = /* @__PURE__ */ new Set();
24143
+ for (const declarator of head2.declarations) {
24144
+ collectPattern2(declarator.id, names);
24145
+ }
24146
+ childScope = { names, parent: scope };
24147
+ }
24148
+ break;
24149
+ }
24150
+ case "MetaProperty":
24151
+ edits.push({ start: node2.start, end: node2.end, text: HELPERS.meta });
24152
+ return;
24153
+ case "ImportExpression": {
24154
+ const argument = node2.source;
24155
+ edits.push({ start: node2.start, end: argument.start, text: `${HELPERS.dynamic}(` });
24156
+ visit(argument, childScope);
24157
+ edits.push({ start: argument.end, end: node2.end, text: ")" });
24158
+ return;
24159
+ }
24160
+ case "Identifier": {
24161
+ const replacement = lookup(node2.name, scope);
24162
+ if (replacement) edits.push({ start: node2.start, end: node2.end, text: replacement });
24163
+ return;
24164
+ }
24165
+ case "MemberExpression":
24166
+ case "MethodDefinition":
24167
+ case "PropertyDefinition":
24168
+ skip = node2.computed ? NOTHING2 : PROPERTY2;
24169
+ break;
24170
+ case "Property": {
24171
+ if (node2.computed) break;
24172
+ if (node2.shorthand) {
24173
+ const value = node2.value;
24174
+ if (value.type === "Identifier") {
24175
+ const replacement = lookup(value.name, scope);
24176
+ if (replacement) {
24177
+ edits.push({ start: value.start, end: value.end, text: `${value.name}: ${replacement}` });
24178
+ return;
24179
+ }
24180
+ }
24181
+ break;
24182
+ }
24183
+ skip = PROPERTY2;
24184
+ break;
24185
+ }
24186
+ case "LabeledStatement":
24187
+ case "BreakStatement":
24188
+ case "ContinueStatement":
24189
+ skip = LABEL2;
24190
+ break;
24191
+ }
24192
+ for (const [key, value] of Object.entries(node2)) {
24193
+ if (key === "type" || key === "start" || key === "end" || skip.includes(key)) continue;
24194
+ if (Array.isArray(value)) {
24195
+ for (const item of value) if (isNode4(item)) visit(item, childScope);
24196
+ } else if (isNode4(value)) {
24197
+ visit(value, childScope);
24198
+ }
24199
+ }
24200
+ }
24201
+ function lookup(name, scope) {
24202
+ for (let current = scope; current; current = current.parent) {
24203
+ if (current.names.has(name)) {
24204
+ return current.parent === null ? importBindings.get(name) ?? null : null;
24205
+ }
24206
+ }
24207
+ return null;
24208
+ }
24209
+ }
24210
+ }
24211
+ var JSX_EXTENSION = /\.[jt]sx$/;
24212
+ var JsxParser = Parser$1.extend(jsx());
24213
+ var PARSE_OPTIONS = {
24214
+ ecmaVersion: "latest",
24215
+ sourceType: "module",
24216
+ allowAwaitOutsideFunction: true,
24217
+ allowHashBang: true,
24218
+ allowReturnOutsideFunction: true
24219
+ };
24220
+ function parseModule(source, filename) {
24221
+ const parser = JSX_EXTENSION.test(filename) ? JsxParser.parse.bind(JsxParser) : parse$1;
24222
+ return parser(source, PARSE_OPTIONS);
24223
+ }
24224
+ function containsImportExpression(node2) {
24225
+ if (Array.isArray(node2)) return node2.some(containsImportExpression);
24226
+ if (!isNode4(node2)) return false;
24227
+ if (node2.type === "ImportExpression") return true;
24228
+ for (const [key, value] of Object.entries(node2)) {
24229
+ if (key === "type" || key === "start" || key === "end") continue;
24230
+ if (containsImportExpression(value)) return true;
24231
+ }
24232
+ return false;
24233
+ }
24234
+ function containsImportMeta(node2) {
24235
+ if (Array.isArray(node2)) return node2.some(containsImportMeta);
24236
+ if (!isNode4(node2)) return false;
24237
+ if (node2.type === "MetaProperty") return true;
24238
+ for (const [key, value] of Object.entries(node2)) {
24239
+ if (key === "type" || key === "start" || key === "end") continue;
24240
+ if (containsImportMeta(value)) return true;
24241
+ }
24242
+ return false;
24243
+ }
24244
+ function hasTopLevelAwait(node2) {
24245
+ if (Array.isArray(node2)) return node2.some(hasTopLevelAwait);
24246
+ if (!isNode4(node2)) return false;
24247
+ if (node2.type === "FunctionDeclaration" || node2.type === "FunctionExpression" || node2.type === "ArrowFunctionExpression") {
24248
+ return false;
24249
+ }
24250
+ if (node2.type === "AwaitExpression") return true;
24251
+ if (node2.type === "ForOfStatement" && node2.await === true) return true;
24252
+ for (const [key, value] of Object.entries(node2)) {
24253
+ if (key === "type" || key === "start" || key === "end") continue;
24254
+ if (hasTopLevelAwait(value)) return true;
24255
+ }
24256
+ return false;
24257
+ }
24258
+ function declaredNames(declaration) {
24259
+ const names = /* @__PURE__ */ new Set();
24260
+ if (declaration.type === "VariableDeclaration") {
24261
+ for (const declarator of declaration.declarations) {
24262
+ collectPattern2(declarator.id, names);
24263
+ }
24264
+ } else if (isNode4(declaration.id)) {
24265
+ names.add(declaration.id.name);
24266
+ }
24267
+ return [...names];
24268
+ }
24269
+ function nameOf(node2) {
24270
+ return node2.type === "Identifier" ? node2.name : node2.value;
24271
+ }
24272
+ function hoistedNames2(body) {
24273
+ const names = blockNames2(body);
24274
+ collectVars2(body, names);
24275
+ return names;
24276
+ }
24277
+ function blockNames2(body) {
24278
+ const names = /* @__PURE__ */ new Set();
24279
+ for (const node2 of body ?? []) {
24280
+ if (node2.type === "VariableDeclaration" && node2.kind !== "var") {
24281
+ for (const declarator of node2.declarations) {
24282
+ collectPattern2(declarator.id, names);
24283
+ }
24284
+ } else if ((node2.type === "ClassDeclaration" || node2.type === "FunctionDeclaration") && isNode4(node2.id)) {
24285
+ names.add(node2.id.name);
24286
+ }
24287
+ }
24288
+ return names;
24289
+ }
24290
+ function collectVars2(nodes, names) {
24291
+ if (Array.isArray(nodes)) {
24292
+ for (const item of nodes) collectVars2(item, names);
24293
+ return;
24294
+ }
24295
+ if (!isNode4(nodes)) return;
24296
+ const node2 = nodes;
24297
+ if (node2.type === "FunctionDeclaration" || node2.type === "FunctionExpression" || node2.type === "ArrowFunctionExpression") {
24298
+ if (isNode4(node2.id)) names.add(node2.id.name);
24299
+ return;
24300
+ }
24301
+ if (node2.type === "VariableDeclaration" && node2.kind === "var") {
24302
+ for (const declarator of node2.declarations) {
24303
+ collectPattern2(declarator.id, names);
24304
+ }
24305
+ }
24306
+ for (const [key, value] of Object.entries(node2)) {
24307
+ if (key === "type" || key === "start" || key === "end") continue;
24308
+ collectVars2(value, names);
24309
+ }
24310
+ }
24311
+ function collectPattern2(node2, names) {
24312
+ if (!isNode4(node2)) return;
24313
+ switch (node2.type) {
24314
+ case "Identifier":
24315
+ names.add(node2.name);
24316
+ return;
24317
+ case "ObjectPattern":
24318
+ for (const property of node2.properties) {
24319
+ collectPattern2(property.value ?? property.argument, names);
24320
+ }
24321
+ return;
24322
+ case "ArrayPattern":
24323
+ for (const element of node2.elements) collectPattern2(element, names);
24324
+ return;
24325
+ case "AssignmentPattern":
24326
+ collectPattern2(node2.left, names);
24327
+ return;
24328
+ case "RestElement":
24329
+ collectPattern2(node2.argument, names);
24330
+ return;
24331
+ default:
24332
+ return;
24333
+ }
24334
+ }
24335
+ function applyEdits(source, edits) {
24336
+ const ordered = [...edits].sort((a, b) => b.start - a.start || b.end - a.end);
24337
+ let out = source;
24338
+ for (const edit of ordered) out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
24339
+ return out;
24340
+ }
24341
+ function isNode4(value) {
24342
+ return typeof value === "object" && value !== null && typeof value.type === "string";
24343
+ }
24344
+ var NOTHING2 = [];
24345
+ var PROPERTY2 = ["property", "key"];
24346
+ var LABEL2 = ["label"];
24347
+ var EXTENSIONS = [".js", ".mjs", ".cjs", ".json", ".node"];
24348
+ var CONDITION_SETS = {
24349
+ import: [["node", "import", "module", "default"], ["node", "require", "default"], ["default"]],
24350
+ require: [["node", "require", "default"], ["node", "import", "module", "default"], ["default"]]
24351
+ };
24352
+ var ENTRY_FIELDS = {
24353
+ import: ["module", "main"],
24354
+ require: ["main", "module"]
24355
+ };
24356
+ var CommonJsEngine = class {
24357
+ constructor(volume, options = {}) {
24358
+ this.volume = volume;
24359
+ this.cwd = options.cwd ?? "/";
24360
+ this.builtins = { ...options.builtins };
24361
+ this.globals = { ...options.globals };
24362
+ this.aliases = { ...options.aliases };
24363
+ this.overrides = { ...options.overrides };
24364
+ }
24365
+ volume;
24366
+ cache = /* @__PURE__ */ new Map();
24367
+ builtins;
24368
+ globals;
24369
+ aliases;
24370
+ overrides;
24371
+ cwd;
24372
+ main = null;
24373
+ /** `package.json` per directory; resolution reads them constantly. */
24374
+ manifests = /* @__PURE__ */ new Map();
24375
+ /**
24376
+ * Evaluate an entry point.
24377
+ *
24378
+ * Returns the module's exports, or a promise for them when the entry is an
24379
+ * ES module with a top-level `await` — the caller has to await that before
24380
+ * treating the program as finished.
24381
+ */
24382
+ run(entry) {
24383
+ const operand = entry.startsWith("/") || entry.startsWith("./") || entry.startsWith("../") ? entry : `./${entry}`;
24384
+ const filename = this.resolve(operand, join(this.cwd, "__entry__.js"));
24385
+ const module = this.load(filename, null, true);
24386
+ return module.pending ? module.pending.then(() => module.exports) : module.exports;
24387
+ }
24388
+ require(specifier, importer = join(this.cwd, "__entry__.js")) {
24389
+ const builtin = this.builtin(specifier);
24390
+ if (builtin.found) return builtin.value;
24391
+ const target = this.load(this.resolve(specifier, importer), this.cache.get(importer) ?? null, false);
24392
+ if (target.pending) throw requireOfAsyncModule(specifier);
24393
+ return target.exports;
24394
+ }
24395
+ resolve(specifier, importer, kind = "require") {
24396
+ const builtin = this.builtin(specifier);
24397
+ if (builtin.found) return specifier.replace(/^node:/, "");
24398
+ if (specifier.startsWith("#")) {
24399
+ const found = this.resolveImports(specifier, importer, kind);
24400
+ if (found) return found;
24401
+ throw this.moduleNotFound(specifier, importer);
24402
+ }
24403
+ const baseDir = dirname(importer);
24404
+ if (specifier.startsWith("/") || specifier.startsWith("./") || specifier.startsWith("../")) {
24405
+ const resolved = specifier.startsWith("/") ? clean(specifier) : resolve(baseDir, specifier);
24406
+ const found = this.resolvePath(resolved, kind);
24407
+ if (found) return found;
24408
+ } else {
24409
+ const aliased = this.aliasFor(specifier);
24410
+ if (aliased) {
24411
+ const substituted = this.resolvePackage(aliased, baseDir, kind);
24412
+ if (substituted) return substituted;
24413
+ }
24414
+ const found = this.resolvePackage(specifier, baseDir, kind);
24415
+ if (found) return found;
24416
+ }
24417
+ throw this.moduleNotFound(specifier, importer);
24418
+ }
24419
+ load(filename, parent, isMain) {
24420
+ const cached2 = this.cache.get(filename);
24421
+ if (cached2) return cached2;
24422
+ const module = {
24423
+ id: isMain ? "." : filename,
24424
+ filename,
24425
+ exports: {},
24426
+ loaded: false,
24427
+ parent,
24428
+ children: []
24429
+ };
24430
+ this.cache.set(filename, module);
24431
+ parent?.children.push(module);
24432
+ if (isMain) this.main = module;
24433
+ try {
24434
+ if (filename.endsWith(".node")) {
24435
+ throw dlopenFailed(filename);
24436
+ } else if (filename.endsWith(".json")) {
24437
+ module.exports = JSON.parse(this.readText(filename));
24438
+ } else {
24439
+ this.evaluate(module, this.readText(filename));
24440
+ }
24441
+ module.loaded = true;
24442
+ return module;
24443
+ } catch (error) {
24444
+ this.cache.delete(filename);
24445
+ if (isMain) this.main = null;
24446
+ throw error;
24447
+ }
24448
+ }
24449
+ evaluate(module, source) {
24450
+ if (source.startsWith("#!")) source = source.replace(/^#![^\n]*(?:\n|$)/, "");
24451
+ const transformed = transformEsm(source, module.filename);
24452
+ const body = transformed?.code ?? source;
24453
+ const code = transformed?.topLevelAwait ? `return (async () => {
24454
+ ${body}
24455
+ })();` : body;
24456
+ const helpers = [
24457
+ [HELPERS.import, (specifier) => this.importNamespace(specifier, module)],
24458
+ [HELPERS.dynamic, (specifier) => this.dynamicImport(specifier, module)],
24459
+ [HELPERS.exportAll, exportAll],
24460
+ [HELPERS.meta, this.importMeta(module)]
24461
+ ];
24462
+ const bindings = transformed?.esm ? [[HELPERS.exports, module.exports], ...helpers] : [
24463
+ ["exports", module.exports],
24464
+ ["require", this.makeRequire(module)],
24465
+ ["module", module],
24466
+ ["__filename", module.filename],
24467
+ ["__dirname", dirname(module.filename)],
24468
+ ...helpers
24469
+ ];
24470
+ const globalNames = Object.keys(this.globals);
24471
+ const factory = new Function(
24472
+ "__sbxGlobals",
24473
+ `"use strict";
24474
+ ` + (globalNames.length ? `const { ${globalNames.join(", ")} } = __sbxGlobals;
24475
+ ` : "") + `return function (${bindings.map(([name]) => name).join(", ")}) {
24476
+ ${code}
24477
+ };
24478
+ //# sourceURL=sandboxedjs:${module.filename}`
24479
+ )(this.globals);
24480
+ const result = factory(...bindings.map(([, value]) => value));
24481
+ if (transformed?.topLevelAwait) module.pending = Promise.resolve(result).then(() => {
24482
+ });
24483
+ }
24484
+ /** The `require` a module sees, complete with `resolve`, `cache` and `main`. */
24485
+ makeRequire(module) {
24486
+ const localRequire = ((specifier) => {
24487
+ const builtin = this.builtin(specifier, module);
24488
+ if (builtin.found) return builtin.value;
24489
+ const target = this.load(this.resolve(specifier, module.filename, "require"), module, false);
24490
+ if (target.pending) throw requireOfAsyncModule(specifier);
24491
+ return target.exports;
24492
+ });
24493
+ localRequire.resolve = (specifier) => this.resolve(specifier, module.filename, "require");
24494
+ Object.defineProperty(localRequire, "main", { get: () => this.main });
24495
+ localRequire.cache = Object.fromEntries(this.cache);
24496
+ return localRequire;
24497
+ }
24498
+ /**
24499
+ * Load `specifier` and present it as an ES module namespace.
24500
+ *
24501
+ * A static `import` is synchronous here, exactly as the CommonJS `require`
24502
+ * it compiles down to. That is the one place this engine knowingly differs
24503
+ * from Node's real ESM semantics, and it is the trade that lets both module
24504
+ * systems share a single cache and resolver.
24505
+ */
24506
+ importNamespace(specifier, importer) {
24507
+ const builtin = this.builtin(specifier, importer);
24508
+ if (builtin.found) return namespaceOf(builtin.value);
24509
+ const target = this.load(this.resolve(specifier, importer.filename, "import"), importer, false);
24510
+ if (target.pending) throw requireOfAsyncModule(specifier);
24511
+ return namespaceOf(target.exports);
24512
+ }
24513
+ /** `import(...)`: the same load, but able to await a top-level `await`. */
24514
+ async dynamicImport(specifier, importer) {
24515
+ const builtin = this.builtin(specifier, importer);
24516
+ if (builtin.found) return namespaceOf(builtin.value);
24517
+ const target = this.load(this.resolve(specifier, importer.filename, "import"), importer, false);
24518
+ if (target.pending) await target.pending;
24519
+ return namespaceOf(target.exports);
24520
+ }
24521
+ /** `import.meta` for a module. */
24522
+ importMeta(module) {
24523
+ return {
24524
+ url: fileUrl(module.filename),
24525
+ filename: module.filename,
24526
+ dirname: dirname(module.filename),
24527
+ resolve: (specifier) => fileUrl(this.resolve(specifier, module.filename, "import"))
24528
+ };
24529
+ }
24530
+ /**
24531
+ * The substituted specifier for `specifier`, or null when none applies.
24532
+ *
24533
+ * An alias names a package, so a subpath rides along: aliasing `rollup` also
24534
+ * redirects `rollup/dist/native.js` into the substitute.
24535
+ */
24536
+ aliasFor(specifier) {
24537
+ const { name, subpath } = splitSpecifier(specifier);
24538
+ const target = this.aliases[name];
24539
+ if (!target) return null;
24540
+ return subpath ? `${target}/${subpath}` : target;
24541
+ }
24542
+ /**
24543
+ * Resolve a bare specifier (`pkg`, `@scope/pkg`, `pkg/sub`) by walking
24544
+ * `node_modules` up from the importer, exactly as Node does.
24545
+ */
24546
+ resolvePackage(specifier, from, kind) {
24547
+ const { name, subpath } = splitSpecifier(specifier);
24548
+ for (let dir3 = from; ; dir3 = dirname(dir3)) {
24549
+ const root = join(dir3, "node_modules", name);
24550
+ if (this.isDirectory(root)) {
24551
+ const resolved = this.resolveInPackage(root, subpath, kind);
24552
+ if (resolved) return resolved;
24553
+ }
24554
+ if (dir3 === "/") return null;
24555
+ }
24556
+ }
24557
+ /**
24558
+ * Resolve `subpath` ("" for the package root) inside an installed package.
24559
+ *
24560
+ * An `exports` map, when present, is authoritative: Node refuses paths it
24561
+ * does not name, and packages rely on that to keep their internals private.
24562
+ * Only a package without one falls back to `main`/`module` and to treating
24563
+ * the subpath as a plain file path.
24564
+ */
24565
+ resolveInPackage(root, subpath, kind) {
24566
+ const manifest = this.readManifest(root);
24567
+ const entry = subpath ? `./${subpath}` : ".";
24568
+ if (manifest?.exports !== void 0) {
24569
+ for (const conditions of CONDITION_SETS[kind]) {
24570
+ let targets;
24571
+ try {
24572
+ targets = exports$1(manifest, entry, { conditions, unsafe: true });
24573
+ } catch {
24574
+ continue;
24575
+ }
24576
+ for (const target of targets ?? []) {
24577
+ const found = this.resolvePath(resolve(root, target), kind);
24578
+ if (found) return found;
24579
+ }
24580
+ }
24581
+ return null;
24582
+ }
24583
+ if (subpath) return this.resolvePath(join(root, subpath), kind);
24584
+ for (const field of ENTRY_FIELDS[kind]) {
24585
+ const value = manifest?.[field];
24586
+ if (typeof value === "string") {
24587
+ const found = this.resolvePath(resolve(root, value), kind);
24588
+ if (found) return found;
24589
+ }
24590
+ }
24591
+ return this.resolveIndex(root);
24592
+ }
24593
+ /**
24594
+ * Resolve a `#private` specifier through the importing package's `imports`
24595
+ * map, which is scoped to the nearest enclosing package rather than to
24596
+ * `node_modules`.
24597
+ */
24598
+ resolveImports(specifier, from, kind) {
24599
+ const root = this.packageRoot(from);
24600
+ if (!root) return null;
24601
+ const manifest = this.readManifest(root);
24602
+ if (!manifest?.imports) return null;
24603
+ for (const conditions of CONDITION_SETS[kind]) {
24604
+ let targets;
24605
+ try {
24606
+ targets = imports(manifest, specifier, { conditions, unsafe: true });
24607
+ } catch {
24608
+ continue;
24609
+ }
24610
+ for (const target of targets ?? []) {
24611
+ const found = target.startsWith(".") ? this.resolvePath(resolve(root, target), kind) : this.resolvePackage(target, root, kind);
24612
+ if (found) return found;
24613
+ }
24614
+ }
24615
+ return null;
24616
+ }
24617
+ /** Resolve a path to a file, trying Node's extension and index fallbacks. */
24618
+ resolvePath(path, kind = "require") {
24619
+ if (this.isFile(path)) return path;
24620
+ for (const extension of EXTENSIONS) {
24621
+ const candidate = `${path}${extension}`;
24622
+ if (this.isFile(candidate)) return candidate;
24623
+ }
24624
+ if (!this.isDirectory(path)) return null;
24625
+ const manifest = this.readManifest(path);
24626
+ for (const field of ENTRY_FIELDS[kind]) {
24627
+ const value = manifest?.[field];
24628
+ if (typeof value !== "string") continue;
24629
+ const target = resolve(path, value);
24630
+ if (this.isFile(target)) return target;
24631
+ for (const extension of EXTENSIONS) {
24632
+ if (this.isFile(`${target}${extension}`)) return `${target}${extension}`;
24633
+ }
24634
+ const nested = this.resolveIndex(target);
24635
+ if (nested) return nested;
24636
+ }
24637
+ return this.resolveIndex(path);
24638
+ }
24639
+ resolveIndex(dir3) {
24640
+ for (const extension of EXTENSIONS) {
24641
+ const candidate = join(dir3, `index${extension}`);
24642
+ if (this.isFile(candidate)) return candidate;
24643
+ }
24644
+ return null;
24645
+ }
24646
+ /** The nearest ancestor directory holding a `package.json`. */
24647
+ packageRoot(from) {
24648
+ for (let dir3 = dirname(from); ; dir3 = dirname(dir3)) {
24649
+ if (this.isFile(join(dir3, "package.json"))) return dir3;
24650
+ if (dir3 === "/") return null;
24651
+ }
24652
+ }
24653
+ readManifest(root) {
24654
+ const cached2 = this.manifests.get(root);
24655
+ if (cached2 !== void 0) return cached2;
24656
+ let manifest = null;
24657
+ try {
24658
+ manifest = JSON.parse(this.readText(join(root, "package.json")));
24659
+ } catch {
24660
+ }
24661
+ this.manifests.set(root, manifest);
24662
+ return manifest;
24663
+ }
24664
+ builtin(specifier, importer) {
24665
+ const name = specifier.replace(/^node:/, "");
24666
+ if (!Object.prototype.hasOwnProperty.call(this.builtins, name)) {
24667
+ return Object.prototype.hasOwnProperty.call(this.overrides, specifier) ? { found: true, value: this.overrides[specifier] } : { found: false, value: void 0 };
24668
+ }
24669
+ if (name === "module" && importer) {
24670
+ return {
24671
+ found: true,
24672
+ value: { ...this.builtins.module, createRequire: () => this.makeRequire(importer) }
24673
+ };
24674
+ }
24675
+ return { found: true, value: this.builtins[name] };
24676
+ }
24677
+ exists(path) {
24678
+ try {
24679
+ this.volume.lstatSync(path);
24680
+ return true;
24681
+ } catch {
24682
+ return false;
24683
+ }
24684
+ }
24685
+ isFile(path) {
24686
+ try {
24687
+ return this.volume.lstatSync(path).isFile();
24688
+ } catch {
24689
+ return false;
24690
+ }
24691
+ }
24692
+ isDirectory(path) {
24693
+ try {
24694
+ return this.volume.lstatSync(path).isDirectory();
24695
+ } catch {
24696
+ return false;
24697
+ }
24698
+ }
24699
+ readText(path) {
24700
+ return new TextDecoder().decode(this.volume.readFileSync(path));
24701
+ }
24702
+ moduleNotFound(specifier, importer) {
24703
+ const error = new Error(`Cannot find module '${specifier}'
24704
+ Require stack:
24705
+ - ${importer}`);
24706
+ error.code = "MODULE_NOT_FOUND";
24707
+ return error;
24708
+ }
24709
+ };
24710
+ var namespaces = /* @__PURE__ */ new WeakMap();
24711
+ function namespaceOf(exports) {
24712
+ if (exports === null || typeof exports !== "object" && typeof exports !== "function") {
24713
+ return { default: exports, __esModule: true };
24714
+ }
24715
+ const target = exports;
24716
+ if (target.__esModule) return target;
24717
+ const cached2 = namespaces.get(target);
24718
+ if (cached2) return cached2;
24719
+ const namespace = {};
24720
+ for (const key of ownKeys(target)) {
24721
+ if (key === "default" || key === "__esModule") continue;
24722
+ Object.defineProperty(namespace, key, {
24723
+ enumerable: true,
24724
+ configurable: true,
24725
+ get: () => target[key]
24726
+ });
24727
+ }
24728
+ Object.defineProperty(namespace, "default", { enumerable: true, configurable: true, value: target });
24729
+ Object.defineProperty(namespace, "__esModule", { value: true });
24730
+ namespaces.set(target, namespace);
24731
+ return namespace;
24732
+ }
24733
+ function exportAll(exports, namespace) {
24734
+ if (namespace === null || typeof namespace !== "object") return;
24735
+ const source = namespace;
24736
+ for (const key of ownKeys(source)) {
24737
+ if (key === "default" || key === "__esModule") continue;
24738
+ if (Object.prototype.hasOwnProperty.call(exports, key)) continue;
24739
+ Object.defineProperty(exports, key, {
24740
+ enumerable: true,
24741
+ configurable: true,
24742
+ get: () => source[key]
24743
+ });
24744
+ }
24745
+ }
24746
+ function ownKeys(target) {
24747
+ const keys = [];
24748
+ for (const key of Object.getOwnPropertyNames(target)) {
24749
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
24750
+ if (descriptor?.enumerable) keys.push(key);
24751
+ }
24752
+ return keys;
24753
+ }
24754
+ function fileUrl(path) {
24755
+ return `file://${path.split("/").map(encodeURIComponent).join("/")}`;
24756
+ }
24757
+ function dlopenFailed(filename) {
24758
+ const error = new Error(
24759
+ `Cannot load '${filename}': it is a compiled native addon, which the sandboxed runtime cannot execute. A pure-JavaScript or WebAssembly build of the package is needed instead.`
24760
+ );
24761
+ error.code = "ERR_DLOPEN_FAILED";
24762
+ return error;
24763
+ }
24764
+ function requireOfAsyncModule(specifier) {
24765
+ const error = new Error(
24766
+ `require() cannot load ES module '${specifier}': it uses top-level await. Use import() instead.`
24767
+ );
24768
+ error.code = "ERR_REQUIRE_ASYNC_MODULE";
24769
+ return error;
24770
+ }
24771
+ function splitSpecifier(specifier) {
24772
+ const parts = specifier.split("/");
24773
+ const size = specifier.startsWith("@") ? 2 : 1;
24774
+ return { name: parts.slice(0, size).join("/"), subpath: parts.slice(size).join("/") };
24775
+ }
24776
+
24777
+ // src/runtime/core-modules.ts
24778
+ init_path();
24779
+ var VirtualIncomingMessage = class extends streamModule3.Readable {
24780
+ method;
24781
+ url;
24782
+ headers;
24783
+ rawHeaders;
24784
+ httpVersion = "1.1";
24785
+ httpVersionMajor = 1;
24786
+ httpVersionMinor = 1;
24787
+ complete = true;
24788
+ socket = socketStub();
24789
+ connection = this.socket;
24790
+ constructor(init) {
24791
+ super();
24792
+ this.method = (init.method ?? "GET").toUpperCase();
24793
+ this.url = init.path ?? "/";
24794
+ const body = init.body == null ? new Uint8Array() : typeof init.body === "string" ? new TextEncoder().encode(init.body) : init.body instanceof ArrayBuffer ? new Uint8Array(init.body) : init.body;
24795
+ this.headers = Object.fromEntries(Object.entries(init.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
24796
+ if (body.length && this.headers["content-length"] === void 0 && this.headers["transfer-encoding"] === void 0) {
24797
+ this.headers["content-length"] = String(body.length);
24798
+ }
24799
+ this.rawHeaders = Object.entries(this.headers).flatMap(([key, value]) => [key, value]);
24800
+ if (body.length) this.push(Buffer$1.from(body));
24801
+ this.push(null);
24802
+ }
24803
+ _read() {
24804
+ }
24805
+ setTimeout(_milliseconds, callback) {
24806
+ if (callback) this.once("timeout", callback);
24807
+ return this;
24808
+ }
24809
+ };
24810
+ var VirtualServerResponse = class extends streamModule3.Writable {
24811
+ statusCode = 200;
24812
+ statusMessage = "OK";
24813
+ headersSent = false;
24814
+ sendDate = true;
24815
+ req;
24816
+ socket = socketStub();
24817
+ connection = this.socket;
24818
+ headers = /* @__PURE__ */ new Map();
24819
+ chunks = [];
24820
+ resolve;
24821
+ completed;
24822
+ constructor(request) {
24823
+ super();
24824
+ this.req = request;
24825
+ this.completed = new Promise((resolve2) => {
24826
+ this.resolve = resolve2;
24827
+ });
24828
+ }
24829
+ _write(chunk, encoding, callback) {
24830
+ this.headersSent = true;
24831
+ this.chunks.push(Buffer$1.isBuffer(chunk) ? chunk : Buffer$1.from(chunk, encoding));
24832
+ callback();
24833
+ }
24834
+ _final(callback) {
24835
+ this.headersSent = true;
24836
+ if (this.sendDate && !this.hasHeader("date")) this.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString());
24837
+ const headers = {};
24838
+ for (const { name, value } of this.headers.values()) headers[name] = Array.isArray(value) ? value.join(", ") : value;
24839
+ this.resolve({
24840
+ statusCode: this.statusCode,
24841
+ statusMessage: this.statusMessage || STATUS_CODES[this.statusCode] || "",
24842
+ headers,
24843
+ body: new Uint8Array(Buffer$1.concat(this.chunks))
24844
+ });
24845
+ callback();
24846
+ }
24847
+ setHeader(name, value) {
24848
+ validateHeaderName(name);
24849
+ validateHeaderValue(name, value);
24850
+ this.headers.set(name.toLowerCase(), { name, value: Array.isArray(value) ? [...value].map(String) : String(value) });
24851
+ return this;
24852
+ }
24853
+ appendHeader(name, value) {
24854
+ const current = this.getHeader(name);
24855
+ const next = Array.isArray(value) ? [...value] : [String(value)];
24856
+ return this.setHeader(name, current === void 0 ? next : [...Array.isArray(current) ? current : [String(current)], ...next]);
24857
+ }
24858
+ getHeader(name) {
24859
+ return this.headers.get(name.toLowerCase())?.value;
24860
+ }
24861
+ getHeaders() {
24862
+ return Object.fromEntries([...this.headers].map(([key, entry]) => [key, entry.value]));
24863
+ }
24864
+ getHeaderNames() {
24865
+ return [...this.headers.keys()];
24866
+ }
24867
+ hasHeader(name) {
24868
+ return this.headers.has(name.toLowerCase());
24869
+ }
24870
+ removeHeader(name) {
24871
+ this.headers.delete(name.toLowerCase());
24872
+ }
24873
+ writeHead(statusCode, statusMessage, headers) {
24874
+ this.statusCode = statusCode;
24875
+ if (typeof statusMessage === "string") this.statusMessage = statusMessage;
24876
+ const values = (typeof statusMessage === "object" ? statusMessage : headers) ?? {};
24877
+ for (const [name, value] of Object.entries(values)) if (value !== void 0) this.setHeader(name, value);
24878
+ this.headersSent = true;
24879
+ return this;
24880
+ }
24881
+ flushHeaders() {
24882
+ this.headersSent = true;
24883
+ }
24884
+ writeContinue() {
24885
+ }
24886
+ writeProcessing() {
24887
+ }
24888
+ addTrailers(_headers) {
24889
+ }
24890
+ setTimeout(_milliseconds, callback) {
24891
+ if (callback) this.once("timeout", callback);
24892
+ return this;
24893
+ }
24894
+ };
24895
+ var VirtualHttpServer = class extends EventEmitter3 {
24896
+ constructor(router, owner, listener) {
24897
+ super();
24898
+ this.router = router;
24899
+ this.owner = owner;
24900
+ if (listener) this.on("request", listener);
24901
+ }
24902
+ router;
24903
+ owner;
24904
+ listening = false;
24905
+ portValue = null;
24906
+ listen(...args) {
24907
+ const callback = typeof args.at(-1) === "function" ? args.pop() : void 0;
24908
+ const first = args[0];
24909
+ const port = typeof first === "object" ? Number(first.port) : Number(first);
24910
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw Object.assign(new RangeError(`Invalid port: ${port}`), { code: "ERR_SOCKET_BAD_PORT" });
24911
+ this.router.register(port, this, this.owner);
24912
+ this.portValue = port;
24913
+ this.listening = true;
24914
+ queueMicrotask(() => {
24915
+ this.emit("listening");
24916
+ callback?.();
24917
+ });
24918
+ return this;
24919
+ }
24920
+ close(callback) {
24921
+ if (this.portValue !== null) this.router.unregister(this.portValue, this);
24922
+ this.portValue = null;
24923
+ this.listening = false;
24924
+ queueMicrotask(() => {
24925
+ this.emit("close");
24926
+ callback?.();
24927
+ });
24928
+ return this;
24929
+ }
24930
+ address() {
24931
+ return this.portValue === null ? null : { address: "0.0.0.0", family: "IPv4", port: this.portValue };
24932
+ }
24933
+ ref() {
24934
+ return this;
24935
+ }
24936
+ unref() {
24937
+ return this;
24938
+ }
24939
+ setTimeout(_milliseconds, callback) {
24940
+ if (callback) this.on("timeout", callback);
24941
+ return this;
24942
+ }
24943
+ };
24944
+ var VirtualHttpRouter = class {
24945
+ servers = /* @__PURE__ */ new Map();
24946
+ register(port, server, owner) {
24947
+ if (this.servers.has(port)) throw Object.assign(new Error(`listen EADDRINUSE: address already in use 0.0.0.0:${port}`), { code: "EADDRINUSE", port });
24948
+ this.servers.set(port, { server, owner });
24949
+ }
24950
+ unregister(port, server) {
24951
+ if (this.servers.get(port)?.server === server) this.servers.delete(port);
24952
+ }
24953
+ activePorts(owner) {
24954
+ return [...this.servers].filter(([, item]) => owner === void 0 || item.owner === owner).map(([port]) => port).sort((a, b) => a - b);
24955
+ }
24956
+ closeOwner(owner) {
24957
+ for (const { server, owner: value } of [...this.servers.values()]) if (value === owner) server.close();
24958
+ }
24959
+ closeAll() {
24960
+ for (const { server } of [...this.servers.values()]) server.close();
24961
+ }
24962
+ async request(port, init = {}) {
24963
+ const item = this.servers.get(port);
24964
+ if (!item) return { statusCode: 503, statusMessage: "Service Unavailable", headers: {}, body: "No server is listening" };
24965
+ const request = new VirtualIncomingMessage(init);
24966
+ const response = new VirtualServerResponse(request);
24967
+ try {
24968
+ item.server.emit("request", request, response);
24969
+ return await response.completed;
24970
+ } catch (error) {
24971
+ if (!response.writableEnded) response.end(error instanceof Error ? error.message : String(error));
24972
+ return { statusCode: 500, statusMessage: "Internal Server Error", headers: {}, body: error instanceof Error ? error.message : String(error) };
24973
+ }
24974
+ }
24975
+ };
24976
+ function createHttpModule(router, owner) {
24977
+ const createServer = (listener) => new VirtualHttpServer(router, owner, listener);
24978
+ const module = {
24979
+ createServer,
24980
+ Server: VirtualHttpServer,
24981
+ ServerResponse: VirtualServerResponse,
24982
+ IncomingMessage: VirtualIncomingMessage,
24983
+ METHODS,
24984
+ STATUS_CODES,
24985
+ maxHeaderSize: 16 * 1024,
24986
+ validateHeaderName,
24987
+ validateHeaderValue,
24988
+ globalAgent: { keepAlive: true },
24989
+ Agent: class Agent {
24990
+ }
24991
+ };
24992
+ return { ...module, request: unsupportedClient, get: unsupportedClient };
24993
+ }
24994
+ function unsupportedClient() {
24995
+ throw Object.assign(new Error("http client requests are not implemented yet"), { code: "ERR_NOT_IMPLEMENTED" });
24996
+ }
24997
+ function validateHeaderName(name) {
24998
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name)) throw Object.assign(new TypeError(`Header name must be a valid HTTP token [${name}]`), { code: "ERR_INVALID_HTTP_TOKEN" });
24999
+ }
25000
+ function validateHeaderValue(name, value) {
25001
+ if (value === void 0 || /[\0\r\n]/.test(String(value))) throw Object.assign(new TypeError(`Invalid value for header "${name}"`), { code: "ERR_INVALID_CHAR" });
25002
+ }
25003
+ function socketStub() {
25004
+ return { remoteAddress: "127.0.0.1", remotePort: 0, localAddress: "127.0.0.1", localPort: 0, encrypted: false, writable: true, readable: true, setTimeout() {
25005
+ }, setNoDelay() {
25006
+ }, setKeepAlive() {
25007
+ }, ref() {
25008
+ return this;
25009
+ }, unref() {
25010
+ return this;
25011
+ }, destroy() {
25012
+ } };
25013
+ }
25014
+ var METHODS = ["ACL", "BIND", "CHECKOUT", "CONNECT", "COPY", "DELETE", "GET", "HEAD", "LINK", "LOCK", "M-SEARCH", "MERGE", "MKACTIVITY", "MKCALENDAR", "MKCOL", "MOVE", "NOTIFY", "OPTIONS", "PATCH", "POST", "PROPFIND", "PROPPATCH", "PURGE", "PUT", "REBIND", "REPORT", "SEARCH", "SOURCE", "SUBSCRIBE", "TRACE", "UNBIND", "UNLINK", "UNLOCK", "UNSUBSCRIBE"];
25015
+ var STATUS_CODES = { 100: "Continue", 200: "OK", 201: "Created", 202: "Accepted", 204: "No Content", 206: "Partial Content", 301: "Moved Permanently", 302: "Found", 304: "Not Modified", 307: "Temporary Redirect", 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Entity", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable" };
25016
+ var hashes = { md5, sha1: sha1$1, "sha-1": sha1$1, sha224, "sha-224": sha224, sha256, "sha-256": sha256, sha384, "sha-384": sha384, sha512, "sha-512": sha512 };
25017
+ function createCryptoModule() {
25018
+ const cryptoObject = globalThis.crypto;
25019
+ return {
25020
+ createHash(algorithm) {
25021
+ const hash = hashFor(algorithm).create();
25022
+ const api = {
25023
+ update(data, encoding) {
25024
+ hash.update(toBytes2(data, encoding));
25025
+ return api;
25026
+ },
25027
+ digest(encoding) {
25028
+ const value = Buffer$1.from(hash.digest());
25029
+ return encoding ? value.toString(encoding) : value;
25030
+ },
25031
+ copy() {
25032
+ throw new Error("Hash.copy is not implemented");
25033
+ }
25034
+ };
25035
+ return api;
25036
+ },
25037
+ createHmac(algorithm, key) {
25038
+ const hash = hashFor(algorithm);
25039
+ const state = hmac.create(hash, toBytes2(key));
25040
+ const api = {
25041
+ update(data, encoding) {
25042
+ state.update(toBytes2(data, encoding));
25043
+ return api;
25044
+ },
25045
+ digest(encoding) {
25046
+ const value = Buffer$1.from(state.digest());
25047
+ return encoding ? value.toString(encoding) : value;
25048
+ }
25049
+ };
25050
+ return api;
25051
+ },
25052
+ randomBytes(size, callback) {
25053
+ const value = Buffer$1.alloc(size);
25054
+ cryptoObject.getRandomValues(value);
25055
+ if (callback) {
25056
+ queueMicrotask(() => callback(null, value));
25057
+ return;
25058
+ }
25059
+ return value;
25060
+ },
25061
+ randomFillSync(target, offset = 0, size = target.length - offset) {
25062
+ cryptoObject.getRandomValues(target.subarray(offset, offset + size));
25063
+ return target;
25064
+ },
25065
+ randomUUID: () => cryptoObject.randomUUID(),
25066
+ /* Node re-exports the Web Crypto entry points on the `crypto` module
25067
+ * itself, and tools use whichever spelling they prefer — Vite's config
25068
+ * hashing reaches for `getRandomValues` on the default import. */
25069
+ getRandomValues: (target) => cryptoObject.getRandomValues(target),
25070
+ randomInt(min, max) {
25071
+ const [low, high] = max === void 0 ? [0, min] : [min, max];
25072
+ const span = high - low;
25073
+ if (!(span > 0)) throw new RangeError('The value of "max" is out of range');
25074
+ const value = new Uint32Array(1);
25075
+ cryptoObject.getRandomValues(value);
25076
+ return low + value[0] % span;
25077
+ },
25078
+ randomFill(target, offset = 0, size, callback) {
25079
+ const done = [offset, size, callback].find((value) => typeof value === "function");
25080
+ const start = typeof offset === "number" ? offset : 0;
25081
+ const length = typeof size === "number" ? size : target.length - start;
25082
+ cryptoObject.getRandomValues(target.subarray(start, start + length));
25083
+ queueMicrotask(() => done?.(null, target));
25084
+ },
25085
+ hash(algorithm, data, encoding = "hex") {
25086
+ const digest = Buffer$1.from(hashFor(algorithm)(toBytes2(data)));
25087
+ return encoding === "buffer" ? digest : digest.toString(encoding);
25088
+ },
25089
+ timingSafeEqual(a, b) {
25090
+ if (a.length !== b.length) throw new RangeError("Input buffers must have the same byte length");
25091
+ let difference = 0;
25092
+ for (let index = 0; index < a.length; index++) difference |= a[index] ^ b[index];
25093
+ return difference === 0;
25094
+ },
25095
+ getHashes: () => ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"],
25096
+ webcrypto: cryptoObject,
25097
+ subtle: cryptoObject.subtle,
25098
+ constants: {}
25099
+ };
25100
+ }
25101
+ function hashFor(algorithm) {
25102
+ const hash = hashes[algorithm.toLowerCase()];
25103
+ if (!hash) throw Object.assign(new Error(`Digest method not supported: ${algorithm}`), { code: "ERR_OSSL_EVP_UNSUPPORTED" });
25104
+ return hash;
25105
+ }
25106
+ function toBytes2(data, encoding) {
25107
+ return typeof data === "string" ? Buffer$1.from(data, encoding) : data;
25108
+ }
25109
+ var ChildProcess = class extends EventEmitter3 {
25110
+ stdout = new streamModule3.PassThrough();
25111
+ stderr = new streamModule3.PassThrough();
25112
+ stdin;
25113
+ stdio;
25114
+ pid;
25115
+ exitCode = null;
25116
+ signalCode = null;
25117
+ killed = false;
25118
+ spawnfile;
25119
+ spawnargs;
25120
+ handle;
25121
+ settled = false;
25122
+ constructor(handle, file3, args) {
25123
+ super();
25124
+ this.handle = handle;
25125
+ this.pid = handle.pid;
25126
+ this.spawnfile = file3;
25127
+ this.spawnargs = [file3, ...args];
25128
+ this.stdin = new streamModule3.Writable({
25129
+ write: (chunk, _encoding, done) => {
25130
+ try {
25131
+ handle.sendStdin(typeof chunk === "string" ? chunk : Buffer$1.from(chunk).toString("utf8"));
25132
+ } catch {
25133
+ }
25134
+ done();
25135
+ }
25136
+ });
25137
+ this.stdio = [this.stdin, this.stdout, this.stderr];
25138
+ handle.on("stdout", (text2) => this.stdout.write(text2));
25139
+ handle.on("stderr", (text2) => this.stderr.write(text2));
25140
+ handle.on("exit", (code) => this.finish(code));
25141
+ handle.exec();
25142
+ }
25143
+ kill(signal = "SIGTERM") {
25144
+ this.killed = true;
25145
+ this.handle.kill(typeof signal === "number" ? "SIGTERM" : signal);
25146
+ return true;
25147
+ }
25148
+ ref() {
25149
+ return this;
25150
+ }
25151
+ unref() {
25152
+ return this;
25153
+ }
25154
+ disconnect() {
25155
+ this.emit("disconnect");
25156
+ }
25157
+ /** No IPC channel exists, and reporting that honestly beats a silent drop. */
25158
+ send() {
25159
+ return false;
25160
+ }
25161
+ get connected() {
25162
+ return false;
25163
+ }
25164
+ finish(code) {
25165
+ if (this.settled) return;
25166
+ this.settled = true;
25167
+ this.exitCode = code;
25168
+ this.stdout.end();
25169
+ this.stderr.end();
25170
+ this.emit("exit", code, null);
25171
+ queueMicrotask(() => this.emit("close", code, null));
25172
+ }
25173
+ };
25174
+ function createChildProcessModule(spawnChild, defaultCwd) {
25175
+ const throughShell = (command, options) => {
25176
+ const shell = typeof options.shell === "string" ? options.shell : "/bin/sh";
25177
+ return { file: shell, args: ["-c", command] };
25178
+ };
25179
+ const start = (file3, args, options) => {
25180
+ const resolved = options.shell ? throughShell([file3, ...args].join(" "), options) : { file: file3, args };
25181
+ const handle = spawnChild({
25182
+ command: resolved.file,
25183
+ args: resolved.args,
25184
+ cwd: options.cwd ?? defaultCwd(),
25185
+ ...options.env ? { env: options.env } : {}
25186
+ });
25187
+ return new ChildProcess(handle, resolved.file, resolved.args);
25188
+ };
25189
+ const spawn = (file3, args = [], options = {}) => {
25190
+ if (!Array.isArray(args)) return start(file3, [], args);
25191
+ return start(file3, args, options);
25192
+ };
25193
+ const collect = (child, options, callback) => {
25194
+ if (!callback) return child;
25195
+ const out = [];
25196
+ const err = [];
25197
+ child.stdout.on("data", (chunk) => out.push(String(chunk)));
25198
+ child.stderr.on("data", (chunk) => err.push(String(chunk)));
25199
+ child.on("close", (code) => {
25200
+ const asBuffer = options.encoding === "buffer";
25201
+ const stdout = asBuffer ? Buffer$1.from(out.join("")) : out.join("");
25202
+ const stderr = asBuffer ? Buffer$1.from(err.join("")) : err.join("");
25203
+ if (code === 0) {
25204
+ callback(null, stdout, stderr);
25205
+ return;
25206
+ }
25207
+ const error = Object.assign(
25208
+ new Error(`Command failed: ${child.spawnargs.join(" ")}
25209
+ ${err.join("")}`),
25210
+ { code, killed: child.killed, cmd: child.spawnargs.join(" ") }
25211
+ );
25212
+ callback(error, stdout, stderr);
25213
+ });
25214
+ return child;
25215
+ };
25216
+ const exec = (command, options = {}, callback) => {
25217
+ const [opts, cb] = normalize2(options, callback);
25218
+ const { file: file3, args } = throughShell(command, opts);
25219
+ return collect(start(file3, args, { ...opts, shell: false }), opts, cb);
25220
+ };
25221
+ const execFile = (file3, args = [], options = {}, callback) => {
25222
+ const list = Array.isArray(args) ? args : [];
25223
+ const [opts, cb] = Array.isArray(args) ? normalize2(options, callback) : normalize2(args, options);
25224
+ return collect(start(file3, list, opts), opts, cb);
25225
+ };
25226
+ return {
25227
+ spawn,
25228
+ exec,
25229
+ execFile,
25230
+ fork: (modulePath, args = [], options = {}) => spawn("node", [modulePath, ...args], options),
25231
+ execSync: unavailable("execSync"),
25232
+ execFileSync: unavailable("execFileSync"),
25233
+ spawnSync: unavailable("spawnSync"),
25234
+ ChildProcess
25235
+ };
25236
+ }
25237
+ function normalize2(options, callback) {
25238
+ if (typeof options === "function") return [{}, options];
25239
+ return [options ?? {}, callback];
25240
+ }
25241
+ function unavailable(name) {
25242
+ return () => {
25243
+ const error = new Error(
25244
+ `child_process.${name} is not supported in the sandboxed runtime: it would have to block the JavaScript thread. Use the asynchronous form instead.`
25245
+ );
25246
+ error.code = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
25247
+ throw error;
25248
+ };
25249
+ }
25250
+
25251
+ // src/runtime/core-modules.ts
25252
+ init_signals();
25253
+ var Dirent = class {
25254
+ /** Node 20+ exposes the containing directory, and `fs.glob` consumers read it. */
25255
+ constructor(name, stat2, parentPath = "") {
25256
+ this.name = name;
25257
+ this.stat = stat2;
25258
+ this.parentPath = parentPath;
25259
+ }
25260
+ name;
25261
+ stat;
25262
+ parentPath;
25263
+ get path() {
25264
+ return this.parentPath;
25265
+ }
25266
+ isFile() {
25267
+ return this.stat.isFile();
25268
+ }
25269
+ isDirectory() {
25270
+ return this.stat.isDirectory();
25271
+ }
25272
+ isSymbolicLink() {
25273
+ return this.stat.isSymbolicLink();
25274
+ }
25275
+ isBlockDevice() {
25276
+ return false;
25277
+ }
25278
+ isCharacterDevice() {
25279
+ return false;
25280
+ }
25281
+ isFIFO() {
25282
+ return false;
25283
+ }
25284
+ isSocket() {
25285
+ return false;
25286
+ }
25287
+ };
25288
+ var Stats2 = class {
25289
+ constructor(inner) {
25290
+ this.inner = inner;
25291
+ }
25292
+ inner;
25293
+ dev = 1;
25294
+ rdev = 0;
25295
+ blksize = 4096;
25296
+ get mode() {
25297
+ const type = this.inner.isDirectory() ? S_IFDIR2 : this.inner.isSymbolicLink() ? S_IFLNK2 : S_IFREG2;
25298
+ return (this.inner.mode & S_IFMT2) !== 0 ? this.inner.mode : this.inner.mode | type;
25299
+ }
25300
+ get size() {
25301
+ return this.inner.size;
25302
+ }
25303
+ get uid() {
25304
+ return this.inner.uid;
25305
+ }
25306
+ get gid() {
25307
+ return this.inner.gid;
25308
+ }
25309
+ get ino() {
25310
+ return this.inner.ino;
25311
+ }
25312
+ get nlink() {
25313
+ return this.inner.nlink;
25314
+ }
25315
+ get blocks() {
25316
+ return Math.ceil(this.inner.size / 512);
25317
+ }
25318
+ get atimeMs() {
25319
+ return this.inner.atimeMs;
25320
+ }
25321
+ get mtimeMs() {
25322
+ return this.inner.mtimeMs;
25323
+ }
25324
+ get ctimeMs() {
25325
+ return this.inner.ctimeMs;
25326
+ }
25327
+ get birthtimeMs() {
25328
+ return this.inner.birthtimeMs;
25329
+ }
25330
+ get atime() {
25331
+ return new Date(this.inner.atimeMs);
25332
+ }
25333
+ get mtime() {
25334
+ return new Date(this.inner.mtimeMs);
25335
+ }
25336
+ get ctime() {
25337
+ return new Date(this.inner.ctimeMs);
25338
+ }
25339
+ get birthtime() {
25340
+ return new Date(this.inner.birthtimeMs);
25341
+ }
25342
+ isFile() {
25343
+ return this.inner.isFile();
25344
+ }
25345
+ isDirectory() {
25346
+ return this.inner.isDirectory();
25347
+ }
25348
+ isSymbolicLink() {
25349
+ return this.inner.isSymbolicLink();
25350
+ }
25351
+ isBlockDevice() {
25352
+ return false;
25353
+ }
25354
+ isCharacterDevice() {
25355
+ return false;
25356
+ }
25357
+ isFIFO() {
25358
+ return false;
25359
+ }
25360
+ isSocket() {
25361
+ return false;
25362
+ }
25363
+ };
25364
+ var S_IFMT2 = 61440;
25365
+ var S_IFREG2 = 32768;
25366
+ var S_IFDIR2 = 16384;
25367
+ var S_IFLNK2 = 40960;
25368
+ var FsWatcher = class extends EventEmitter3 {
25369
+ close() {
25370
+ this.removeAllListeners();
25371
+ }
25372
+ ref() {
25373
+ return this;
25374
+ }
25375
+ unref() {
25376
+ return this;
25377
+ }
25378
+ };
25379
+ function createCoreModules(options) {
25380
+ const volume = options.volume;
25381
+ let cwd = clean(options.cwd ?? "/");
25382
+ let exitCode = 0;
25383
+ const env2 = { ...options.env };
25384
+ const stdoutWrite = options.stdout ?? (() => {
25385
+ });
25386
+ const stderrWrite = options.stderr ?? (() => {
25387
+ });
25388
+ const timers = createTrackedTimers();
25389
+ const processObject = Object.assign(new EventEmitter3(), processShim, {
25390
+ argv: options.argv?.slice() ?? ["/usr/bin/node"],
25391
+ argv0: "node",
25392
+ execPath: "/usr/bin/node",
25393
+ env: env2,
25394
+ platform: "linux",
25395
+ arch: "x64",
25396
+ version: "v22.12.0",
25397
+ versions: { ...processShim.versions, node: "22.12.0" },
25398
+ pid: 100,
25399
+ ppid: 1,
25400
+ title: "node",
25401
+ exitCode,
25402
+ cwd: () => cwd,
25403
+ chdir: (path2) => {
25404
+ const next = resolve(cwd, path2);
25405
+ const stat2 = volume.lstatSync(resolveLinks(volume, next));
25406
+ if (!stat2.isDirectory()) throw fsError("ENOTDIR", "chdir", next);
25407
+ cwd = next;
25408
+ },
25409
+ umask: (_mask) => 18,
25410
+ getuid: () => 0,
25411
+ geteuid: () => 0,
25412
+ getgid: () => 0,
25413
+ getegid: () => 0,
25414
+ getgroups: () => [0],
25415
+ uptime: () => performance.now() / 1e3,
25416
+ memoryUsage: () => ({ rss: 0, heapTotal: 0, heapUsed: 0, external: 0, arrayBuffers: 0 }),
25417
+ cpuUsage: () => ({ user: 0, system: 0 }),
25418
+ exit: (code = 0) => {
25419
+ exitCode = code;
25420
+ processObject.exitCode = code;
25421
+ options.onExit?.(code);
25422
+ },
25423
+ kill: () => true
25424
+ });
25425
+ processObject.stdout = makeOutputStream(stdoutWrite, 1);
25426
+ processObject.stderr = makeOutputStream(stderrWrite, 2);
25427
+ processObject.stdin = new streamModule3.Readable({ read() {
25428
+ this.push(null);
25429
+ } });
25430
+ Object.assign(processObject.stdin, { fd: 0, isTTY: false, setRawMode() {
25431
+ return this;
25432
+ } });
25433
+ const fs = createFsModule(volume, () => cwd);
25434
+ const path = createPathModule(() => cwd);
25435
+ const consoleObject = new Console(stdoutWrite, stderrWrite);
25436
+ const os = createOsModule();
25437
+ const asyncHooks = createAsyncHooksModule();
25438
+ const moduleBuiltin = {
25439
+ builtinModules: builtinNames2.flatMap((name) => [name, `node:${name}`]),
25440
+ isBuiltin: (name) => builtinNames2.includes(name.replace(/^node:/, "")),
25441
+ createRequire: () => {
25442
+ throw new Error("createRequire is only available inside a loaded module");
25443
+ }
25444
+ };
25445
+ const http = options.http ? createHttpModule(options.http.router, options.http.owner) : createUnsupportedModule("http");
25446
+ const childProcess = options.spawnChild ? createChildProcessModule(options.spawnChild, () => cwd) : createUnsupportedModule("child_process");
25447
+ const readline2 = createReadlineModule(() => processObject.stdin);
25448
+ const dns = createDnsModule();
25449
+ const builtins = {
25450
+ assert: assertModule,
25451
+ "assert/strict": assertModule.strict ?? assertModule,
25452
+ buffer: { Buffer: Buffer$1, SlowBuffer: Buffer$1, INSPECT_MAX_BYTES: 50, kMaxLength: Buffer$1.kMaxLength },
25453
+ async_hooks: asyncHooks,
25454
+ child_process: childProcess,
25455
+ console: consoleObject,
25456
+ constants: fs.constants,
25457
+ crypto: createCryptoModule(),
25458
+ dns,
25459
+ "dns/promises": dns.promises,
25460
+ events: EventEmitter3,
25461
+ fs,
25462
+ "fs/promises": fs.promises,
25463
+ module: moduleBuiltin,
25464
+ http,
25465
+ https: http,
25466
+ os,
25467
+ path,
25468
+ "path/posix": path,
25469
+ perf_hooks: { performance, PerformanceObserver: globalThis.PerformanceObserver },
25470
+ process: processObject,
25471
+ punycode: urlModule.punycode ?? {},
25472
+ querystring: querystringModule,
25473
+ readline: readline2,
25474
+ "readline/promises": readline2.promises,
25475
+ stream: streamModule3,
25476
+ "stream/promises": createStreamPromises(),
25477
+ string_decoder: stringDecoderModule,
25478
+ timers: { ...timersModule, ...timers.api },
25479
+ "timers/promises": createTimerPromises(),
25480
+ tty: { isatty: () => false, ReadStream: streamModule3.Readable, WriteStream: streamModule3.Writable },
25481
+ url: urlModule,
25482
+ util: utilModule,
25483
+ "util/types": utilModule.types ?? {},
25484
+ zlib: zlibModule
25485
+ };
25486
+ for (const name of stubNames) builtins[name] = createUnsupportedModule(name);
25487
+ const globals = {
25488
+ Buffer: Buffer$1,
25489
+ console: consoleObject,
25490
+ process: processObject,
25491
+ ...timers.api
25492
+ };
25493
+ const globalOverlay = new Proxy(globalThis, {
25494
+ get: (target, key) => typeof key === "string" && key in globals ? globals[key] : key === "global" || key === "globalThis" ? globalOverlay : Reflect.get(target, key),
25495
+ has: (target, key) => typeof key === "string" && key in globals || Reflect.has(target, key)
25496
+ });
25497
+ globals.global = globalOverlay;
25498
+ globals.globalThis = globalOverlay;
25499
+ return { builtins, globals, process: processObject, pendingHandles: timers.pending };
25500
+ }
25501
+ var ASYNC_FS_METHODS = [
25502
+ "readFile",
25503
+ "writeFile",
25504
+ "appendFile",
25505
+ "stat",
25506
+ "lstat",
25507
+ "fstat",
25508
+ "readdir",
25509
+ "mkdir",
25510
+ "mkdtemp",
25511
+ "rm",
25512
+ "rmdir",
25513
+ "unlink",
25514
+ "rename",
25515
+ "readlink",
25516
+ "symlink",
25517
+ "link",
25518
+ "realpath",
25519
+ "truncate",
25520
+ "ftruncate",
25521
+ "chmod",
25522
+ "lchmod",
25523
+ "fchmod",
25524
+ "chown",
25525
+ "lchown",
25526
+ "fchown",
25527
+ "utimes",
25528
+ "lutimes",
25529
+ "futimes",
25530
+ "access",
25531
+ "copyFile",
25532
+ "cp",
25533
+ "open",
25534
+ "close",
25535
+ "read",
25536
+ "write",
25537
+ "exists"
25538
+ ];
25539
+ function createPathModule(cwd) {
25540
+ const resolve2 = (...segments2) => pathModule.resolve(cwd(), ...segments2);
25541
+ const path = {
25542
+ ...pathModule,
25543
+ resolve: resolve2,
25544
+ /* `relative` resolves both operands, and the implementation would do so
25545
+ * against the host cwd, so they are resolved here first. */
25546
+ relative: (from, to) => pathModule.relative(resolve2(from), resolve2(to))
25547
+ };
25548
+ path.posix = path;
25549
+ path.win32 = pathModule.win32 ?? path;
25550
+ path.default = path;
25551
+ return path;
25552
+ }
25553
+ function createFsModule(volume, cwd) {
25554
+ const fds = /* @__PURE__ */ new Map();
25555
+ let nextFd = 3;
25556
+ const abs = (value) => {
25557
+ if (value instanceof URL) value = value.pathname;
25558
+ if (Buffer$1.isBuffer(value) || value instanceof Uint8Array) value = new TextDecoder().decode(value);
25559
+ if (typeof value !== "string") throw new TypeError("path must be a string, Buffer, or URL");
25560
+ return value.startsWith("/") ? clean(value) : resolve(cwd(), value);
25561
+ };
25562
+ const bytes = (data, encoding) => {
25563
+ if (typeof data === "string") return new Uint8Array(Buffer$1.from(data, encoding));
25564
+ if (Buffer$1.isBuffer(data) || data instanceof Uint8Array) return new Uint8Array(data);
25565
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
25566
+ throw new TypeError("data must be a string or byte array");
25567
+ };
25568
+ const read = (path, encoding) => {
25569
+ const data = Buffer$1.from(volume.readFileSync(resolveLinks(volume, abs(path))));
25570
+ return encoding && encoding !== "buffer" ? data.toString(encoding) : data;
25571
+ };
25572
+ const mkdirRecursive = (path, mode) => {
25573
+ let cursor = "";
25574
+ for (const part of segments(path)) {
25575
+ cursor += `/${part}`;
25576
+ try {
25577
+ if (!volume.lstatSync(cursor).isDirectory()) throw fsError("ENOTDIR", "mkdir", cursor);
25578
+ } catch (error) {
25579
+ if (error.code !== "ENOENT") throw error;
25580
+ volume.mkdirSync(cursor, { mode });
25581
+ }
25582
+ }
25583
+ };
25584
+ const rmRecursive = (path) => {
25585
+ const stat2 = volume.lstatSync(path);
25586
+ if (!stat2.isDirectory()) return volume.unlinkSync(path);
25587
+ for (const name of volume.readdirSync(path)) rmRecursive(join(path, name));
25588
+ volume.rmdirSync(path);
25589
+ };
25590
+ const callback = (operation, cb) => {
25591
+ queueMicrotask(() => {
25592
+ try {
25593
+ cb(null, operation());
25594
+ } catch (error) {
25595
+ cb(error);
25596
+ }
25597
+ });
25598
+ };
25599
+ const fs = {
25600
+ constants: {
25601
+ F_OK: 0,
25602
+ R_OK: 4,
25603
+ W_OK: 2,
25604
+ X_OK: 1,
25605
+ O_RDONLY: 0,
25606
+ O_WRONLY: 1,
25607
+ O_RDWR: 2,
25608
+ O_CREAT: 64,
25609
+ O_EXCL: 128,
25610
+ O_TRUNC: 512,
25611
+ O_APPEND: 1024,
25612
+ COPYFILE_EXCL: 1
25613
+ },
25614
+ Dirent,
25615
+ readFileSync: (path, options) => read(path, typeof options === "object" && options ? options.encoding : options),
25616
+ writeFileSync: (path, data, options) => {
25617
+ const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
25618
+ volume.writeFileSync(abs(path), bytes(data, encoding ?? void 0));
25619
+ if (typeof options === "object" && options?.mode !== void 0) volume.chmodSync(abs(path), options.mode);
25620
+ },
25621
+ appendFileSync: (path, data, options) => {
25622
+ const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
25623
+ volume.appendFileSync(abs(path), bytes(data, encoding ?? void 0));
25624
+ },
25625
+ existsSync: (path) => {
25626
+ try {
25627
+ volume.lstatSync(abs(path));
25628
+ return true;
25629
+ } catch {
25630
+ return false;
25631
+ }
25632
+ },
25633
+ statSync: (path) => new Stats2(volume.lstatSync(resolveLinks(volume, abs(path)))),
25634
+ lstatSync: (path) => new Stats2(volume.lstatSync(abs(path))),
25635
+ readdirSync: (path, options) => {
25636
+ const dir3 = resolveLinks(volume, abs(path));
25637
+ const names = volume.readdirSync(dir3);
25638
+ if (typeof options === "object" && options?.withFileTypes) {
25639
+ return names.map((name) => new Dirent(name, new Stats2(volume.lstatSync(join(dir3, name))), dir3));
25640
+ }
25641
+ if ((typeof options === "string" ? options : options?.encoding) === "buffer") return names.map((name) => Buffer$1.from(name));
25642
+ return names;
25643
+ },
25644
+ mkdirSync: (path, options) => {
25645
+ const target = abs(path);
25646
+ const mode = typeof options === "number" ? options : options?.mode ?? 511;
25647
+ if (typeof options === "object" && options?.recursive) return mkdirRecursive(target, mode);
25648
+ return volume.mkdirSync(target, { mode });
25649
+ },
25650
+ rmdirSync: (path, options) => options?.recursive ? rmRecursive(abs(path)) : volume.rmdirSync(abs(path)),
25651
+ rmSync: (path, options) => {
25652
+ try {
25653
+ options?.recursive ? rmRecursive(abs(path)) : volume.unlinkSync(abs(path));
25654
+ } catch (error) {
25655
+ if (!options?.force) throw error;
25656
+ }
25657
+ },
25658
+ unlinkSync: (path) => volume.unlinkSync(abs(path)),
25659
+ renameSync: (from, to) => volume.renameSync(abs(from), abs(to)),
25660
+ readlinkSync: (path, encoding) => {
25661
+ const value = volume.readlinkSync(abs(path));
25662
+ return encoding === "buffer" ? Buffer$1.from(value) : value;
25663
+ },
25664
+ symlinkSync: (target, path) => volume.symlinkSync(target, abs(path)),
25665
+ linkSync: (from, to) => volume.linkSync(abs(from), abs(to)),
25666
+ realpathSync: (path) => resolveLinks(volume, abs(path)),
25667
+ truncateSync: (path, length = 0) => volume.truncateSync(abs(path), length),
25668
+ chmodSync: (path, mode) => volume.chmodSync(resolveLinks(volume, abs(path)), mode),
25669
+ chownSync: (path, uid, gid) => volume.chownSync(resolveLinks(volume, abs(path)), uid, gid),
25670
+ utimesSync: (path, atime, mtime) => volume.utimesSync(resolveLinks(volume, abs(path)), new Date(atime), new Date(mtime)),
25671
+ accessSync: (path) => {
25672
+ volume.lstatSync(resolveLinks(volume, abs(path)));
25673
+ },
25674
+ copyFileSync: (from, to, flags = 0) => {
25675
+ const target = abs(to);
25676
+ if (flags && fs.existsSync(target)) throw fsError("EEXIST", "copyfile", target);
25677
+ volume.writeFileSync(target, volume.readFileSync(resolveLinks(volume, abs(from))));
25678
+ },
25679
+ openSync: (path, flags) => {
25680
+ const target = abs(path);
25681
+ const textFlags = typeof flags === "number" ? flags === 0 ? "r" : "r+" : flags;
25682
+ if (/[wa]/.test(textFlags) && !fs.existsSync(target)) volume.writeFileSync(target, new Uint8Array());
25683
+ if (textFlags.startsWith("w")) volume.truncateSync(target, 0);
25684
+ else volume.lstatSync(resolveLinks(volume, target));
25685
+ const fd = nextFd++;
25686
+ fds.set(fd, { path: target, position: textFlags.startsWith("a") ? volume.lstatSync(target).size : 0, flags: textFlags });
25687
+ return fd;
25688
+ },
25689
+ closeSync: (fd) => {
25690
+ if (!fds.delete(fd)) throw fsError("EBADF", "close", String(fd));
25691
+ },
25692
+ /** Used by the promise API's FileHandle to reach whole-file operations. */
25693
+ __pathForFd: (fd) => requiredFd(fds, fd).path,
25694
+ fstatSync: (fd) => new Stats2(volume.lstatSync(resolveLinks(volume, requiredFd(fds, fd).path))),
25695
+ readSync: (fd, target, offset, length, position) => {
25696
+ const file3 = requiredFd(fds, fd);
25697
+ const source = volume.readFileSync(resolveLinks(volume, file3.path));
25698
+ const start = position ?? file3.position;
25699
+ const count = Math.max(0, Math.min(length, source.length - start));
25700
+ target.set(source.subarray(start, start + count), offset);
25701
+ if (position == null) file3.position += count;
25702
+ return count;
25703
+ },
25704
+ writeSync: (fd, data, offset, length, position) => {
25705
+ const file3 = requiredFd(fds, fd);
25706
+ const input = bytes(data);
25707
+ const chunk = typeof data === "string" ? input : input.subarray(offset ?? 0, (offset ?? 0) + (length ?? input.length));
25708
+ const old = volume.readFileSync(file3.path);
25709
+ const start = file3.flags.startsWith("a") ? old.length : position ?? file3.position;
25710
+ const next = new Uint8Array(Math.max(old.length, start + chunk.length));
25711
+ next.set(old);
25712
+ next.set(chunk, start);
25713
+ volume.writeFileSync(file3.path, next);
25714
+ if (position == null) file3.position = start + chunk.length;
25715
+ return chunk.length;
25716
+ },
25717
+ createReadStream: (path) => {
25718
+ const data = Buffer$1.from(volume.readFileSync(resolveLinks(volume, abs(path))));
25719
+ return streamModule3.Readable.from([data]);
25720
+ },
25721
+ createWriteStream: (path, options) => {
25722
+ const target = abs(path);
25723
+ let first = true;
25724
+ return new streamModule3.Writable({ write(chunk, _encoding, done) {
25725
+ try {
25726
+ if (options?.flags?.startsWith("a") || !first) volume.appendFileSync(target, new Uint8Array(chunk));
25727
+ else volume.writeFileSync(target, new Uint8Array(chunk));
25728
+ first = false;
25729
+ done();
25730
+ } catch (error) {
25731
+ done(error);
25732
+ }
25733
+ } });
25734
+ },
25735
+ watch: () => new FsWatcher(),
25736
+ watchFile: () => {
25737
+ },
25738
+ unwatchFile: () => {
25739
+ }
25740
+ };
25741
+ fs.ftruncateSync = (fd, length) => fs.truncateSync(requiredFd(fds, fd).path, length);
25742
+ fs.fchmodSync = (fd, mode) => fs.chmodSync(requiredFd(fds, fd).path, mode);
25743
+ fs.fchownSync = (fd, uid, gid) => fs.chownSync(requiredFd(fds, fd).path, uid, gid);
25744
+ fs.futimesSync = (fd, atime, mtime) => fs.utimesSync(requiredFd(fds, fd).path, atime, mtime);
25745
+ fs.lchmodSync = (path, mode) => volume.lchmodSync(abs(path), mode);
25746
+ fs.lchownSync = (path, uid, gid) => volume.lchownSync(abs(path), uid, gid);
25747
+ fs.lutimesSync = (path, atime, mtime) => fs.utimesSync(path, atime, mtime);
25748
+ fs.realpathSync.native = fs.realpathSync;
25749
+ fs.mkdtempSync = (prefix) => {
25750
+ const target = `${String(prefix)}${Math.random().toString(36).slice(2, 8)}`;
25751
+ volume.mkdirSync(resolve(cwd(), target), { mode: 448 });
25752
+ return target;
25753
+ };
25754
+ fs.cpSync = (from, to, options) => {
25755
+ const copy = (source, destination) => {
25756
+ const stat2 = volume.lstatSync(source);
25757
+ if (stat2.isDirectory()) {
25758
+ if (!options?.recursive) throw fsError("EISDIR", "cp", source);
25759
+ mkdirRecursive(destination, stat2.mode);
25760
+ for (const name of volume.readdirSync(source)) {
25761
+ copy(join(source, name), join(destination, name));
25762
+ }
25763
+ return;
25764
+ }
25765
+ if (stat2.isSymbolicLink()) {
25766
+ volume.symlinkSync(volume.readlinkSync(source), destination);
25767
+ return;
25768
+ }
25769
+ volume.writeFileSync(destination, volume.readFileSync(source));
25770
+ };
25771
+ copy(abs(from), abs(to));
25772
+ };
25773
+ for (const name of ASYNC_FS_METHODS) {
25774
+ if (name === "exists") continue;
25775
+ fs[name] = (...args) => {
25776
+ const cb = args.pop();
25777
+ if (typeof cb !== "function") throw new TypeError("callback must be a function");
25778
+ callback(() => fs[`${name}Sync`](...args), cb);
25779
+ };
25780
+ }
25781
+ fs.realpath.native = fs.realpath;
25782
+ fs.exists = (path, cb) => {
25783
+ queueMicrotask(() => cb(fs.existsSync(path)));
25784
+ };
25785
+ fs.promises = {
25786
+ ...Object.fromEntries(
25787
+ ASYNC_FS_METHODS.filter((name) => name !== "exists" && name !== "open").map((name) => [name, (...args) => Promise.resolve().then(() => fs[`${name}Sync`](...args))])
25788
+ ),
25789
+ constants: fs.constants,
25790
+ /* The promise API hands back a FileHandle object rather than a numeric
25791
+ * descriptor, and callers use its methods instead of passing the number
25792
+ * to `fs.read`. */
25793
+ open: async (path, flags = "r", mode) => makeFileHandle(fs, fs.openSync(path, flags, mode))
25794
+ };
25795
+ return fs;
25796
+ }
25797
+ function makeFileHandle(fs, fd) {
25798
+ return {
25799
+ fd,
25800
+ close: async () => fs.closeSync(fd),
25801
+ stat: async () => fs.fstatSync(fd),
25802
+ truncate: async (length) => fs.ftruncateSync(fd, length),
25803
+ chmod: async (mode) => fs.fchmodSync(fd, mode),
25804
+ chown: async (uid, gid) => fs.fchownSync(fd, uid, gid),
25805
+ utimes: async (atime, mtime) => fs.futimesSync(fd, atime, mtime),
25806
+ read: async (buffer, offset = 0, length = buffer.length, position) => ({
25807
+ bytesRead: fs.readSync(fd, buffer, offset, length, position),
25808
+ buffer
25809
+ }),
25810
+ write: async (data, offset, length, position) => ({
25811
+ bytesWritten: fs.writeSync(fd, data, offset, length, position),
25812
+ buffer: data
25813
+ }),
25814
+ readFile: async (options) => fs.readFileSync(fs.__pathForFd(fd), options),
25815
+ writeFile: async (data, options) => fs.writeFileSync(fs.__pathForFd(fd), data, options)
25816
+ };
25817
+ }
25818
+ function resolveLinks(volume, input) {
25819
+ let path = clean(input);
25820
+ for (let hops = 0; hops < 40; hops++) {
25821
+ const parts = segments(path);
25822
+ let cursor = "";
25823
+ let followed = false;
25824
+ for (let index = 0; index < parts.length; index++) {
25825
+ cursor += `/${parts[index]}`;
25826
+ const stat2 = volume.lstatSync(cursor);
25827
+ if (!stat2.isSymbolicLink()) continue;
25828
+ const target = volume.readlinkSync(cursor);
25829
+ const rest = parts.slice(index + 1).join("/");
25830
+ path = resolve(dirname(cursor), target, rest);
25831
+ followed = true;
25832
+ break;
25833
+ }
25834
+ if (!followed) return path || "/";
25835
+ }
25836
+ throw fsError("ELOOP", "realpath", input);
25837
+ }
25838
+ function requiredFd(fds, fd) {
25839
+ const file3 = fds.get(fd);
25840
+ if (!file3) throw fsError("EBADF", "fd", String(fd));
25841
+ return file3;
25842
+ }
25843
+ function fsError(code, syscall, path) {
25844
+ return Object.assign(new Error(`${code}: ${syscall}, '${path}'`), { code, syscall, path });
25845
+ }
25846
+ function makeOutputStream(write, fd) {
25847
+ const stream = new streamModule3.Writable({ write(chunk, _encoding, done) {
25848
+ write(Buffer$1.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk));
25849
+ done();
25850
+ } });
25851
+ return Object.assign(stream, { fd, isTTY: false, columns: 80, rows: 24 });
25852
+ }
25853
+ var Console = class {
25854
+ constructor(out, err) {
25855
+ this.out = out;
25856
+ this.err = err;
25857
+ }
25858
+ out;
25859
+ err;
25860
+ log = (...args) => {
25861
+ this.out(utilModule.format(...args) + "\n");
25862
+ };
25863
+ info = (...args) => {
25864
+ this.log(...args);
25865
+ };
25866
+ debug = (...args) => {
25867
+ this.log(...args);
25868
+ };
25869
+ warn = (...args) => {
25870
+ this.err(utilModule.format(...args) + "\n");
25871
+ };
25872
+ error = (...args) => {
25873
+ this.warn(...args);
25874
+ };
25875
+ dir = (value, options) => {
25876
+ this.out(utilModule.inspect(value, options) + "\n");
25877
+ };
25878
+ trace = (...args) => {
25879
+ this.err(`Trace: ${utilModule.format(...args)}
25880
+ `);
25881
+ };
25882
+ assert = (value, ...args) => {
25883
+ if (!value) this.err(`Assertion failed: ${utilModule.format(...args)}
25884
+ `);
25885
+ };
25886
+ group = (...args) => {
25887
+ if (args.length) this.log(...args);
25888
+ };
25889
+ groupEnd = () => {
25890
+ };
25891
+ table = (value) => {
25892
+ this.dir(value);
25893
+ };
25894
+ count = () => {
25895
+ };
25896
+ countReset = () => {
25897
+ };
25898
+ time = (_label = "default") => {
25899
+ };
25900
+ timeEnd = (_label = "default") => {
25901
+ };
25902
+ timeLog = (_label = "default") => {
25903
+ };
25904
+ };
25905
+ function createReadlineModule(stdin) {
25906
+ class Interface extends EventEmitter3 {
25907
+ constructor(input) {
25908
+ super();
25909
+ this.input = input;
25910
+ input?.on?.("data", (chunk) => {
25911
+ for (const line of String(chunk).split("\n")) this.lines.push(line);
25912
+ while (this.lines.length > 1) this.emit("line", this.lines.shift());
25913
+ });
25914
+ input?.on?.("end", () => this.close());
25915
+ }
25916
+ input;
25917
+ closed = false;
25918
+ lines = [];
25919
+ question(_query, callback) {
25920
+ const answer = this.lines.shift() ?? "";
25921
+ if (callback) {
25922
+ queueMicrotask(() => callback(answer));
25923
+ return;
25924
+ }
25925
+ return Promise.resolve(answer);
25926
+ }
25927
+ prompt() {
25928
+ }
25929
+ setPrompt() {
25930
+ }
25931
+ pause() {
25932
+ return this;
25933
+ }
25934
+ resume() {
25935
+ return this;
25936
+ }
25937
+ write() {
25938
+ }
25939
+ close() {
25940
+ if (this.closed) return;
25941
+ this.closed = true;
25942
+ this.emit("close");
25943
+ }
25944
+ async *[Symbol.asyncIterator]() {
25945
+ while (this.lines.length) yield this.lines.shift();
25946
+ }
25947
+ }
25948
+ const createInterface = (options) => new Interface(options?.input ?? (Array.isArray(options) ? options[0] : stdin()));
25949
+ const noop = () => {
25950
+ };
25951
+ const base = {
25952
+ Interface,
25953
+ createInterface,
25954
+ clearLine: noop,
25955
+ clearScreenDown: noop,
25956
+ cursorTo: noop,
25957
+ moveCursor: noop,
25958
+ emitKeypressEvents: noop
25959
+ };
25960
+ return { ...base, promises: { ...base, Interface, createInterface } };
25961
+ }
25962
+ function createDnsModule() {
25963
+ const LOOPBACK = {
25964
+ localhost: { address: "127.0.0.1", family: 4 },
25965
+ "127.0.0.1": { address: "127.0.0.1", family: 4 },
25966
+ "0.0.0.0": { address: "0.0.0.0", family: 4 },
25967
+ "::1": { address: "::1", family: 6 }
25968
+ };
25969
+ const lookupSync = (hostname) => {
25970
+ const entry = LOOPBACK[hostname];
25971
+ if (entry) return entry;
25972
+ const error = new Error(`getaddrinfo ENOTFOUND ${hostname}`);
25973
+ error.code = "ENOTFOUND";
25974
+ error.errno = -3008;
25975
+ error.syscall = "getaddrinfo";
25976
+ error.hostname = hostname;
25977
+ throw error;
25978
+ };
25979
+ const lookup = (hostname, options, callback) => {
25980
+ const done = typeof options === "function" ? options : callback;
25981
+ const all = typeof options === "object" && options !== null && options.all;
25982
+ queueMicrotask(() => {
25983
+ try {
25984
+ const entry = lookupSync(hostname);
25985
+ done?.(null, all ? [entry] : entry.address, entry.family);
25986
+ } catch (error) {
25987
+ done?.(error);
25988
+ }
25989
+ });
25990
+ };
25991
+ const notFound = (hostname) => Promise.reject(lookupThrow(hostname));
25992
+ const lookupThrow = (hostname) => {
25993
+ try {
25994
+ lookupSync(hostname);
25995
+ return null;
25996
+ } catch (error) {
25997
+ return error;
25998
+ }
25999
+ };
26000
+ const promises = {
26001
+ lookup: async (hostname, options) => {
26002
+ const entry = lookupSync(hostname);
26003
+ return options?.all ? [entry] : entry;
26004
+ },
26005
+ resolve4: async (hostname) => [lookupSync(hostname).address],
26006
+ resolve6: async (hostname) => [lookupSync(hostname).address],
26007
+ reverse: async (address) => address === "127.0.0.1" ? ["localhost"] : notFound(address)
26008
+ };
26009
+ return {
26010
+ lookup,
26011
+ promises,
26012
+ Resolver: class Resolver {
26013
+ },
26014
+ getServers: () => [],
26015
+ setServers: () => {
26016
+ },
26017
+ ADDRCONFIG: 1024,
26018
+ V4MAPPED: 8,
26019
+ ALL: 16,
26020
+ NODATA: "ENODATA",
26021
+ NOTFOUND: "ENOTFOUND"
26022
+ };
26023
+ }
26024
+ function createOsModule() {
26025
+ return {
26026
+ EOL: "\n",
26027
+ devNull: "/dev/null",
26028
+ type: () => "Linux",
26029
+ platform: () => "linux",
26030
+ release: () => "5.10.0-sandboxedjs",
26031
+ version: () => "#1 SMP SandboxedJS",
26032
+ arch: () => "x64",
26033
+ endianness: () => "LE",
26034
+ hostname: () => "sandbox",
26035
+ homedir: () => "/root",
26036
+ tmpdir: () => "/tmp",
26037
+ userInfo: () => ({ uid: 0, gid: 0, username: "root", homedir: "/root", shell: "/bin/sh" }),
26038
+ cpus: () => [{ model: "SandboxedJS Virtual CPU", speed: 1e3, times: { user: 0, nice: 0, sys: 0, idle: 0, irq: 0 } }],
26039
+ totalmem: () => 2 * 1024 ** 3,
26040
+ freemem: () => 1024 ** 3,
26041
+ uptime: () => performance.now() / 1e3,
26042
+ loadavg: () => [0, 0, 0],
26043
+ networkInterfaces: () => ({}),
26044
+ machine: () => "x86_64",
26045
+ availableParallelism: () => 4,
26046
+ /* `os.constants.signals` is not decoration: the `human-signals` package
26047
+ * that `execa` pulls in enumerates it at load time, so every tool built on
26048
+ * execa fails to even import without it. */
26049
+ constants: {
26050
+ signals: SIGNALS,
26051
+ errno: ERRNO_CONSTANTS,
26052
+ priority: {
26053
+ PRIORITY_LOW: 19,
26054
+ PRIORITY_BELOW_NORMAL: 10,
26055
+ PRIORITY_NORMAL: 0,
26056
+ PRIORITY_ABOVE_NORMAL: -7,
26057
+ PRIORITY_HIGH: -14,
26058
+ PRIORITY_HIGHEST: -20
26059
+ }
26060
+ }
26061
+ };
26062
+ }
26063
+ var ERRNO_CONSTANTS = {
26064
+ E2BIG: 7,
26065
+ EACCES: 13,
26066
+ EADDRINUSE: 98,
26067
+ EADDRNOTAVAIL: 99,
26068
+ EAFNOSUPPORT: 97,
26069
+ EAGAIN: 11,
26070
+ EALREADY: 114,
26071
+ EBADF: 9,
26072
+ EBADMSG: 74,
26073
+ EBUSY: 16,
26074
+ ECANCELED: 125,
26075
+ ECHILD: 10,
26076
+ ECONNABORTED: 103,
26077
+ ECONNREFUSED: 111,
26078
+ ECONNRESET: 104,
26079
+ EDEADLK: 35,
26080
+ EDESTADDRREQ: 89,
26081
+ EDOM: 33,
26082
+ EDQUOT: 122,
26083
+ EEXIST: 17,
26084
+ EFAULT: 14,
26085
+ EFBIG: 27,
26086
+ EHOSTUNREACH: 113,
26087
+ EIDRM: 43,
26088
+ EILSEQ: 84,
26089
+ EINPROGRESS: 115,
26090
+ EINTR: 4,
26091
+ EINVAL: 22,
26092
+ EIO: 5,
26093
+ EISCONN: 106,
26094
+ EISDIR: 21,
26095
+ ELOOP: 40,
26096
+ EMFILE: 24,
26097
+ EMLINK: 31,
26098
+ EMSGSIZE: 90,
26099
+ EMULTIHOP: 72,
26100
+ ENAMETOOLONG: 36,
26101
+ ENETDOWN: 100,
26102
+ ENETRESET: 102,
26103
+ ENETUNREACH: 101,
26104
+ ENFILE: 23,
26105
+ ENOBUFS: 105,
26106
+ ENODATA: 61,
26107
+ ENODEV: 19,
26108
+ ENOENT: 2,
26109
+ ENOEXEC: 8,
26110
+ ENOLCK: 37,
26111
+ ENOLINK: 67,
26112
+ ENOMEM: 12,
26113
+ ENOMSG: 42,
26114
+ ENOPROTOOPT: 92,
26115
+ ENOSPC: 28,
26116
+ ENOSR: 63,
26117
+ ENOSTR: 60,
26118
+ ENOSYS: 38,
26119
+ ENOTCONN: 107,
26120
+ ENOTDIR: 20,
26121
+ ENOTEMPTY: 39,
26122
+ ENOTSOCK: 88,
26123
+ ENOTSUP: 95,
26124
+ ENOTTY: 25,
26125
+ ENXIO: 6,
26126
+ EOPNOTSUPP: 95,
26127
+ EOVERFLOW: 75,
26128
+ EPERM: 1,
26129
+ EPIPE: 32,
26130
+ EPROTO: 71,
26131
+ EPROTONOSUPPORT: 93,
26132
+ EPROTOTYPE: 91,
26133
+ ERANGE: 34,
26134
+ EROFS: 30,
26135
+ ESPIPE: 29,
26136
+ ESRCH: 3,
26137
+ ESTALE: 116,
26138
+ ETIME: 62,
26139
+ ETIMEDOUT: 110,
26140
+ ETXTBSY: 26,
26141
+ EWOULDBLOCK: 11,
26142
+ EXDEV: 18
26143
+ };
26144
+ function createTrackedTimers() {
26145
+ const live = /* @__PURE__ */ new Set();
26146
+ const track = (handle, repeating) => {
26147
+ live.add(handle);
26148
+ return handle;
26149
+ };
26150
+ const setTimeoutTracked = (fn, delay, ...args) => {
26151
+ const handle = setTimeout(
26152
+ (...inner) => {
26153
+ live.delete(handle);
26154
+ fn(...inner);
26155
+ },
26156
+ delay,
26157
+ ...args
26158
+ );
26159
+ live.add(handle);
26160
+ return handle;
26161
+ };
26162
+ const setIntervalTracked = (fn, delay, ...args) => track(setInterval(fn, delay, ...args));
26163
+ const hostSetImmediate = globalThis.setImmediate;
26164
+ const setImmediateTracked = (fn, ...args) => {
26165
+ const handle = hostSetImmediate ? hostSetImmediate((...inner) => {
26166
+ live.delete(handle);
26167
+ fn(...inner);
26168
+ }, ...args) : setTimeoutTracked(fn, 0, ...args);
26169
+ live.add(handle);
26170
+ return handle;
26171
+ };
26172
+ const clear2 = (handle, native) => {
26173
+ live.delete(handle);
26174
+ native(handle);
26175
+ };
26176
+ return {
26177
+ api: {
26178
+ setTimeout: setTimeoutTracked,
26179
+ setInterval: setIntervalTracked,
26180
+ setImmediate: setImmediateTracked,
26181
+ clearTimeout: (handle) => clear2(handle, clearTimeout),
26182
+ clearInterval: (handle) => clear2(handle, clearInterval),
26183
+ clearImmediate: (handle) => clear2(handle, globalThis.clearImmediate ?? clearTimeout)
26184
+ },
26185
+ pending: () => live.size
26186
+ };
26187
+ }
26188
+ function createTimerPromises() {
26189
+ return {
26190
+ setTimeout: (delay, value) => new Promise((resolve2) => setTimeout(resolve2, delay, value)),
26191
+ setImmediate: (value) => new Promise((resolve2) => setTimeout(resolve2, 0, value))
26192
+ };
26193
+ }
26194
+ function createAsyncHooksModule() {
26195
+ class AsyncResource {
26196
+ constructor(type, _options) {
26197
+ this.type = type;
26198
+ }
26199
+ type;
26200
+ runInAsyncScope(fn, thisArg, ...args) {
26201
+ return fn.apply(thisArg, args);
26202
+ }
26203
+ bind(fn, thisArg) {
26204
+ return ((...args) => this.runInAsyncScope(fn, thisArg, ...args));
26205
+ }
26206
+ emitDestroy() {
26207
+ return this;
26208
+ }
26209
+ asyncId() {
26210
+ return 1;
26211
+ }
26212
+ triggerAsyncId() {
26213
+ return 0;
26214
+ }
26215
+ static bind(fn, type = "bound-anonymous-fn", thisArg) {
26216
+ return new AsyncResource(type).bind(fn, thisArg);
26217
+ }
26218
+ }
26219
+ class AsyncLocalStorage {
26220
+ value;
26221
+ disable() {
26222
+ this.value = void 0;
26223
+ }
26224
+ getStore() {
26225
+ return this.value;
26226
+ }
26227
+ enterWith(store) {
26228
+ this.value = store;
26229
+ }
26230
+ run(store, callback, ...args) {
26231
+ const previous = this.value;
26232
+ this.value = store;
26233
+ try {
26234
+ return callback(...args);
26235
+ } finally {
26236
+ this.value = previous;
26237
+ }
26238
+ }
26239
+ exit(callback, ...args) {
26240
+ const previous = this.value;
26241
+ this.value = void 0;
26242
+ try {
26243
+ return callback(...args);
26244
+ } finally {
26245
+ this.value = previous;
26246
+ }
26247
+ }
26248
+ static bind(fn) {
26249
+ return fn;
26250
+ }
26251
+ static snapshot() {
26252
+ return (fn, ...args) => fn(...args);
26253
+ }
26254
+ }
26255
+ return {
26256
+ AsyncResource,
26257
+ AsyncLocalStorage,
26258
+ executionAsyncId: () => 1,
26259
+ triggerAsyncId: () => 0,
26260
+ executionAsyncResource: () => ({}),
26261
+ createHook: () => ({ enable() {
26262
+ return this;
26263
+ }, disable() {
26264
+ return this;
26265
+ } })
26266
+ };
26267
+ }
26268
+ function createStreamPromises() {
26269
+ return {
26270
+ pipeline: (...streams) => new Promise((resolve2, reject) => {
26271
+ const callback = (error) => error ? reject(error) : resolve2();
26272
+ streamModule3.pipeline(...streams, callback);
26273
+ }),
26274
+ finished: (stream) => new Promise((resolve2, reject) => {
26275
+ streamModule3.finished(stream, (error) => error ? reject(error) : resolve2());
26276
+ })
26277
+ };
26278
+ }
26279
+ function createUnsupportedModule(name) {
26280
+ const unsupported = () => {
26281
+ const error = new Error(`${name} is unavailable in the browser runtime`);
26282
+ error.code = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
26283
+ throw error;
26284
+ };
26285
+ return new Proxy({ unsupported }, { get(target, key) {
26286
+ return key in target ? target[key] : unsupported;
26287
+ } });
26288
+ }
26289
+ var stubNames = ["cluster", "dgram", "diagnostics_channel", "domain", "http2", "inspector", "net", "tls", "v8", "vm", "worker_threads"];
26290
+ var builtinNames2 = [
26291
+ "assert",
26292
+ "assert/strict",
26293
+ "async_hooks",
26294
+ "buffer",
26295
+ "child_process",
26296
+ "console",
26297
+ "constants",
26298
+ "crypto",
26299
+ "events",
26300
+ "fs",
26301
+ "fs/promises",
26302
+ "dns",
26303
+ "dns/promises",
26304
+ "http",
26305
+ "https",
26306
+ "module",
26307
+ "os",
26308
+ "path",
26309
+ "path/posix",
26310
+ "perf_hooks",
26311
+ "process",
26312
+ "punycode",
26313
+ "querystring",
26314
+ "readline",
26315
+ "readline/promises",
26316
+ "stream",
26317
+ "stream/promises",
26318
+ "string_decoder",
26319
+ "timers",
26320
+ "timers/promises",
26321
+ "tty",
26322
+ "url",
26323
+ "util",
26324
+ "util/types",
26325
+ "zlib",
26326
+ ...stubNames
26327
+ ];
26328
+
26329
+ // src/runtime/memory-volume.ts
26330
+ init_path();
26331
+ var VolumeError = class extends Error {
26332
+ constructor(code, operation, path) {
26333
+ super(`${code}: ${operation}, '${path}'`);
26334
+ this.code = code;
26335
+ this.name = "VolumeError";
26336
+ }
26337
+ code;
26338
+ };
26339
+ var MemoryStat = class {
26340
+ constructor(inode) {
26341
+ this.inode = inode;
26342
+ }
26343
+ inode;
26344
+ get mode() {
26345
+ return this.inode.mode;
26346
+ }
26347
+ get size() {
26348
+ return this.inode.kind === "file" ? this.inode.data.length : this.inode.kind === "symlink" ? new TextEncoder().encode(this.inode.target).length : 0;
26349
+ }
26350
+ get uid() {
26351
+ return this.inode.uid;
26352
+ }
26353
+ get gid() {
26354
+ return this.inode.gid;
26355
+ }
26356
+ get ino() {
26357
+ return this.inode.ino;
26358
+ }
26359
+ get nlink() {
26360
+ return this.inode.nlink;
26361
+ }
26362
+ get atimeMs() {
26363
+ return this.inode.atimeMs;
26364
+ }
26365
+ get mtimeMs() {
26366
+ return this.inode.mtimeMs;
26367
+ }
26368
+ get ctimeMs() {
26369
+ return this.inode.ctimeMs;
26370
+ }
26371
+ get birthtimeMs() {
26372
+ return this.inode.birthtimeMs;
26373
+ }
26374
+ isFile() {
26375
+ return this.inode.kind === "file";
26376
+ }
26377
+ isDirectory() {
26378
+ return this.inode.kind === "directory";
26379
+ }
26380
+ isSymbolicLink() {
26381
+ return this.inode.kind === "symlink";
26382
+ }
26383
+ };
26384
+ var encoder6 = new TextEncoder();
26385
+ var MemoryVolume = class {
26386
+ entries = /* @__PURE__ */ new Map();
26387
+ nextIno = 2;
26388
+ constructor() {
26389
+ this.entries.set("/", this.inode("directory", 493));
26390
+ }
26391
+ readFileSync(path) {
26392
+ const key = this.key(path);
26393
+ const node2 = this.required(key, "open");
26394
+ if (node2.kind === "directory") throw new VolumeError("EISDIR", "read", key);
26395
+ if (node2.kind !== "file") throw new VolumeError("EINVAL", "read", key);
26396
+ node2.atimeMs = Date.now();
26397
+ return node2.data.slice();
26398
+ }
26399
+ writeFileSync(path, data) {
26400
+ const key = this.key(path);
26401
+ this.requireParent(key, "open");
26402
+ const bytes = typeof data === "string" ? encoder6.encode(data) : data.slice();
26403
+ const current = this.entries.get(key);
26404
+ if (current?.kind === "directory") throw new VolumeError("EISDIR", "open", key);
26405
+ if (current?.kind === "symlink") throw new VolumeError("EINVAL", "open", key);
26406
+ if (current) {
26407
+ current.data = bytes;
26408
+ this.touchChanged(current, true);
26409
+ } else {
26410
+ this.entries.set(key, this.inode("file", 438, bytes));
26411
+ }
26412
+ }
26413
+ appendFileSync(path, data) {
26414
+ const key = this.key(path);
26415
+ const bytes = typeof data === "string" ? encoder6.encode(data) : data;
26416
+ const current = this.entries.get(key);
26417
+ if (!current) return this.writeFileSync(key, bytes);
26418
+ if (current.kind !== "file") throw new VolumeError(current.kind === "directory" ? "EISDIR" : "EINVAL", "open", key);
26419
+ const next = new Uint8Array(current.data.length + bytes.length);
26420
+ next.set(current.data);
26421
+ next.set(bytes, current.data.length);
26422
+ current.data = next;
26423
+ this.touchChanged(current, true);
26424
+ }
26425
+ readdirSync(path) {
26426
+ const key = this.key(path);
26427
+ const node2 = this.required(key, "scandir");
26428
+ if (node2.kind !== "directory") throw new VolumeError("ENOTDIR", "scandir", key);
26429
+ const prefix = key === "/" ? "/" : `${key}/`;
26430
+ const names = /* @__PURE__ */ new Set();
26431
+ for (const candidate of this.entries.keys()) {
26432
+ if (!candidate.startsWith(prefix) || candidate === key) continue;
26433
+ const rest = candidate.slice(prefix.length);
26434
+ if (rest && !rest.includes("/")) names.add(rest);
26435
+ }
26436
+ node2.atimeMs = Date.now();
26437
+ return [...names].sort();
26438
+ }
26439
+ lstatSync(path) {
26440
+ return new MemoryStat(this.required(this.key(path), "lstat"));
26441
+ }
26442
+ readlinkSync(path) {
26443
+ const key = this.key(path);
26444
+ const node2 = this.required(key, "readlink");
26445
+ if (node2.kind !== "symlink") throw new VolumeError("EINVAL", "readlink", key);
26446
+ return node2.target;
26447
+ }
26448
+ mkdirSync(path, options = {}) {
26449
+ const key = this.key(path);
26450
+ if (this.entries.has(key)) throw new VolumeError("EEXIST", "mkdir", key);
26451
+ this.requireParent(key, "mkdir");
26452
+ this.entries.set(key, this.inode("directory", options.mode ?? 511));
26453
+ }
26454
+ rmdirSync(path) {
26455
+ const key = this.key(path);
26456
+ if (key === "/") throw new VolumeError("EBUSY", "rmdir", key);
26457
+ const node2 = this.required(key, "rmdir");
26458
+ if (node2.kind !== "directory") throw new VolumeError("ENOTDIR", "rmdir", key);
26459
+ const prefix = `${key}/`;
26460
+ if ([...this.entries.keys()].some((candidate) => candidate.startsWith(prefix))) {
26461
+ throw new VolumeError("ENOTEMPTY", "rmdir", key);
26462
+ }
26463
+ this.entries.delete(key);
26464
+ }
26465
+ unlinkSync(path) {
26466
+ const key = this.key(path);
26467
+ const node2 = this.required(key, "unlink");
26468
+ if (node2.kind === "directory") throw new VolumeError("EISDIR", "unlink", key);
26469
+ this.entries.delete(key);
26470
+ node2.nlink--;
26471
+ node2.ctimeMs = Date.now();
26472
+ }
26473
+ renameSync(from, to) {
26474
+ const source = this.key(from);
26475
+ const dest = this.key(to);
26476
+ const node2 = this.required(source, "rename");
26477
+ this.requireParent(dest, "rename");
26478
+ if (source === "/") throw new VolumeError("EBUSY", "rename", source);
26479
+ if (dest.startsWith(`${source}/`)) throw new VolumeError("EINVAL", "rename", source);
26480
+ const existing = this.entries.get(dest);
26481
+ if (existing?.kind === "directory" && this.readdirSync(dest).length > 0) {
26482
+ throw new VolumeError("ENOTEMPTY", "rename", dest);
26483
+ }
26484
+ if (existing) {
26485
+ this.entries.delete(dest);
26486
+ existing.nlink--;
26487
+ }
26488
+ const moved = [...this.entries.entries()].filter(([path]) => path === source || path.startsWith(`${source}/`)).sort(([a], [b]) => a.length - b.length);
26489
+ for (const [path] of moved) this.entries.delete(path);
26490
+ for (const [path, value] of moved) {
26491
+ this.entries.set(dest + path.slice(source.length), value);
26492
+ value.ctimeMs = Date.now();
26493
+ }
26494
+ node2.ctimeMs = Date.now();
26495
+ }
26496
+ symlinkSync(target, path) {
26497
+ const key = this.key(path);
26498
+ if (this.entries.has(key)) throw new VolumeError("EEXIST", "symlink", key);
26499
+ this.requireParent(key, "symlink");
26500
+ const node2 = this.inode("symlink", 511);
26501
+ node2.target = target;
26502
+ this.entries.set(key, node2);
26503
+ }
26504
+ linkSync(existing, path) {
26505
+ const source = this.key(existing);
26506
+ const dest = this.key(path);
26507
+ const node2 = this.required(source, "link");
26508
+ if (node2.kind === "directory") throw new VolumeError("EPERM", "link", source);
26509
+ if (this.entries.has(dest)) throw new VolumeError("EEXIST", "link", dest);
26510
+ this.requireParent(dest, "link");
26511
+ node2.nlink++;
26512
+ node2.ctimeMs = Date.now();
26513
+ this.entries.set(dest, node2);
26514
+ }
26515
+ truncateSync(path, length = 0) {
26516
+ const key = this.key(path);
26517
+ const node2 = this.required(key, "truncate");
26518
+ if (node2.kind !== "file") throw new VolumeError(node2.kind === "directory" ? "EISDIR" : "EINVAL", "truncate", key);
26519
+ const data = new Uint8Array(length);
26520
+ data.set(node2.data.subarray(0, length));
26521
+ node2.data = data;
26522
+ this.touchChanged(node2, true);
26523
+ }
26524
+ chmodSync(path, mode) {
26525
+ this.setMode(path, mode);
26526
+ }
26527
+ lchmodSync(path, mode) {
26528
+ this.setMode(path, mode);
26529
+ }
26530
+ chownSync(path, uid, gid) {
26531
+ this.setOwner(path, uid, gid);
26532
+ }
26533
+ lchownSync(path, uid, gid) {
26534
+ this.setOwner(path, uid, gid);
26535
+ }
26536
+ utimesSync(path, atime, mtime) {
26537
+ const node2 = this.required(this.key(path), "utimes");
26538
+ node2.atimeMs = atime.getTime();
26539
+ node2.mtimeMs = mtime.getTime();
26540
+ node2.ctimeMs = Date.now();
26541
+ }
26542
+ getStats() {
26543
+ const seen = /* @__PURE__ */ new Set();
26544
+ let totalBytes = 0;
26545
+ let fileCount = 0;
26546
+ let directoryCount = 0;
26547
+ for (const node2 of this.entries.values()) {
26548
+ if (seen.has(node2.ino)) continue;
26549
+ seen.add(node2.ino);
26550
+ if (node2.kind === "directory") directoryCount++;
26551
+ else {
26552
+ fileCount++;
26553
+ totalBytes += node2.kind === "file" ? node2.data.length : encoder6.encode(node2.target).length;
26554
+ }
26555
+ }
26556
+ return { totalBytes, fileCount, directoryCount, dirCount: directoryCount };
26557
+ }
26558
+ snapshot() {
26559
+ return [...this.entries.entries()].map(([path, node2]) => ({ path, ...node2, data: [...node2.data] }));
26560
+ }
26561
+ restore(snapshot) {
26562
+ const inodes = /* @__PURE__ */ new Map();
26563
+ const entries = /* @__PURE__ */ new Map();
26564
+ for (const item of snapshot) {
26565
+ let inode = inodes.get(item.ino);
26566
+ if (!inode) {
26567
+ inode = { ...item, data: new Uint8Array(item.data) };
26568
+ inodes.set(item.ino, inode);
26569
+ }
26570
+ entries.set(this.key(item.path), inode);
26571
+ }
26572
+ if (!entries.has("/")) throw new VolumeError("EINVAL", "restore", "/");
26573
+ this.entries.clear();
26574
+ for (const [path, inode] of entries) this.entries.set(path, inode);
26575
+ this.nextIno = Math.max(1, ...inodes.keys()) + 1;
26576
+ }
26577
+ /** Serializable representation used by RuntimePod snapshots. */
26578
+ export() {
26579
+ return [...this.entries.entries()].map(([path, node2]) => ({
26580
+ path,
26581
+ kind: node2.kind,
26582
+ mode: node2.mode,
26583
+ uid: node2.uid,
26584
+ gid: node2.gid,
26585
+ ...node2.kind === "file" ? { data: [...node2.data] } : {},
26586
+ ...node2.kind === "symlink" ? { target: node2.target } : {}
26587
+ }));
26588
+ }
26589
+ setMode(path, mode) {
26590
+ const node2 = this.required(this.key(path), "chmod");
26591
+ node2.mode = mode & 4095;
26592
+ node2.ctimeMs = Date.now();
26593
+ }
26594
+ setOwner(path, uid, gid) {
26595
+ const node2 = this.required(this.key(path), "chown");
26596
+ node2.uid = uid;
26597
+ node2.gid = gid;
26598
+ node2.ctimeMs = Date.now();
26599
+ }
26600
+ key(path) {
26601
+ const clean2 = clean(path);
26602
+ if (!isAbsolute(clean2)) throw new VolumeError("EINVAL", "path", path);
26603
+ return clean2;
26604
+ }
26605
+ required(path, operation) {
26606
+ const node2 = this.entries.get(path);
26607
+ if (!node2) throw new VolumeError("ENOENT", operation, path);
26608
+ return node2;
26609
+ }
26610
+ requireParent(path, operation) {
26611
+ const parent = this.required(dirname(path), operation);
26612
+ if (parent.kind !== "directory") throw new VolumeError("ENOTDIR", operation, path);
26613
+ return parent;
26614
+ }
26615
+ inode(kind, mode, data = new Uint8Array(0)) {
26616
+ const now = Date.now();
26617
+ return {
26618
+ ino: kind === "directory" && this.entries.size === 0 ? 1 : this.nextIno++,
26619
+ kind,
26620
+ mode: mode & 4095,
26621
+ uid: 0,
26622
+ gid: 0,
26623
+ nlink: 1,
26624
+ data,
26625
+ target: "",
26626
+ atimeMs: now,
26627
+ mtimeMs: now,
26628
+ ctimeMs: now,
26629
+ birthtimeMs: now
26630
+ };
26631
+ }
26632
+ touchChanged(node2, modified) {
26633
+ const now = Date.now();
26634
+ node2.ctimeMs = now;
26635
+ if (modified) node2.mtimeMs = now;
26636
+ }
26637
+ };
26638
+
26639
+ // src/pkg/clean-installer.ts
26640
+ init_path();
26641
+ var CleanPackageInstaller = class _CleanPackageInstaller {
26642
+ constructor(volume, options = {}) {
26643
+ this.volume = volume;
26644
+ this.options = options;
26645
+ this.registry = (options.registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
26646
+ this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
26647
+ }
26648
+ volume;
26649
+ options;
26650
+ registry;
26651
+ fetcher;
26652
+ metadata = /* @__PURE__ */ new Map();
26653
+ tarballs = /* @__PURE__ */ new Map();
26654
+ forCwd(cwd) {
26655
+ return new _CleanPackageInstaller(this.volume, { ...this.options, cwd });
26656
+ }
26657
+ async install(name, version = "latest", options = {}) {
26658
+ const cwd = this.options.cwd ?? "/";
26659
+ const manifest = await this.installAt(name, version || "latest", join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26660
+ if (options.persist !== false) this.persist(cwd, name, version, options.persistDev === true);
26661
+ return manifest;
26662
+ }
26663
+ async installFromManifest(path, options = {}) {
26664
+ const project = this.readJson(path);
26665
+ const cwd = dirname(path);
26666
+ const dependencies = {
26667
+ ...project.dependencies ?? {},
26668
+ ...options.withDevDeps === false ? {} : project.devDependencies ?? {}
26669
+ };
26670
+ for (const [name, range] of Object.entries(dependencies)) {
26671
+ await this.installAt(name, range, join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26672
+ }
26673
+ }
26674
+ async installAt(name, range, modulesRoot, options, ancestry) {
26675
+ const metadata = await this.getMetadata(name);
26676
+ const version = resolveVersion(metadata, range);
26677
+ const manifest = metadata.versions[version];
26678
+ if (!manifest) throw new Error(`No matching version found for ${name}@${range}`);
26679
+ const identity = `${name}@${version}`;
26680
+ const target = join(modulesRoot, name);
26681
+ const installed2 = this.tryReadJson(join(target, "package.json"));
26682
+ if (installed2?.version === version) return installed2;
26683
+ if (ancestry.has(identity)) return manifest;
26684
+ options.onProgress?.(`Fetching ${identity}`);
26685
+ const archive = await this.getTarball(manifest.dist.tarball);
26686
+ verifyIntegrity(archive, manifest.dist.integrity, manifest.dist.shasum, identity);
26687
+ this.removeIfPresent(target);
26688
+ mkdirp(this.volume, target);
26689
+ extractNpmTarball(this.volume, archive, target);
26690
+ options.onProgress?.(`Installed ${identity}`);
26691
+ this.createBinLinks(manifest, target, modulesRoot);
26692
+ const nextAncestry = new Set(ancestry).add(identity);
26693
+ const childRoot = join(target, "node_modules");
26694
+ for (const [dependency, dependencyRange] of Object.entries(manifest.dependencies ?? {})) {
26695
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26696
+ }
26697
+ for (const [dependency, dependencyRange] of Object.entries(manifest.optionalDependencies ?? {})) {
26698
+ try {
26699
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26700
+ } catch (error) {
26701
+ options.onProgress?.(`Skipped optional ${dependency}: ${error instanceof Error ? error.message : String(error)}`);
26702
+ }
26703
+ }
26704
+ return manifest;
26705
+ }
26706
+ async getMetadata(name) {
26707
+ let request = this.metadata.get(name);
26708
+ if (!request) {
26709
+ request = (async () => {
26710
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
26711
+ const response = await this.fetcher(`${this.registry}/${encoded}`, {
26712
+ headers: { Accept: "application/vnd.npm.install-v1+json" }
26713
+ });
26714
+ if (!response.ok) throw new Error(`registry returned ${response.status} for ${name}`);
26715
+ return await response.json();
26716
+ })();
26717
+ this.metadata.set(name, request);
26718
+ }
26719
+ return request;
26720
+ }
26721
+ async getTarball(url) {
26722
+ let request = this.tarballs.get(url);
26723
+ if (!request) {
26724
+ request = (async () => {
26725
+ const response = await this.fetcher(url);
26726
+ if (!response.ok) throw new Error(`tarball returned ${response.status}: ${url}`);
26727
+ return new Uint8Array(await response.arrayBuffer());
26728
+ })();
26729
+ this.tarballs.set(url, request);
26730
+ }
26731
+ return request;
26732
+ }
26733
+ createBinLinks(manifest, target, modulesRoot) {
26734
+ if (!manifest.bin) return;
26735
+ const bins = typeof manifest.bin === "string" ? { [unscoped(manifest.name)]: manifest.bin } : manifest.bin;
26736
+ const binDir = join(modulesRoot, ".bin");
26737
+ mkdirp(this.volume, binDir);
26738
+ for (const [name, path] of Object.entries(bins)) {
26739
+ const link = join(binDir, name);
26740
+ this.removeIfPresent(link);
26741
+ this.volume.symlinkSync(relative(binDir, join(target, path)), link);
26742
+ }
26743
+ }
26744
+ persist(cwd, name, range, dev) {
26745
+ const path = join(cwd, "package.json");
26746
+ const manifest = this.tryReadJson(path) ?? {};
26747
+ const key = dev ? "devDependencies" : "dependencies";
26748
+ manifest[key] = { ...manifest[key] ?? {}, [name]: range === "latest" ? "*" : range };
26749
+ this.volume.writeFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
26750
+ }
26751
+ removeIfPresent(path) {
26752
+ let stat2;
26753
+ try {
26754
+ stat2 = this.volume.lstatSync(path);
26755
+ } catch {
26756
+ return;
26757
+ }
26758
+ if (!stat2.isDirectory()) return this.volume.unlinkSync(path);
26759
+ for (const name of this.volume.readdirSync(path)) this.removeIfPresent(join(path, name));
26760
+ this.volume.rmdirSync(path);
26761
+ }
26762
+ readJson(path) {
26763
+ return JSON.parse(new TextDecoder().decode(this.volume.readFileSync(path)));
26764
+ }
26765
+ tryReadJson(path) {
26766
+ try {
26767
+ return this.readJson(path);
26768
+ } catch {
26769
+ return null;
26770
+ }
26771
+ }
26772
+ };
26773
+ function resolveVersion(metadata, range) {
26774
+ const tag = metadata["dist-tags"]?.[range];
26775
+ if (tag) return tag;
26776
+ if (valid(range) && metadata.versions[range]) return range;
26777
+ const found = maxSatisfying(Object.keys(metadata.versions), range === "latest" ? "*" : range, { includePrerelease: false });
26778
+ if (!found) throw new Error(`No matching version found for ${metadata.name}@${range}`);
26779
+ return found;
26780
+ }
26781
+ function verifyIntegrity(data, integrity, shasum, identity) {
26782
+ if (integrity) {
26783
+ const choices = integrity.trim().split(/\s+/);
26784
+ for (const choice of choices) {
26785
+ const dash = choice.indexOf("-");
26786
+ const algorithm = choice.slice(0, dash);
26787
+ const expected = choice.slice(dash + 1).replace(/\?.*$/, "");
26788
+ const digest = algorithm === "sha512" ? sha512(data) : algorithm === "sha256" ? sha256(data) : null;
26789
+ if (digest && Buffer$1.from(digest).toString("base64") === expected) return;
26790
+ }
26791
+ throw new Error(`Integrity check failed for ${identity}`);
26792
+ }
26793
+ if (shasum && Buffer$1.from(sha1(data)).toString("hex") === shasum) return;
26794
+ if (shasum) throw new Error(`Legacy checksum check failed for ${identity}`);
26795
+ }
26796
+ function extractNpmTarball(volume, compressed, destination) {
26797
+ const tar2 = ungzip(compressed);
26798
+ let offset = 0;
26799
+ let longPath = null;
26800
+ let paxPath = null;
26801
+ while (offset + 512 <= tar2.length) {
26802
+ const header = tar2.subarray(offset, offset + 512);
26803
+ if (header.every((byte) => byte === 0)) break;
26804
+ const size = octal(header, 124, 12);
26805
+ const type = String.fromCharCode(header[156] || 48);
26806
+ const prefix = text(header, 345, 155);
26807
+ let name = longPath ?? paxPath ?? [prefix, text(header, 0, 100)].filter(Boolean).join("/");
26808
+ longPath = null;
26809
+ paxPath = null;
26810
+ const data = tar2.subarray(offset + 512, offset + 512 + size);
26811
+ offset += 512 + Math.ceil(size / 512) * 512;
26812
+ if (type === "L") {
26813
+ longPath = new TextDecoder().decode(data).replace(/\0.*$/, "").trim();
26814
+ continue;
26815
+ }
26816
+ if (type === "x" || type === "g") {
26817
+ paxPath = parsePax(data).path ?? null;
26818
+ continue;
26819
+ }
26820
+ name = stripPackageRoot(name);
26821
+ if (!name) continue;
26822
+ const target = safeTarget(destination, name);
26823
+ const mode = octal(header, 100, 8) || 420;
26824
+ if (type === "5") {
26825
+ mkdirp(volume, target, mode);
26826
+ } else if (type === "2") {
26827
+ mkdirp(volume, dirname(target));
26828
+ volume.symlinkSync(text(header, 157, 100), target);
26829
+ } else if (type === "1") {
26830
+ mkdirp(volume, dirname(target));
26831
+ volume.linkSync(safeTarget(destination, stripPackageRoot(text(header, 157, 100))), target);
26832
+ } else if (type === "0" || type === "\0" || type === "7") {
26833
+ mkdirp(volume, dirname(target));
26834
+ volume.writeFileSync(target, data.slice());
26835
+ volume.chmodSync(target, mode);
26836
+ }
26837
+ }
26838
+ }
26839
+ function mkdirp(volume, path, mode = 493) {
26840
+ let current = "";
26841
+ for (const part of segments(path)) {
26842
+ current += `/${part}`;
26843
+ try {
26844
+ volume.mkdirSync(current, { mode });
26845
+ } catch (error) {
26846
+ if (error.code !== "EEXIST") throw error;
26847
+ if (!volume.lstatSync(current).isDirectory()) throw error;
26848
+ }
26849
+ }
26850
+ }
26851
+ function safeTarget(destination, name) {
26852
+ const clean2 = clean(`/${name}`).slice(1);
26853
+ if (!clean2 || clean2 === ".." || clean2.startsWith("../") || name.startsWith("/")) throw new Error(`Unsafe path in package: ${name}`);
26854
+ return join(destination, clean2);
26855
+ }
26856
+ function stripPackageRoot(name) {
26857
+ return name.replace(/^\.\//, "").replace(/^package\//, "").replace(/\/$/, "");
26858
+ }
26859
+ function text(bytes, start, length) {
26860
+ return new TextDecoder().decode(bytes.subarray(start, start + length)).replace(/\0.*$/, "").trim();
26861
+ }
26862
+ function octal(bytes, start, length) {
26863
+ return parseInt(text(bytes, start, length).replace(/^0+/, "") || "0", 8);
26864
+ }
26865
+ function parsePax(data) {
26866
+ const value = new TextDecoder().decode(data);
26867
+ const result = {};
26868
+ let offset = 0;
26869
+ while (offset < value.length) {
26870
+ const space = value.indexOf(" ", offset);
26871
+ if (space < 0) break;
26872
+ const length = Number(value.slice(offset, space));
26873
+ if (!Number.isFinite(length) || length <= 0) break;
26874
+ const record = value.slice(space + 1, offset + length - 1);
26875
+ const equal = record.indexOf("=");
26876
+ if (equal > 0) result[record.slice(0, equal)] = record.slice(equal + 1);
26877
+ offset += length;
26878
+ }
26879
+ return result;
26880
+ }
26881
+ function unscoped(name) {
26882
+ return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
26883
+ }
26884
+
26885
+ // src/runtime/host-esbuild.ts
26886
+ var cached = null;
26887
+ function loadHostEsbuild() {
26888
+ cached ??= load().catch((error) => {
26889
+ if (typeof process !== "undefined" && process.env?.SANDBOXEDJS_DEBUG) {
26890
+ console.error("[sandboxedjs] host esbuild unavailable:", error);
26891
+ }
26892
+ return null;
26893
+ });
26894
+ return cached;
26895
+ }
26896
+ async function load() {
26897
+ if (typeof process === "undefined" || process.versions?.node == null) return null;
26898
+ for (const specifier of ["esbuild-wasm", "esbuild"]) {
26899
+ try {
26900
+ const esbuild = await nodeOnlyModule(specifier);
26901
+ const api = esbuild.default ?? esbuild;
26902
+ if (specifier === "esbuild-wasm") await api.initialize({});
26903
+ return api;
26904
+ } catch {
26905
+ }
26906
+ }
26907
+ return null;
26908
+ }
26909
+
26910
+ // src/runtime/local-runtime-pod.ts
26911
+ var WASM_ALIASES = {
26912
+ esbuild: "esbuild-wasm",
26913
+ rollup: "@rollup/wasm-node"
26914
+ };
26915
+ var ProcessExit = class extends Error {
26916
+ constructor(code) {
26917
+ super(`process exited with code ${code}`);
26918
+ this.code = code;
26919
+ }
26920
+ code;
26921
+ };
26922
+ var LocalProcess = class extends EventEmitter3 {
26923
+ constructor(task) {
26924
+ super();
26925
+ this.task = task;
26926
+ super.on("error", () => {
26927
+ });
26928
+ this.completion = new Promise((resolve2) => {
26929
+ this.resolveCompletion = resolve2;
26930
+ });
26931
+ setTimeout(() => void this.start(), 0);
26932
+ }
26933
+ task;
26934
+ completion;
26935
+ resolveCompletion;
26936
+ settled = false;
26937
+ killed = false;
26938
+ out = [];
26939
+ err = [];
26940
+ resolveKilled;
26941
+ killedPromise = new Promise((resolve2) => {
26942
+ this.resolveKilled = resolve2;
26943
+ });
26944
+ on(event, listener) {
26945
+ return super.on(event, listener);
26946
+ }
26947
+ output(text2) {
26948
+ this.out.push(text2);
26949
+ this.emit("output", text2);
26950
+ }
26951
+ error(text2) {
26952
+ this.err.push(text2);
26953
+ this.emit("error", text2);
26954
+ }
26955
+ write(_data) {
26956
+ }
26957
+ kill(_signal = "SIGTERM") {
26958
+ this.killed = true;
26959
+ this.resolveKilled();
26960
+ }
26961
+ waitForKill() {
26962
+ return this.killedPromise;
26963
+ }
26964
+ /** End the process now, for an asynchronous `process.exit`. */
26965
+ exitNow(code) {
26966
+ this.finish(code);
26967
+ this.resolveKilled();
26968
+ }
26969
+ async start() {
26970
+ if (this.killed) {
26971
+ this.finish(137);
26972
+ return;
26973
+ }
26974
+ try {
26975
+ this.finish(await this.task(this));
26976
+ } catch (error) {
26977
+ if (error instanceof ProcessExit) this.finish(error.code);
26978
+ else {
26979
+ this.error(formatError(error));
26980
+ this.finish(1);
26981
+ }
26982
+ }
26983
+ }
26984
+ finish(exitCode) {
26985
+ if (this.settled) return;
26986
+ this.settled = true;
26987
+ const result = { exitCode, stdout: this.out.join(""), stderr: this.err.join("") };
26988
+ this.emit("exit", exitCode);
26989
+ this.resolveCompletion(result);
26990
+ }
26991
+ };
26992
+ var PodChildProcess = class {
26993
+ constructor(pid, config, launch) {
26994
+ this.pid = pid;
26995
+ this.config = config;
26996
+ this.launch = launch;
26997
+ }
26998
+ pid;
26999
+ config;
27000
+ launch;
27001
+ state = "starting";
27002
+ exitCode;
27003
+ stdout = "";
27004
+ stderr = "";
27005
+ listeners = /* @__PURE__ */ new Map();
27006
+ started = false;
27007
+ cancelled = false;
27008
+ child;
27009
+ on(event, listener) {
27010
+ let set = this.listeners.get(event);
27011
+ if (!set) this.listeners.set(event, set = /* @__PURE__ */ new Set());
27012
+ set.add(listener);
27013
+ return this;
27014
+ }
27015
+ emit(event, ...args) {
27016
+ for (const listener of this.listeners.get(event) ?? []) listener(...args);
27017
+ }
27018
+ exec() {
27019
+ if (this.started) return;
27020
+ this.started = true;
27021
+ queueMicrotask(() => {
27022
+ if (this.cancelled) {
27023
+ this.finish(143);
27024
+ return;
27025
+ }
27026
+ this.state = "running";
27027
+ void this.launch(this.config).then(
27028
+ (child) => {
27029
+ this.child = child;
27030
+ if (this.cancelled) child.kill();
27031
+ child.on("output", (text2) => {
27032
+ this.stdout += text2;
27033
+ this.emit("stdout", text2);
27034
+ });
27035
+ child.on("error", (text2) => {
27036
+ this.stderr += text2;
27037
+ this.emit("stderr", text2);
27038
+ });
27039
+ void child.completion.then((result) => this.finish(result.exitCode));
27040
+ },
27041
+ (error) => {
27042
+ const text2 = error instanceof Error ? `${error.message}
27043
+ ` : `${String(error)}
27044
+ `;
27045
+ this.stderr += text2;
27046
+ this.emit("stderr", text2);
27047
+ this.finish(127);
27048
+ }
27049
+ );
27050
+ });
27051
+ }
27052
+ sendStdin(data) {
27053
+ this.child?.write(data);
27054
+ }
27055
+ kill(signal = "SIGTERM") {
27056
+ if (this.child) this.child.kill(signal);
27057
+ else this.cancelled = true;
27058
+ }
27059
+ finish(code) {
27060
+ if (this.state === "exited") return;
27061
+ this.state = "exited";
27062
+ this.exitCode = code;
27063
+ this.emit("exit", code);
27064
+ }
27065
+ };
27066
+ var nextChildPid = 805306368;
27067
+ var LocalRuntimePod = class _LocalRuntimePod {
27068
+ volume = new MemoryVolume();
27069
+ packages;
27070
+ instanceId = `sbx-${Math.random().toString(36).slice(2)}`;
27071
+ router = new VirtualHttpRouter();
27072
+ proxy = { activePorts: (_instanceId) => this.router.activePorts() };
27073
+ /**
27074
+ * Mutable on purpose: a container replaces `spawn` so that children resolve
27075
+ * against the kernel's PATH. Left alone, it runs `node` and reports anything
27076
+ * else as not found, which is the correct answer for a bare pod.
27077
+ */
27078
+ processManager = {
27079
+ spawn: (config) => new PodChildProcess(
27080
+ nextChildPid++,
27081
+ config,
27082
+ (child) => this.spawn(child.command, child.args ?? [], {
27083
+ ...child.cwd ? { cwd: child.cwd } : {},
27084
+ ...child.env ? { env: child.env } : {}
27085
+ })
27086
+ )
27087
+ };
27088
+ disposed = false;
27089
+ workdir;
27090
+ env;
27091
+ aliases;
27092
+ modules;
27093
+ constructor(options) {
27094
+ this.workdir = options.workdir ?? "/";
27095
+ this.env = { ...options.env };
27096
+ this.aliases = { ...WASM_ALIASES, ...options.aliases };
27097
+ this.modules = { ...options.modules };
27098
+ this.packages = new CleanPackageInstaller(this.volume, {
27099
+ cwd: this.workdir,
27100
+ ...options.registry ? { registry: options.registry } : {},
27101
+ ...options.fetch ? { fetch: options.fetch } : {}
27102
+ });
27103
+ this.seed(options.files ?? {});
27104
+ }
27105
+ static async boot(options = {}) {
27106
+ const pod = new _LocalRuntimePod(options);
27107
+ if (options.hostEsbuild !== false && !pod.modules.esbuild) {
27108
+ const esbuild = await loadHostEsbuild();
27109
+ if (esbuild) pod.modules.esbuild = esbuild;
27110
+ }
27111
+ return pod;
27112
+ }
27113
+ async spawn(command, args = [], options = {}) {
27114
+ this.assertActive();
27115
+ if (command !== "node" && command !== "nodejs") throw commandError(command);
27116
+ const script = args[0];
27117
+ if (!script) throw new Error("node: a script path is required");
27118
+ const cwd = typeof options.cwd === "string" ? options.cwd : this.workdir;
27119
+ const env2 = { ...this.env, ...isRecord(options.env) ? options.env : {} };
27120
+ const owner = `${this.instanceId}:${Math.random().toString(36).slice(2)}`;
27121
+ return new LocalProcess(async (proc) => {
27122
+ let requestedExit = 0;
27123
+ let evaluating = true;
27124
+ const core = createCoreModules({
27125
+ volume: this.volume,
27126
+ cwd,
27127
+ env: env2,
27128
+ argv: Array.isArray(options.argv) ? options.argv : ["/usr/bin/node", script, ...args.slice(1)],
27129
+ stdout: (text2) => proc.output(text2),
27130
+ stderr: (text2) => proc.error(text2),
27131
+ onExit: (code) => {
27132
+ requestedExit = code;
27133
+ if (evaluating) throw new ProcessExit(code);
27134
+ proc.exitNow(code);
27135
+ },
27136
+ http: { router: this.router, owner },
27137
+ spawnChild: (config) => this.processManager.spawn(config)
27138
+ });
27139
+ const engine = new CommonJsEngine(this.volume, {
27140
+ cwd,
27141
+ builtins: core.builtins,
27142
+ globals: core.globals,
27143
+ aliases: this.aliases,
27144
+ overrides: this.modules
27145
+ });
27146
+ try {
27147
+ try {
27148
+ await engine.run(script);
27149
+ } finally {
27150
+ evaluating = false;
27151
+ }
27152
+ await this.settle(owner, core.pendingHandles);
27153
+ if (this.router.activePorts(owner).length) {
27154
+ await proc.waitForKill();
27155
+ return 137;
27156
+ }
27157
+ return requestedExit;
27158
+ } finally {
27159
+ this.router.closeOwner(owner);
27160
+ }
27161
+ });
27162
+ }
27163
+ /**
27164
+ * Wait until the process has either started serving or genuinely run out of
27165
+ * work.
27166
+ *
27167
+ * Timers are the observable half of the event loop, so a process with none
27168
+ * outstanding and no port open has finished — and, being the common case for
27169
+ * a plain script, is settled without waiting at all.
27170
+ */
27171
+ async settle(owner, pendingHandles) {
27172
+ while (!this.router.activePorts(owner).length && pendingHandles() > 0) {
27173
+ await new Promise((resolve2) => setTimeout(resolve2, 5));
27174
+ }
27175
+ }
27176
+ async request(_port, _init = {}) {
27177
+ return this.router.request(_port, _init);
27178
+ }
27179
+ snapshot() {
27180
+ this.assertActive();
27181
+ return this.volume.snapshot();
27182
+ }
27183
+ async restore(snapshot) {
27184
+ this.assertActive();
27185
+ if (!Array.isArray(snapshot)) throw new TypeError("invalid runtime snapshot");
27186
+ this.volume.restore(snapshot);
27187
+ }
27188
+ teardown() {
27189
+ this.disposed = true;
27190
+ this.router.closeAll();
27191
+ }
27192
+ seed(files) {
27193
+ for (const [path, data] of Object.entries(files)) {
27194
+ const parts = path.split("/").filter(Boolean);
27195
+ let parent = "";
27196
+ for (const part of parts.slice(0, -1)) {
27197
+ parent += `/${part}`;
27198
+ try {
27199
+ this.volume.mkdirSync(parent);
27200
+ } catch (error) {
27201
+ if (error.code !== "EEXIST") throw error;
27202
+ }
27203
+ }
27204
+ this.volume.writeFileSync(path, data);
27205
+ }
27206
+ }
27207
+ assertActive() {
27208
+ if (this.disposed) throw new Error("runtime has been disposed");
27209
+ }
27210
+ };
27211
+ function commandError(command) {
27212
+ return Object.assign(new Error(`${command}: command not found`), { code: "ENOENT" });
27213
+ }
27214
+ function formatError(error) {
27215
+ if (error instanceof Error) return `${error.stack ?? `${error.name}: ${error.message}`}
27216
+ `;
27217
+ return `${String(error)}
27218
+ `;
27219
+ }
27220
+ function isRecord(value) {
27221
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27222
+ }
27223
+
23886
27224
  // src/container/container.ts
23887
27225
  var Container = class _Container {
23888
27226
  kernel;
@@ -23927,8 +27265,8 @@ var Container = class _Container {
23927
27265
  // ── boot ──────────────────────────────────────────────────────────────────
23928
27266
  static async create(opts = {}) {
23929
27267
  if (opts.python) configurePython(opts.python);
23930
- if (!opts.pod && isNodeRuntime()) await installEsbuildRuntime();
23931
- const pod = opts.pod ?? (isNodeRuntime() ? await bootHeadlessPod(opts) : await bootBrowserPod(opts));
27268
+ if (!opts.pod && opts.runtime !== "sandboxedjs" && isNodeRuntime()) await installEsbuildRuntime();
27269
+ const pod = opts.pod ?? (opts.runtime === "sandboxedjs" ? await LocalRuntimePod.boot({ workdir: opts.cwd ?? "/", env: opts.env ?? {} }) : isNodeRuntime() ? await bootHeadlessPod(opts) : await bootBrowserPod(opts));
23932
27270
  const kernel = new Kernel({
23933
27271
  pod,
23934
27272
  hostname: opts.hostname ?? "sandbox",
@@ -24172,16 +27510,16 @@ var Container = class _Container {
24172
27510
  const combined = [];
24173
27511
  const decoder7 = new TextDecoder();
24174
27512
  const stdout = new BufferSink((chunk) => {
24175
- const text = decoder7.decode(chunk, { stream: true });
24176
- combined.push(text);
24177
- opts.onStdout?.(text);
24178
- this.hooks.onStdout?.(text);
27513
+ const text2 = decoder7.decode(chunk, { stream: true });
27514
+ combined.push(text2);
27515
+ opts.onStdout?.(text2);
27516
+ this.hooks.onStdout?.(text2);
24179
27517
  });
24180
27518
  const stderr = new BufferSink((chunk) => {
24181
- const text = decoder7.decode(chunk, { stream: true });
24182
- combined.push(text);
24183
- opts.onStderr?.(text);
24184
- this.hooks.onStderr?.(text);
27519
+ const text2 = decoder7.decode(chunk, { stream: true });
27520
+ combined.push(text2);
27521
+ opts.onStderr?.(text2);
27522
+ this.hooks.onStderr?.(text2);
24185
27523
  });
24186
27524
  if (opts.tty) {
24187
27525
  stdout.isTTY = true;
@@ -24442,8 +27780,8 @@ var Terminal = class {
24442
27780
  return this.closed;
24443
27781
  }
24444
27782
  // ── rendering ─────────────────────────────────────────────────────────────
24445
- write(text) {
24446
- this.opts.write(text);
27783
+ write(text2) {
27784
+ this.opts.write(text2);
24447
27785
  }
24448
27786
  promptText() {
24449
27787
  if (this.opts.prompt) return this.opts.prompt(this.session);
@@ -24710,7 +28048,7 @@ var Terminal = class {
24710
28048
  stdin.isTTY = true;
24711
28049
  stdin.interactive = true;
24712
28050
  this.currentStdin = stdin;
24713
- const sink = new CallbackSink((text) => this.write(text.replace(/(?<!\r)\n/g, "\r\n")), {
28051
+ const sink = new CallbackSink((text2) => this.write(text2.replace(/(?<!\r)\n/g, "\r\n")), {
24714
28052
  isTTY: true,
24715
28053
  columns: this.columns,
24716
28054
  rows: this.rows
@@ -24819,6 +28157,6 @@ init_expand();
24819
28157
  init_builtins();
24820
28158
  var src_default = createContainer;
24821
28159
 
24822
- export { ArithError, BufferSink, CallbackSink, CommandRegistry, Container, ContainerFs, ERRNO, FileInput, FileOutput, IncompleteInputError, KERNEL_NAME, KERNEL_RELEASE, Kernel, NODE_VERSION, NPM_VERSION, NetworkStack, NullInput, NullOutput, OS_RELEASE, PYTHON_VERSION, Pipe, Process, ProcessTable, ROOT_CRED, SIGNALS, SIGNAL_NAMES, Session, Shell, ShellExit, Lexer as ShellLexer, ShellSyntaxError, Stats, SysError, TeeOutput, Terminal, UserDatabase, Variables, Vfs, allCommands, applyChmod, braceExpand, buildRootfs, builtinNames, captureStdio, configureCPython, configurePython, createContainer, createContext, src_default as default, defineCommand, evalArith, exitCodeForSignal, expandPrompt, expandWord, expandWords, fnmatch, formatMode, getBuiltin, glob, globToRegex, hasMagic, installUserland, isBuiltinName, isCPythonAvailable, isPythonAvailable, isSysError, makeCred, normalizeSignal, octalMode, parse as parseShell, parseUmask, path_exports as posixPath, resetPidCounter, shellQuote, strerror, unameInfo };
28160
+ export { ArithError, BufferSink, CallbackSink, CleanPackageInstaller, CommandRegistry, CommonJsEngine, Container, ContainerFs, ERRNO, FileInput, FileOutput, IncompleteInputError, KERNEL_NAME, KERNEL_RELEASE, Kernel, LocalRuntimePod, MemoryVolume, NODE_VERSION, NPM_VERSION, NetworkStack, NullInput, NullOutput, OS_RELEASE, PYTHON_VERSION, Pipe, Process, ProcessTable, ROOT_CRED, SIGNALS, SIGNAL_NAMES, Session, Shell, ShellExit, Lexer as ShellLexer, ShellSyntaxError, Stats, SysError, TeeOutput, Terminal, UserDatabase, Variables, Vfs, VirtualHttpRouter, VirtualHttpServer, VirtualIncomingMessage, VirtualServerResponse, WASM_ALIASES, allCommands, applyChmod, braceExpand, buildRootfs, builtinNames, captureStdio, configureCPython, configurePython, createChildProcessModule, createContainer, createContext, createCoreModules, src_default as default, defineCommand, evalArith, exitCodeForSignal, expandPrompt, expandWord, expandWords, extractNpmTarball, fnmatch, formatMode, getBuiltin, glob, globToRegex, hasMagic, installUserland, isBuiltinName, isCPythonAvailable, isPythonAvailable, isSysError, looksLikeEsm, makeCred, normalizeSignal, octalMode, parse as parseShell, parseUmask, path_exports as posixPath, resetPidCounter, shellQuote, strerror, transformEsm, unameInfo };
24823
28161
  //# sourceMappingURL=index.js.map
24824
28162
  //# sourceMappingURL=index.js.map