sandboxedjs 0.2.21 → 0.2.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,11 +1,12 @@
1
1
  import { Inflate as Inflate$1, Deflate as Deflate$1, inflateRaw, ungzip, gzip as gzip$1, deflate as deflate$1, inflate as inflate$1, deflateRaw } from 'pako';
2
2
  import { sha256, sha224 } from '@noble/hashes/sha256';
3
- import { Parser as Parser$1, parse as parse$1 } from 'acorn';
4
- import jsx from 'acorn-jsx';
5
3
  import { Buffer as Buffer$1 } from 'buffer/index.js';
6
4
  import { sha512, sha384 } from '@noble/hashes/sha512';
7
5
  import { sha1 } from '@noble/hashes/sha1';
8
6
  import { valid, maxSatisfying } from 'semver';
7
+ import { Parser as Parser$1, parse as parse$1 } from 'acorn';
8
+ import jsx from 'acorn-jsx';
9
+ import { transform } from 'sucrase';
9
10
  import EventEmitter4 from 'events/events.js';
10
11
  import { exports as exports$1, imports } from 'resolve.exports';
11
12
  import pathModule from 'path-browserify';
@@ -4129,9 +4130,9 @@ async function randomUuid() {
4129
4130
  const { randomUUID } = await nodeCrypto();
4130
4131
  return randomUUID();
4131
4132
  }
4132
- function toHex(bytes2) {
4133
+ function toHex(bytes3) {
4133
4134
  let out = "";
4134
- for (const byte of bytes2) out += byte.toString(16).padStart(2, "0");
4135
+ for (const byte of bytes3) out += byte.toString(16).padStart(2, "0");
4135
4136
  return out;
4136
4137
  }
4137
4138
  function md5Hex(input) {
@@ -4869,12 +4870,12 @@ var Vfs = class {
4869
4870
  writeFile(abs, data, opts = {}) {
4870
4871
  const cred = opts.privileged ? void 0 : opts.cred;
4871
4872
  const real = this.resolvePath(abs, { cred });
4872
- const bytes2 = typeof data === "string" ? encoder.encode(data) : data;
4873
+ const bytes3 = typeof data === "string" ? encoder.encode(data) : data;
4873
4874
  const virt = this.lookupVirtual(real);
4874
4875
  if (virt) {
4875
4876
  if (!virt.write) throw new SysError("EACCES", "write", real);
4876
4877
  this.require(this.statFromVirtual(real, virt), W_OK, cred, "open", real);
4877
- virt.write(bytes2, opts.append ?? false);
4878
+ virt.write(bytes3, opts.append ?? false);
4878
4879
  return;
4879
4880
  }
4880
4881
  if (this.isUnderProvider(real)) throw new SysError("ENOENT", "open", real);
@@ -4889,8 +4890,8 @@ var Vfs = class {
4889
4890
  this.require(pst, W_OK | X_OK, cred, "open", real);
4890
4891
  }
4891
4892
  try {
4892
- if (opts.append && existing) this.volume.appendFileSync(real, bytes2);
4893
- else this.volume.writeFileSync(real, bytes2);
4893
+ if (opts.append && existing) this.volume.appendFileSync(real, bytes3);
4894
+ else this.volume.writeFileSync(real, bytes3);
4894
4895
  } catch (e) {
4895
4896
  throw toSysError(e, "open", real);
4896
4897
  }
@@ -5142,7 +5143,7 @@ var Vfs = class {
5142
5143
  usage(abs = "/") {
5143
5144
  let files = 0;
5144
5145
  let dirs = 0;
5145
- let bytes2 = 0;
5146
+ let bytes3 = 0;
5146
5147
  for (const p of this.walk(abs)) {
5147
5148
  let st = null;
5148
5149
  try {
@@ -5153,10 +5154,10 @@ var Vfs = class {
5153
5154
  if (st.isDirectory()) dirs++;
5154
5155
  else {
5155
5156
  files++;
5156
- bytes2 += st.size;
5157
+ bytes3 += st.size;
5157
5158
  }
5158
5159
  }
5159
- return { files, dirs, bytes: bytes2 };
5160
+ return { files, dirs, bytes: bytes3 };
5160
5161
  }
5161
5162
  };
5162
5163
 
@@ -5240,10 +5241,10 @@ var Pipe = class _Pipe {
5240
5241
  write(data) {
5241
5242
  if (this.readerClosed) throw new SysError("EPIPE", "write");
5242
5243
  if (this.writerClosed) return;
5243
- const bytes2 = this.icrnl && !this.raw ? translateCarriageReturns(toBytes(data)) : toBytes(data);
5244
- if (bytes2.length === 0) return;
5245
- this.chunks.push(bytes2);
5246
- this.buffered += bytes2.length;
5244
+ const bytes3 = this.icrnl && !this.raw ? translateCarriageReturns(toBytes(data)) : toBytes(data);
5245
+ if (bytes3.length === 0) return;
5246
+ this.chunks.push(bytes3);
5247
+ this.buffered += bytes3.length;
5247
5248
  this.wake();
5248
5249
  }
5249
5250
  end() {
@@ -5333,15 +5334,15 @@ var Pipe = class _Pipe {
5333
5334
  return p;
5334
5335
  }
5335
5336
  };
5336
- function translateCarriageReturns(bytes2) {
5337
- if (!bytes2.includes(CR)) return bytes2;
5338
- const out = new Uint8Array(bytes2.length);
5337
+ function translateCarriageReturns(bytes3) {
5338
+ if (!bytes3.includes(CR)) return bytes3;
5339
+ const out = new Uint8Array(bytes3.length);
5339
5340
  let length = 0;
5340
- for (let index = 0; index < bytes2.length; index += 1) {
5341
- const byte = bytes2[index];
5341
+ for (let index = 0; index < bytes3.length; index += 1) {
5342
+ const byte = bytes3[index];
5342
5343
  if (byte === CR) {
5343
5344
  out[length++] = LF;
5344
- if (bytes2[index + 1] === LF) index += 1;
5345
+ if (bytes3[index + 1] === LF) index += 1;
5345
5346
  } else {
5346
5347
  out[length++] = byte;
5347
5348
  }
@@ -5387,11 +5388,11 @@ var BufferSink = class {
5387
5388
  }
5388
5389
  write(data) {
5389
5390
  if (this._closed) return;
5390
- const bytes2 = toBytes(data);
5391
- if (bytes2.length === 0) return;
5392
- this.chunks.push(bytes2);
5393
- this.total += bytes2.length;
5394
- this.onWrite?.(bytes2);
5391
+ const bytes3 = toBytes(data);
5392
+ if (bytes3.length === 0) return;
5393
+ this.chunks.push(bytes3);
5394
+ this.total += bytes3.length;
5395
+ this.onWrite?.(bytes3);
5395
5396
  }
5396
5397
  end() {
5397
5398
  this._closed = true;
@@ -6280,8 +6281,8 @@ var SIZEOF_FDSTAT = 24;
6280
6281
  var SIZEOF_DIRENT = 24;
6281
6282
  var SIZEOF_SUBSCRIPTION = 48;
6282
6283
  var SIZEOF_EVENT = 32;
6283
- function isWasmBinary(bytes2) {
6284
- return bytes2.length >= 4 && bytes2[0] === 0 && bytes2[1] === 97 && bytes2[2] === 115 && bytes2[3] === 109;
6284
+ function isWasmBinary(bytes3) {
6285
+ return bytes3.length >= 4 && bytes3[0] === 0 && bytes3[1] === 97 && bytes3[2] === 115 && bytes3[3] === 109;
6285
6286
  }
6286
6287
 
6287
6288
  // src/wasi/host.ts
@@ -7071,8 +7072,8 @@ function defaultSleep(milliseconds) {
7071
7072
  // src/wasi/run.ts
7072
7073
  var compiled = /* @__PURE__ */ new Map();
7073
7074
  var MAX_CACHED_MODULES = 32;
7074
- async function runWasi(ctx, bytes2, options = {}) {
7075
- if (!isWasmBinary(bytes2)) {
7075
+ async function runWasi(ctx, bytes3, options = {}) {
7076
+ if (!isWasmBinary(bytes3)) {
7076
7077
  ctx.warn("cannot execute binary file: not a WebAssembly module");
7077
7078
  return EXIT_NOT_EXECUTABLE;
7078
7079
  }
@@ -7096,7 +7097,7 @@ async function runWasi(ctx, bytes2, options = {}) {
7096
7097
  });
7097
7098
  let instance;
7098
7099
  try {
7099
- const module = await compile(bytes2);
7100
+ const module = await compile(bytes3);
7100
7101
  instance = await WebAssembly.instantiate(module, {
7101
7102
  ...options.imports,
7102
7103
  wasi_snapshot_preview1: host2.wasiImport,
@@ -7132,15 +7133,15 @@ async function runWasi(ctx, bytes2, options = {}) {
7132
7133
  }
7133
7134
  }
7134
7135
  }
7135
- async function compile(bytes2) {
7136
- const key = await digest(bytes2);
7136
+ async function compile(bytes3) {
7137
+ const key = await digest(bytes3);
7137
7138
  const hit = compiled.get(key);
7138
7139
  if (hit) {
7139
7140
  compiled.delete(key);
7140
7141
  compiled.set(key, hit);
7141
7142
  return hit;
7142
7143
  }
7143
- const module = await WebAssembly.compile(sliceForWasm(bytes2));
7144
+ const module = await WebAssembly.compile(sliceForWasm(bytes3));
7144
7145
  compiled.set(key, module);
7145
7146
  if (compiled.size > MAX_CACHED_MODULES) {
7146
7147
  const oldest = compiled.keys().next().value;
@@ -7148,12 +7149,12 @@ async function compile(bytes2) {
7148
7149
  }
7149
7150
  return module;
7150
7151
  }
7151
- async function digest(bytes2) {
7152
- const hash = await crypto.subtle.digest("SHA-256", sliceForWasm(bytes2));
7152
+ async function digest(bytes3) {
7153
+ const hash = await crypto.subtle.digest("SHA-256", sliceForWasm(bytes3));
7153
7154
  return Array.from(new Uint8Array(hash, 0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
7154
7155
  }
7155
- function sliceForWasm(bytes2) {
7156
- return bytes2.buffer.slice(bytes2.byteOffset, bytes2.byteOffset + bytes2.byteLength);
7156
+ function sliceForWasm(bytes3) {
7157
+ return bytes3.buffer.slice(bytes3.byteOffset, bytes3.byteOffset + bytes3.byteLength);
7157
7158
  }
7158
7159
  async function primeStdin(ctx) {
7159
7160
  let pending = new Uint8Array(0);
@@ -7185,19 +7186,19 @@ function describeStartupFailure(error) {
7185
7186
  }
7186
7187
 
7187
7188
  // src/compat/execution.ts
7188
- function binaryDigest(bytes2) {
7189
- return Array.from(sha256(bytes2), (b) => b.toString(16).padStart(2, "0")).join("");
7189
+ function binaryDigest(bytes3) {
7190
+ return Array.from(sha256(bytes3), (b) => b.toString(16).padStart(2, "0")).join("");
7190
7191
  }
7191
- function isElfBinary(bytes2) {
7192
- return bytes2[0] === 127 && bytes2[1] === 69 && bytes2[2] === 76 && bytes2[3] === 70;
7192
+ function isElfBinary(bytes3) {
7193
+ return bytes3[0] === 127 && bytes3[1] === 69 && bytes3[2] === 76 && bytes3[3] === 70;
7193
7194
  }
7194
- function inspectElf(bytes2) {
7195
- if (!isElfBinary(bytes2) || ![1, 2].includes(bytes2[4]) || ![1, 2].includes(bytes2[5]) || bytes2[6] !== 1 || bytes2.length < (bytes2[4] === 2 ? 64 : 52)) throw new Error("invalid or truncated ELF header");
7196
- const littleEndian = bytes2[5] === 1;
7197
- const machine = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength).getUint16(18, littleEndian);
7195
+ function inspectElf(bytes3) {
7196
+ if (!isElfBinary(bytes3) || ![1, 2].includes(bytes3[4]) || ![1, 2].includes(bytes3[5]) || bytes3[6] !== 1 || bytes3.length < (bytes3[4] === 2 ? 64 : 52)) throw new Error("invalid or truncated ELF header");
7197
+ const littleEndian = bytes3[5] === 1;
7198
+ const machine = new DataView(bytes3.buffer, bytes3.byteOffset, bytes3.byteLength).getUint16(18, littleEndian);
7198
7199
  return {
7199
7200
  format: "elf",
7200
- bits: bytes2[4] === 2 ? 64 : 32,
7201
+ bits: bytes3[4] === 2 ? 64 : 32,
7201
7202
  machine,
7202
7203
  littleEndian,
7203
7204
  architecture: { 3: "x86", 62: "x86_64", 40: "arm", 183: "aarch64", 243: "riscv" }[machine] ?? `machine-${machine}`
@@ -7224,14 +7225,14 @@ var BinaryExecutionRegistry = class {
7224
7225
  return this.backends.map(({ id, tier }) => ({ id, tier }));
7225
7226
  }
7226
7227
  async run(ctx, path) {
7227
- const bytes2 = ctx.vfs.readFile(path, ctx.cred);
7228
+ const bytes3 = ctx.vfs.readFile(path, ctx.cred);
7228
7229
  let info2;
7229
7230
  try {
7230
- info2 = inspectElf(bytes2);
7231
+ info2 = inspectElf(bytes3);
7231
7232
  } catch (error) {
7232
7233
  return ctx.fail(String(error), 126);
7233
7234
  }
7234
- const request = { path, bytes: bytes2, info: info2, sha256: binaryDigest(bytes2) };
7235
+ const request = { path, bytes: bytes3, info: info2, sha256: binaryDigest(bytes3) };
7235
7236
  const reasons = [];
7236
7237
  const backends = [...this.backends];
7237
7238
  for (const tier of ["compatibility", "translation", "emulation"]) {
@@ -7254,10 +7255,10 @@ var BinaryExecutionRegistry = class {
7254
7255
  }
7255
7256
  };
7256
7257
  function checkedWasm(artifact) {
7257
- const bytes2 = artifact.bytes.slice();
7258
- if (!/^[a-f0-9]{64}$/i.test(artifact.sha256) || binaryDigest(bytes2) !== artifact.sha256.toLowerCase()) throw new Error("Wasm artifact integrity mismatch");
7259
- if (!WebAssembly.validate(bytes2)) throw new Error("invalid WebAssembly artifact");
7260
- return bytes2;
7258
+ const bytes3 = artifact.bytes.slice();
7259
+ if (!/^[a-f0-9]{64}$/i.test(artifact.sha256) || binaryDigest(bytes3) !== artifact.sha256.toLowerCase()) throw new Error("Wasm artifact integrity mismatch");
7260
+ if (!WebAssembly.validate(bytes3)) throw new Error("invalid WebAssembly artifact");
7261
+ return bytes3;
7261
7262
  }
7262
7263
  function installWasmCommands(kernel, artifacts) {
7263
7264
  const names = /* @__PURE__ */ new Set();
@@ -7266,7 +7267,7 @@ function installWasmCommands(kernel, artifacts) {
7266
7267
  names.add(artifact.name);
7267
7268
  return { name: artifact.name, bytes: checkedWasm(artifact) };
7268
7269
  });
7269
- for (const { name, bytes: bytes2 } of checked) kernel.installCommand({ name, run: (ctx) => runWasi(ctx, bytes2) });
7270
+ for (const { name, bytes: bytes3 } of checked) kernel.installCommand({ name, run: (ctx) => runWasi(ctx, bytes3) });
7270
7271
  }
7271
7272
  function createWasmCompatibilityBackend(id, entries) {
7272
7273
  const ports = new Map(entries.map((entry) => {
@@ -7274,8 +7275,8 @@ function createWasmCompatibilityBackend(id, entries) {
7274
7275
  return [entry.elfSha256.toLowerCase(), checkedWasm(entry.wasm)];
7275
7276
  }));
7276
7277
  return { id, tier: "compatibility", prepare(request) {
7277
- const bytes2 = ports.get(request.sha256);
7278
- return bytes2 ? { supported: true, program: { run: (ctx) => runWasi(ctx, bytes2, { argv: [request.path, ...ctx.args] }) } } : { supported: false, reason: "no port for this binary digest" };
7278
+ const bytes3 = ports.get(request.sha256);
7279
+ return bytes3 ? { supported: true, program: { run: (ctx) => runWasi(ctx, bytes3, { argv: [request.path, ...ctx.args] }) } } : { supported: false, reason: "no port for this binary digest" };
7279
7280
  } };
7280
7281
  }
7281
7282
  function createTranslationBackend(translator, maxCacheBytes = 32 * 1024 * 1024) {
@@ -7284,32 +7285,32 @@ function createTranslationBackend(translator, maxCacheBytes = 32 * 1024 * 1024)
7284
7285
  let size = 0;
7285
7286
  return { id: translator.id, tier: "translation", async prepare(request, signal) {
7286
7287
  if (!translator.supports(request.info)) return { supported: false, reason: "unsupported ELF architecture" };
7287
- let bytes2 = cache.get(request.sha256);
7288
- if (bytes2) {
7288
+ let bytes3 = cache.get(request.sha256);
7289
+ if (bytes3) {
7289
7290
  cache.delete(request.sha256);
7290
- cache.set(request.sha256, bytes2);
7291
+ cache.set(request.sha256, bytes3);
7291
7292
  } else {
7292
7293
  const output = await translator.translate(request, signal);
7293
7294
  if (signal.aborted) return { supported: false, reason: "cancelled" };
7294
7295
  if (!output) return { supported: false, reason: "translator declined this program" };
7295
- bytes2 = output.slice();
7296
- if (!WebAssembly.validate(bytes2.slice())) throw new Error(`${translator.id}: invalid translator output`);
7297
- if (bytes2.byteLength <= maxCacheBytes) {
7296
+ bytes3 = output.slice();
7297
+ if (!WebAssembly.validate(bytes3.slice())) throw new Error(`${translator.id}: invalid translator output`);
7298
+ if (bytes3.byteLength <= maxCacheBytes) {
7298
7299
  const previous = cache.get(request.sha256);
7299
7300
  if (previous) {
7300
7301
  size -= previous.byteLength;
7301
7302
  cache.delete(request.sha256);
7302
7303
  }
7303
- while (size + bytes2.byteLength > maxCacheBytes && cache.size) {
7304
+ while (size + bytes3.byteLength > maxCacheBytes && cache.size) {
7304
7305
  const key = cache.keys().next().value;
7305
7306
  size -= cache.get(key).byteLength;
7306
7307
  cache.delete(key);
7307
7308
  }
7308
- cache.set(request.sha256, bytes2);
7309
- size += bytes2.byteLength;
7309
+ cache.set(request.sha256, bytes3);
7310
+ size += bytes3.byteLength;
7310
7311
  }
7311
7312
  }
7312
- const artifact = bytes2;
7313
+ const artifact = bytes3;
7313
7314
  return { supported: true, program: { run: (ctx) => runWasi(ctx, artifact, { argv: [request.path, ...ctx.args] }) } };
7314
7315
  } };
7315
7316
  }
@@ -8358,18 +8359,18 @@ function createSysProvider(kernel) {
8358
8359
  }
8359
8360
 
8360
8361
  // src/net/proxy-fetch.ts
8361
- function toBase64(bytes2) {
8362
+ function toBase64(bytes3) {
8362
8363
  let text2 = "";
8363
- for (let at = 0; at < bytes2.length; at += 32768) {
8364
- text2 += String.fromCharCode(...bytes2.subarray(at, at + 32768));
8364
+ for (let at = 0; at < bytes3.length; at += 32768) {
8365
+ text2 += String.fromCharCode(...bytes3.subarray(at, at + 32768));
8365
8366
  }
8366
8367
  return btoa(text2);
8367
8368
  }
8368
8369
  function fromBase64(text2) {
8369
8370
  const binary = atob(text2);
8370
- const bytes2 = new Uint8Array(binary.length);
8371
- for (let at = 0; at < binary.length; at += 1) bytes2[at] = binary.charCodeAt(at);
8372
- return bytes2;
8371
+ const bytes3 = new Uint8Array(binary.length);
8372
+ for (let at = 0; at < binary.length; at += 1) bytes3[at] = binary.charCodeAt(at);
8373
+ return bytes3;
8373
8374
  }
8374
8375
  async function proxyExchange(proxy, request, fetchImpl = fetch) {
8375
8376
  let answer;
@@ -8456,6 +8457,93 @@ async function discoverEgress(fetchImpl = fetch) {
8456
8457
  return await found;
8457
8458
  }
8458
8459
 
8460
+ // src/net/secrets.ts
8461
+ var PLACEHOLDER = /\{\{secret:([A-Za-z_][A-Za-z0-9_]*)\}\}/g;
8462
+ var REDACTED = "[sealed]";
8463
+ var SecretRefused = class extends Error {
8464
+ code = "EACCES";
8465
+ };
8466
+ function hostBound(secret, hostname) {
8467
+ return secret.hosts.some((host2) => hostname === host2 || hostname.endsWith(`.${host2}`));
8468
+ }
8469
+ function mentionsSecret(text2) {
8470
+ PLACEHOLDER.lastIndex = 0;
8471
+ return PLACEHOLDER.test(text2);
8472
+ }
8473
+ function substituteSecrets(text2, hostname, secrets) {
8474
+ return text2.replace(PLACEHOLDER, (_match, name) => {
8475
+ const secret = Object.prototype.hasOwnProperty.call(secrets, name) ? secrets[name] : void 0;
8476
+ if (!secret) {
8477
+ throw new SecretRefused(`no sealed secret named ${name} is configured for this container`);
8478
+ }
8479
+ if (!hostBound(secret, hostname)) {
8480
+ throw new SecretRefused(
8481
+ `the sealed secret ${name} is not bound to ${hostname}; it may only be sent to ${secret.hosts.join(", ") || "no host"}`
8482
+ );
8483
+ }
8484
+ return secret.value;
8485
+ });
8486
+ }
8487
+ function sealRequest(request, secrets) {
8488
+ const url = new URL(request.url);
8489
+ if (mentionsSecret(decodeURIComponent(url.href))) {
8490
+ throw new SecretRefused("a sealed secret can only be used in a request header, not in the URL");
8491
+ }
8492
+ const used = [];
8493
+ let headers = null;
8494
+ request.headers.forEach((value, name) => {
8495
+ if (!mentionsSecret(value)) return;
8496
+ headers ??= new Headers(request.headers);
8497
+ headers.set(name, substituteSecrets(value, url.hostname, secrets));
8498
+ PLACEHOLDER.lastIndex = 0;
8499
+ for (const match2 of value.matchAll(PLACEHOLDER)) used.push(match2[1]);
8500
+ });
8501
+ return headers ? { request: new Request(request, { headers }), used } : { request, used };
8502
+ }
8503
+ function redactResponse(response, secrets) {
8504
+ const values = Object.values(secrets).map((secret) => secret.value).filter((value) => value.length > 0);
8505
+ if (values.length === 0) return response;
8506
+ const headers = new Headers();
8507
+ response.headers.forEach((value, name) => headers.set(name, redactText(value, values)));
8508
+ const init = { status: response.status, statusText: response.statusText, headers };
8509
+ if (!response.body) return new Response(null, init);
8510
+ headers.delete("content-length");
8511
+ return new Response(response.body.pipeThrough(redactingStream(values)), init);
8512
+ }
8513
+ function redactText(text2, values) {
8514
+ let out = text2;
8515
+ for (const value of values) out = out.split(value).join(REDACTED);
8516
+ return out;
8517
+ }
8518
+ function redactingStream(values) {
8519
+ const needles = values.map((value) => latin1(new TextEncoder().encode(value)));
8520
+ const hold = Math.max(...needles.map((needle) => needle.length)) - 1;
8521
+ let pending = "";
8522
+ return new TransformStream({
8523
+ transform(chunk, controller) {
8524
+ pending = redactText(pending + latin1(chunk), needles);
8525
+ if (pending.length <= hold) return;
8526
+ controller.enqueue(bytes(pending.slice(0, pending.length - hold)));
8527
+ pending = pending.slice(pending.length - hold);
8528
+ },
8529
+ flush(controller) {
8530
+ if (pending) controller.enqueue(bytes(redactText(pending, needles)));
8531
+ }
8532
+ });
8533
+ }
8534
+ function latin1(chunk) {
8535
+ let out = "";
8536
+ for (let at = 0; at < chunk.length; at += 32768) {
8537
+ out += String.fromCharCode(...chunk.subarray(at, at + 32768));
8538
+ }
8539
+ return out;
8540
+ }
8541
+ function bytes(text2) {
8542
+ const out = new Uint8Array(text2.length);
8543
+ for (let index = 0; index < text2.length; index += 1) out[index] = text2.charCodeAt(index);
8544
+ return out;
8545
+ }
8546
+
8459
8547
  // src/net/policy.ts
8460
8548
  function isLoopbackHostname(hostname) {
8461
8549
  const host2 = hostname.replace(/^\[|\]$/g, "").toLowerCase();
@@ -8493,6 +8581,24 @@ function requestUrl(input) {
8493
8581
  return input.url;
8494
8582
  }
8495
8583
  function policedFetch(policy, fetchImpl) {
8584
+ const secrets = policy.secrets && Object.keys(policy.secrets).length > 0 ? policy.secrets : null;
8585
+ if (!secrets) return policedPlainFetch(policy, fetchImpl);
8586
+ const plain = policedPlainFetch(policy, fetchImpl);
8587
+ return (async (input, init) => {
8588
+ const url = requestUrl(input);
8589
+ if (!outboundAllowed(policy, url)) {
8590
+ throw Object.assign(new TypeError("fetch failed"), { cause: outboundBlockedError(url) });
8591
+ }
8592
+ let sealed;
8593
+ try {
8594
+ sealed = sealRequest(new Request(input, init), secrets).request;
8595
+ } catch (error) {
8596
+ throw Object.assign(new TypeError("fetch failed"), { cause: error });
8597
+ }
8598
+ return redactResponse(await plain(sealed), secrets);
8599
+ });
8600
+ }
8601
+ function policedPlainFetch(policy, fetchImpl) {
8496
8602
  return (async (input, init) => {
8497
8603
  const url = requestUrl(input);
8498
8604
  if (!outboundAllowed(policy, url)) {
@@ -8729,22 +8835,22 @@ var NetworkStack = class {
8729
8835
  `;
8730
8836
  return out;
8731
8837
  }
8732
- countTx(bytes2, iface = "eth0") {
8838
+ countTx(bytes3, iface = "eth0") {
8733
8839
  const i = this.interface(iface);
8734
8840
  if (!i) return;
8735
- i.txBytes += bytes2;
8736
- i.txPackets += Math.max(1, Math.ceil(bytes2 / 1400));
8841
+ i.txBytes += bytes3;
8842
+ i.txPackets += Math.max(1, Math.ceil(bytes3 / 1400));
8737
8843
  }
8738
- countRx(bytes2, iface = "eth0") {
8844
+ countRx(bytes3, iface = "eth0") {
8739
8845
  const i = this.interface(iface);
8740
8846
  if (!i) return;
8741
- i.rxBytes += bytes2;
8742
- i.rxPackets += Math.max(1, Math.ceil(bytes2 / 1400));
8847
+ i.rxBytes += bytes3;
8848
+ i.rxPackets += Math.max(1, Math.ceil(bytes3 / 1400));
8743
8849
  }
8744
8850
  };
8745
8851
  function randomMac() {
8746
- const bytes2 = [2, 66, 172, 17, 0, 2];
8747
- return bytes2.map((b) => b.toString(16).padStart(2, "0")).join(":");
8852
+ const bytes3 = [2, 66, 172, 17, 0, 2];
8853
+ return bytes3.map((b) => b.toString(16).padStart(2, "0")).join(":");
8748
8854
  }
8749
8855
  function hexIp(ip2) {
8750
8856
  return ip2.split(".").reverse().map((o) => Number(o).toString(16).padStart(2, "0").toUpperCase()).join("");
@@ -9189,15 +9295,15 @@ var Parser = class {
9189
9295
  if (this.isWord("-p")) this.next();
9190
9296
  }
9191
9297
  }
9192
- const commands12 = [this.parseCommand()];
9298
+ const commands13 = [this.parseCommand()];
9193
9299
  const stderrToo = [];
9194
9300
  while (this.isOp("|") || this.isOp("|&")) {
9195
9301
  stderrToo.push(this.next().value === "|&");
9196
9302
  this.skipNewlines();
9197
- commands12.push(this.parseCommand());
9303
+ commands13.push(this.parseCommand());
9198
9304
  }
9199
- if (commands12.length === 1 && !negated && !timed) return commands12[0];
9200
- return { type: "pipeline", commands: commands12, negated, stderrToo, timed };
9305
+ if (commands13.length === 1 && !negated && !timed) return commands13[0];
9306
+ return { type: "pipeline", commands: commands13, negated, stderrToo, timed };
9201
9307
  }
9202
9308
  // ── commands ─────────────────────────────────────────────────────────────
9203
9309
  parseCommand() {
@@ -10817,8 +10923,8 @@ var decoder4 = new TextDecoder();
10817
10923
  async function readInputs(ctx, operands, opts = {}) {
10818
10924
  const stdinName = opts.stdinName ?? "-";
10819
10925
  if (operands.length === 0) {
10820
- const bytes2 = await ctx.stdin.readAll();
10821
- return { sources: [{ name: stdinName, bytes: bytes2 }], ok: true };
10926
+ const bytes3 = await ctx.stdin.readAll();
10927
+ return { sources: [{ name: stdinName, bytes: bytes3 }], ok: true };
10822
10928
  }
10823
10929
  const sources = [];
10824
10930
  let ok2 = true;
@@ -10843,8 +10949,8 @@ async function readInputs(ctx, operands, opts = {}) {
10843
10949
  }
10844
10950
  return { sources, ok: ok2 };
10845
10951
  }
10846
- function splitLines(bytes2) {
10847
- const text2 = decoder4.decode(bytes2);
10952
+ function splitLines(bytes3) {
10953
+ const text2 = decoder4.decode(bytes3);
10848
10954
  if (text2 === "") return { lines: [], trailingNewline: true };
10849
10955
  const trailingNewline = text2.endsWith("\n");
10850
10956
  const body = trailingNewline ? text2.slice(0, -1) : text2;
@@ -10856,11 +10962,11 @@ function joinLines(lines, trailingNewline = true) {
10856
10962
  }
10857
10963
  var SI_UNITS = ["", "k", "M", "G", "T", "P", "E"];
10858
10964
  var IEC_UNITS = ["", "K", "M", "G", "T", "P", "E"];
10859
- function humanSize(bytes2, opts = {}) {
10965
+ function humanSize(bytes3, opts = {}) {
10860
10966
  const base2 = opts.si ? 1e3 : 1024;
10861
10967
  const units = opts.si ? SI_UNITS : IEC_UNITS;
10862
- if (bytes2 < base2) return String(bytes2);
10863
- let value = bytes2;
10968
+ if (bytes3 < base2) return String(bytes3);
10969
+ let value = bytes3;
10864
10970
  let unit = 0;
10865
10971
  while (value >= base2 && unit < units.length - 1) {
10866
10972
  value /= base2;
@@ -11150,7 +11256,7 @@ var cat = defineCommand({
11150
11256
  let lineNumber = 1;
11151
11257
  let lastWasBlank = false;
11152
11258
  for (const operand of operands) {
11153
- let bytes2;
11259
+ let bytes3;
11154
11260
  if (operand === "-") {
11155
11261
  if (plain) {
11156
11262
  for (; ; ) {
@@ -11161,7 +11267,7 @@ var cat = defineCommand({
11161
11267
  }
11162
11268
  continue;
11163
11269
  }
11164
- bytes2 = await ctx.stdin.readAll();
11270
+ bytes3 = await ctx.stdin.readAll();
11165
11271
  } else {
11166
11272
  try {
11167
11273
  const abs = ctx.path(operand);
@@ -11171,17 +11277,17 @@ var cat = defineCommand({
11171
11277
  status = 1;
11172
11278
  continue;
11173
11279
  }
11174
- bytes2 = ctx.vfs.readFile(abs, ctx.cred);
11280
+ bytes3 = ctx.vfs.readFile(abs, ctx.cred);
11175
11281
  } catch (e) {
11176
11282
  status = ctx.reportError(e, operand);
11177
11283
  continue;
11178
11284
  }
11179
11285
  }
11180
11286
  if (plain) {
11181
- ctx.write(bytes2);
11287
+ ctx.write(bytes3);
11182
11288
  continue;
11183
11289
  }
11184
- const text2 = new TextDecoder().decode(bytes2);
11290
+ const text2 = new TextDecoder().decode(bytes3);
11185
11291
  const hadTrailing = text2.endsWith("\n");
11186
11292
  const parts = (hadTrailing ? text2.slice(0, -1) : text2).split("\n");
11187
11293
  for (const raw of parts) {
@@ -12035,15 +12141,15 @@ function describeFile(ctx, abs, st, mime) {
12035
12141
  }
12036
12142
  if (st.isCharacterDevice()) return mime ? "inode/chardevice" : "character special";
12037
12143
  if (st.size === 0) return mime ? "inode/x-empty" : "empty";
12038
- const bytes2 = ctx.vfs.readFile(abs, ctx.cred).subarray(0, 512);
12039
- const magic = [...bytes2.subarray(0, 4)];
12144
+ const bytes3 = ctx.vfs.readFile(abs, ctx.cred).subarray(0, 512);
12145
+ const magic = [...bytes3.subarray(0, 4)];
12040
12146
  if (magic[0] === 127 && magic[1] === 69 && magic[2] === 76 && magic[3] === 70) {
12041
12147
  return mime ? "application/x-executable" : "ELF 64-bit LSB executable, x86-64";
12042
12148
  }
12043
12149
  if (magic[0] === 31 && magic[1] === 139) return mime ? "application/gzip" : "gzip compressed data";
12044
12150
  if (magic[0] === 80 && magic[1] === 75) return mime ? "application/zip" : "Zip archive data";
12045
12151
  if (magic[0] === 137 && magic[1] === 80) return mime ? "image/png" : "PNG image data";
12046
- const text2 = new TextDecoder().decode(bytes2);
12152
+ const text2 = new TextDecoder().decode(bytes3);
12047
12153
  const printable = [...text2].every((c) => c === "\n" || c === " " || c === "\r" || c >= " " && c <= "~" || c.charCodeAt(0) > 127);
12048
12154
  if (!printable) return mime ? "application/octet-stream" : "data";
12049
12155
  if (text2.startsWith("#!")) {
@@ -12946,6 +13052,523 @@ var commands3 = [
12946
13052
  clear,
12947
13053
  sync
12948
13054
  ];
13055
+ var platformBuffer = globalThis.Buffer;
13056
+ addUint8ArraySupport(addBase64UrlSupport(Buffer$1));
13057
+ var Buffer2 = platformBuffer ?? Buffer$1;
13058
+ function addUint8ArraySupport(BufferClass) {
13059
+ const target = BufferClass;
13060
+ if (target.__sandboxedUint8Array) return BufferClass;
13061
+ Object.defineProperty(target, "__sandboxedUint8Array", { value: true });
13062
+ const asBuffer = (value) => value instanceof Uint8Array && !target.isBuffer(value) ? target.from(value.buffer, value.byteOffset, value.byteLength) : value;
13063
+ for (const method of ["indexOf", "lastIndexOf", "includes"]) {
13064
+ const original = target.prototype[method];
13065
+ target.prototype[method] = function(value, ...rest) {
13066
+ return original.call(this, asBuffer(value), ...rest);
13067
+ };
13068
+ }
13069
+ const equals = target.prototype.equals;
13070
+ target.prototype.equals = function(other) {
13071
+ return equals.call(this, asBuffer(other));
13072
+ };
13073
+ return BufferClass;
13074
+ }
13075
+ function addBase64UrlSupport(BufferClass) {
13076
+ const target = BufferClass;
13077
+ if (target.__sandboxedBase64Url) return BufferClass;
13078
+ Object.defineProperty(target, "__sandboxedBase64Url", { value: true });
13079
+ const from = target.from.bind(target);
13080
+ target.from = (value, encodingOrOffset, length) => from(value, normalizeEncoding(encodingOrOffset), length);
13081
+ const byteLength = target.byteLength.bind(target);
13082
+ target.byteLength = (value, encoding) => byteLength(value, normalizeEncoding(encoding));
13083
+ const isEncoding = target.isEncoding?.bind(target);
13084
+ if (isEncoding) target.isEncoding = (encoding) => encoding.toLowerCase() === "base64url" || isEncoding(encoding);
13085
+ const toString = target.prototype.toString;
13086
+ target.prototype.toString = function(encoding, start2, end) {
13087
+ if (encoding?.toLowerCase() !== "base64url") return toString.call(this, encoding, start2, end);
13088
+ return toString.call(this, "base64", start2, end).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
13089
+ };
13090
+ const write = target.prototype.write;
13091
+ target.prototype.write = function(...args) {
13092
+ const index = typeof args[1] === "string" ? 1 : typeof args[2] === "string" ? 2 : 3;
13093
+ if (typeof args[index] === "string") args[index] = normalizeEncoding(args[index]);
13094
+ return write.apply(this, args);
13095
+ };
13096
+ return BufferClass;
13097
+ }
13098
+ function normalizeEncoding(value) {
13099
+ return typeof value === "string" && value.toLowerCase() === "base64url" ? "base64" : value;
13100
+ }
13101
+
13102
+ // src/pkg/clean-installer.ts
13103
+ init_path();
13104
+
13105
+ // src/browser/playwright-browsers.ts
13106
+ init_path();
13107
+ var PLAYWRIGHT_REGISTRY = "/root/.cache/ms-playwright";
13108
+ var LAYOUTS = {
13109
+ "chromium": ["chrome-linux64", "chrome"],
13110
+ "chromium-headless-shell": ["chrome-headless-shell-linux64", "chrome-headless-shell"]
13111
+ };
13112
+ function virtualBrowserFiles(browsersJson) {
13113
+ let manifest;
13114
+ try {
13115
+ manifest = JSON.parse(browsersJson);
13116
+ } catch {
13117
+ return [];
13118
+ }
13119
+ const encoder9 = new TextEncoder();
13120
+ const files = [];
13121
+ for (const browser of manifest.browsers ?? []) {
13122
+ const layout = LAYOUTS[browser.name];
13123
+ if (!layout) continue;
13124
+ const dir3 = join(PLAYWRIGHT_REGISTRY, `${browser.name.replace(/-/g, "_")}-${browser.revision}`);
13125
+ files.push({ path: join(dir3, ...layout), data: encoder9.encode(`#!${BUILTIN_INTERPRETER} chrome
13126
+ `), mode: 493 });
13127
+ files.push({ path: join(dir3, "INSTALLATION_COMPLETE"), data: new Uint8Array() });
13128
+ }
13129
+ return files;
13130
+ }
13131
+ function mkdirp(volume, path) {
13132
+ let current2 = "";
13133
+ for (const part of segments(path)) {
13134
+ current2 += `/${part}`;
13135
+ try {
13136
+ volume.mkdirSync(current2, { mode: 493 });
13137
+ } catch (error) {
13138
+ if (error.code !== "EEXIST") throw error;
13139
+ }
13140
+ }
13141
+ }
13142
+ function installVirtualPlaywrightBrowsers(volume, packageDir) {
13143
+ let text2;
13144
+ try {
13145
+ text2 = new TextDecoder().decode(volume.readFileSync(join(packageDir, "browsers.json")));
13146
+ } catch {
13147
+ return [];
13148
+ }
13149
+ const written = [];
13150
+ for (const file3 of virtualBrowserFiles(text2)) {
13151
+ mkdirp(volume, dirname(file3.path));
13152
+ volume.writeFileSync(file3.path, file3.data);
13153
+ if (file3.mode !== void 0) {
13154
+ volume.chmodSync(file3.path, file3.mode);
13155
+ written.push(file3.path);
13156
+ }
13157
+ }
13158
+ return written;
13159
+ }
13160
+
13161
+ // src/pkg/clean-installer.ts
13162
+ var RUNTIME_PACKAGE_FALLBACKS = {
13163
+ esbuild: "esbuild-wasm",
13164
+ rollup: "@rollup/wasm-node"
13165
+ };
13166
+ var CleanPackageInstaller = class _CleanPackageInstaller {
13167
+ constructor(volume, options = {}) {
13168
+ this.volume = volume;
13169
+ this.options = options;
13170
+ this.registry = (options.registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
13171
+ this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
13172
+ }
13173
+ volume;
13174
+ options;
13175
+ registry;
13176
+ fetcher;
13177
+ metadata = /* @__PURE__ */ new Map();
13178
+ tarballs = /* @__PURE__ */ new Map();
13179
+ /** Single-version manifests, for the fields the packument omits. */
13180
+ details = /* @__PURE__ */ new Map();
13181
+ forCwd(cwd) {
13182
+ const installer = new _CleanPackageInstaller(this.volume, { ...this.options, cwd });
13183
+ installer.metadata = this.metadata;
13184
+ installer.tarballs = this.tarballs;
13185
+ installer.details = this.details;
13186
+ return installer;
13187
+ }
13188
+ async install(name, version = "latest", options = {}) {
13189
+ const cwd = this.options.cwd ?? "/";
13190
+ const manifest = await this.installAt(name, version || "latest", join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
13191
+ if (options.persist !== false) this.persist(cwd, name, version, options.persistDev === true);
13192
+ return manifest;
13193
+ }
13194
+ async installFromManifest(path, options = {}) {
13195
+ const project = this.readJson(path);
13196
+ const cwd = dirname(path);
13197
+ const dependencies = {
13198
+ ...project.dependencies ?? {},
13199
+ ...options.withDevDeps === false ? {} : project.devDependencies ?? {}
13200
+ };
13201
+ await this.prefetch(dependencies);
13202
+ for (const [name, range] of Object.entries(dependencies)) {
13203
+ await this.installAt(name, range, join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
13204
+ }
13205
+ }
13206
+ async installAt(name, range, modulesRoot, options, ancestry) {
13207
+ const metadata = await this.getMetadata(name);
13208
+ const version = resolveVersion(metadata, range);
13209
+ const manifest = metadata.versions[version];
13210
+ if (!manifest) throw new Error(`No matching version found for ${name}@${range}`);
13211
+ const identity = `${name}@${version}`;
13212
+ if (!supportsPlatform(manifest)) throw new IncompatiblePlatform(identity, "");
13213
+ if (manifest.os?.length || manifest.cpu?.length) {
13214
+ const detail = await this.platformDetail(name, version);
13215
+ if (!platformListAllows(detail.libc, PLATFORM.libc)) {
13216
+ throw new IncompatiblePlatform(identity, ` (needs ${detail.libc?.join(", ")})`);
13217
+ }
13218
+ if (detail.main?.endsWith(".node")) {
13219
+ throw new IncompatiblePlatform(identity, " (native addon; this runtime cannot dlopen)");
13220
+ }
13221
+ }
13222
+ const target = join(modulesRoot, name);
13223
+ const installed3 = this.tryReadJson(join(target, "package.json"));
13224
+ if (ancestry.has(identity)) return manifest;
13225
+ if (installed3?.version !== version) {
13226
+ options.onProgress?.(`Fetching ${identity}`);
13227
+ const archive = await this.getTarball(manifest.dist.tarball);
13228
+ verifyIntegrity(archive, manifest.dist.integrity, manifest.dist.shasum, identity);
13229
+ this.removeIfPresent(target);
13230
+ mkdirp2(this.volume, target);
13231
+ extractNpmTarball(this.volume, archive, target);
13232
+ options.onProgress?.(`Installed ${identity}`);
13233
+ }
13234
+ this.createBinLinks(manifest, target, modulesRoot);
13235
+ if (name === "playwright-core") {
13236
+ for (const executable of installVirtualPlaywrightBrowsers(this.volume, target)) {
13237
+ options.onProgress?.(`Linked ${executable} to the virtual browser`);
13238
+ }
13239
+ }
13240
+ const nextAncestry = new Set(ancestry).add(identity);
13241
+ const fallback = RUNTIME_PACKAGE_FALLBACKS[name];
13242
+ if (fallback && fallback !== name) {
13243
+ await this.installAt(fallback, version, modulesRoot, options, nextAncestry);
13244
+ }
13245
+ const childRoot = join(target, "node_modules");
13246
+ const required = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name2]) => !(name2 in (manifest.optionalDependencies ?? {}))));
13247
+ await this.prefetch(required);
13248
+ for (const [dependency, dependencyRange] of Object.entries(required)) {
13249
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
13250
+ }
13251
+ for (const [dependency, dependencyRange] of Object.entries(manifest.optionalDependencies ?? {})) {
13252
+ try {
13253
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
13254
+ } catch (error) {
13255
+ if (error instanceof IncompatiblePlatform) continue;
13256
+ options.onProgress?.(`Skipped optional ${dependency}: ${error instanceof Error ? error.message : String(error)}`);
13257
+ }
13258
+ }
13259
+ return manifest;
13260
+ }
13261
+ /**
13262
+ * The `libc` and `main` fields, which the abbreviated packument leaves out.
13263
+ *
13264
+ * Fetched per version rather than as a full packument: the single-version
13265
+ * document is a few kilobytes, while the full one for a popular package runs
13266
+ * to megabytes. Only packages that already declare `os` or `cpu` ask for it,
13267
+ * so an ordinary install of pure-JavaScript dependencies makes no extra
13268
+ * requests at all — it is the prebuilt binaries, a handful per project, that
13269
+ * need the answer.
13270
+ *
13271
+ * A failure here is not fatal. Being unable to read `libc` puts the check
13272
+ * back where it was before this existed, which is worth strictly less than
13273
+ * being right and strictly more than refusing to install.
13274
+ */
13275
+ async platformDetail(name, version) {
13276
+ const key = `${name}@${version}`;
13277
+ let request = this.details.get(key);
13278
+ if (!request) {
13279
+ request = (async () => {
13280
+ try {
13281
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
13282
+ const response = await this.fetcher(`${this.registry}/${encoded}/${version}`);
13283
+ if (!response.ok) return {};
13284
+ return await response.json();
13285
+ } catch {
13286
+ return {};
13287
+ }
13288
+ })();
13289
+ this.details.set(key, request);
13290
+ }
13291
+ return request;
13292
+ }
13293
+ /** Overlap up to six sibling downloads; filesystem writes remain ordered. */
13294
+ async prefetch(dependencies) {
13295
+ const entries = Object.entries(dependencies);
13296
+ let next = 0;
13297
+ await Promise.all(Array.from({ length: Math.min(6, entries.length) }, async () => {
13298
+ while (next < entries.length) {
13299
+ const [name, range] = entries[next++];
13300
+ try {
13301
+ const metadata = await this.getMetadata(name);
13302
+ const manifest = metadata.versions[resolveVersion(metadata, range)];
13303
+ if (!manifest.os?.length && !manifest.cpu?.length && supportsPlatform(manifest)) {
13304
+ await this.getTarball(manifest.dist.tarball);
13305
+ }
13306
+ } catch {
13307
+ }
13308
+ }
13309
+ }));
13310
+ }
13311
+ async getMetadata(name) {
13312
+ let request = this.metadata.get(name);
13313
+ if (!request) {
13314
+ request = (async () => {
13315
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
13316
+ const response = await this.fetcher(`${this.registry}/${encoded}`, {
13317
+ headers: { Accept: "application/vnd.npm.install-v1+json" }
13318
+ });
13319
+ if (!response.ok) throw new Error(`registry returned ${response.status} for ${name}`);
13320
+ return await response.json();
13321
+ })();
13322
+ this.metadata.set(name, request);
13323
+ void request.catch(() => {
13324
+ this.metadata.delete(name);
13325
+ });
13326
+ }
13327
+ return request;
13328
+ }
13329
+ async getTarball(url) {
13330
+ let request = this.tarballs.get(url);
13331
+ if (!request) {
13332
+ request = (async () => {
13333
+ const response = await this.fetcher(url);
13334
+ if (!response.ok) throw new Error(`tarball returned ${response.status}: ${url}`);
13335
+ return new Uint8Array(await response.arrayBuffer());
13336
+ })();
13337
+ this.tarballs.set(url, request);
13338
+ void request.catch(() => {
13339
+ this.tarballs.delete(url);
13340
+ });
13341
+ }
13342
+ return request;
13343
+ }
13344
+ createBinLinks(manifest, target, modulesRoot) {
13345
+ if (!manifest.bin) return;
13346
+ const bins = typeof manifest.bin === "string" ? { [unscoped(manifest.name)]: manifest.bin } : manifest.bin;
13347
+ const binDir = join(modulesRoot, ".bin");
13348
+ mkdirp2(this.volume, binDir);
13349
+ for (const [name, path] of Object.entries(bins)) {
13350
+ const link = join(binDir, name);
13351
+ this.removeIfPresent(link);
13352
+ this.volume.symlinkSync(relative(binDir, join(target, path)), link);
13353
+ }
13354
+ }
13355
+ persist(cwd, name, range, dev) {
13356
+ const path = join(cwd, "package.json");
13357
+ const manifest = this.tryReadJson(path) ?? {};
13358
+ const key = dev ? "devDependencies" : "dependencies";
13359
+ manifest[key] = { ...manifest[key] ?? {}, [name]: range === "latest" ? "*" : range };
13360
+ this.volume.writeFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
13361
+ }
13362
+ removeIfPresent(path) {
13363
+ let stat2;
13364
+ try {
13365
+ stat2 = this.volume.lstatSync(path);
13366
+ } catch {
13367
+ return;
13368
+ }
13369
+ if (!stat2.isDirectory()) return this.volume.unlinkSync(path);
13370
+ for (const name of this.volume.readdirSync(path)) this.removeIfPresent(join(path, name));
13371
+ this.volume.rmdirSync(path);
13372
+ }
13373
+ readJson(path) {
13374
+ return JSON.parse(new TextDecoder().decode(this.volume.readFileSync(path)));
13375
+ }
13376
+ tryReadJson(path) {
13377
+ try {
13378
+ return this.readJson(path);
13379
+ } catch {
13380
+ return null;
13381
+ }
13382
+ }
13383
+ };
13384
+ var PLATFORM = { os: "linux", cpu: "x64", libc: "glibc" };
13385
+ var IncompatiblePlatform = class extends Error {
13386
+ constructor(identity, detail) {
13387
+ super(`${identity} is not compatible with ${PLATFORM.os}/${PLATFORM.cpu}/${PLATFORM.libc}${detail}`);
13388
+ this.name = "IncompatiblePlatform";
13389
+ }
13390
+ };
13391
+ function supportsPlatform(manifest) {
13392
+ return platformListAllows(manifest.os, PLATFORM.os) && platformListAllows(manifest.cpu, PLATFORM.cpu) && platformListAllows(manifest.libc, PLATFORM.libc);
13393
+ }
13394
+ function platformListAllows(values, current2) {
13395
+ if (!values?.length) return true;
13396
+ if (values.includes(`!${current2}`)) return false;
13397
+ const positive = values.filter((value) => !value.startsWith("!"));
13398
+ return positive.length === 0 || positive.includes(current2) || positive.includes("any");
13399
+ }
13400
+ function resolveVersion(metadata, range) {
13401
+ const tag2 = metadata["dist-tags"]?.[range];
13402
+ if (tag2) return tag2;
13403
+ if (valid(range) && metadata.versions[range]) return range;
13404
+ const found2 = maxSatisfying(Object.keys(metadata.versions), range === "latest" ? "*" : range, { includePrerelease: false });
13405
+ if (!found2) throw new Error(`No matching version found for ${metadata.name}@${range}`);
13406
+ return found2;
13407
+ }
13408
+ function verifyIntegrity(data, integrity, shasum, identity) {
13409
+ if (integrity) {
13410
+ const choices = integrity.trim().split(/\s+/);
13411
+ for (const choice of choices) {
13412
+ const dash = choice.indexOf("-");
13413
+ const algorithm = choice.slice(0, dash);
13414
+ const expected = choice.slice(dash + 1).replace(/\?.*$/, "");
13415
+ const digest2 = algorithm === "sha512" ? sha512(data) : algorithm === "sha256" ? sha256(data) : null;
13416
+ if (digest2 && Buffer2.from(digest2).toString("base64") === expected) return;
13417
+ }
13418
+ throw new Error(`Integrity check failed for ${identity}`);
13419
+ }
13420
+ if (shasum && Buffer2.from(sha1(data)).toString("hex") === shasum) return;
13421
+ if (shasum) throw new Error(`Legacy checksum check failed for ${identity}`);
13422
+ }
13423
+ function extractNpmTarball(volume, compressed, destination) {
13424
+ const tar2 = ungzip(compressed);
13425
+ let offset = 0;
13426
+ let longPath = null;
13427
+ let paxPath = null;
13428
+ while (offset + 512 <= tar2.length) {
13429
+ const header = tar2.subarray(offset, offset + 512);
13430
+ if (header.every((byte) => byte === 0)) break;
13431
+ const size = octal(header, 124, 12);
13432
+ const type = String.fromCharCode(header[156] || 48);
13433
+ const prefix = text(header, 345, 155);
13434
+ let name = longPath ?? paxPath ?? [prefix, text(header, 0, 100)].filter(Boolean).join("/");
13435
+ longPath = null;
13436
+ paxPath = null;
13437
+ const data = tar2.subarray(offset + 512, offset + 512 + size);
13438
+ offset += 512 + Math.ceil(size / 512) * 512;
13439
+ if (type === "L") {
13440
+ longPath = new TextDecoder().decode(data).replace(/\0.*$/, "").trim();
13441
+ continue;
13442
+ }
13443
+ if (type === "x" || type === "g") {
13444
+ paxPath = parsePax(data).path ?? null;
13445
+ continue;
13446
+ }
13447
+ name = stripPackageRoot(name);
13448
+ if (!name) continue;
13449
+ const target = safeTarget(destination, name);
13450
+ const mode = octal(header, 100, 8) || 420;
13451
+ if (type === "5") {
13452
+ mkdirp2(volume, target, mode);
13453
+ } else if (type === "2") {
13454
+ mkdirp2(volume, dirname(target));
13455
+ volume.symlinkSync(text(header, 157, 100), target);
13456
+ } else if (type === "1") {
13457
+ mkdirp2(volume, dirname(target));
13458
+ volume.linkSync(safeTarget(destination, stripPackageRoot(text(header, 157, 100))), target);
13459
+ } else if (type === "0" || type === "\0" || type === "7") {
13460
+ mkdirp2(volume, dirname(target));
13461
+ volume.writeFileSync(target, data.slice());
13462
+ volume.chmodSync(target, mode);
13463
+ }
13464
+ }
13465
+ }
13466
+ function mkdirp2(volume, path, mode = 493) {
13467
+ let current2 = "";
13468
+ for (const part of segments(path)) {
13469
+ current2 += `/${part}`;
13470
+ try {
13471
+ volume.mkdirSync(current2, { mode });
13472
+ } catch (error) {
13473
+ if (error.code !== "EEXIST") throw error;
13474
+ if (!volume.lstatSync(current2).isDirectory()) throw error;
13475
+ }
13476
+ }
13477
+ }
13478
+ function safeTarget(destination, name) {
13479
+ const clean2 = clean(`/${name}`).slice(1);
13480
+ if (!clean2 || clean2 === ".." || clean2.startsWith("../") || name.startsWith("/")) throw new Error(`Unsafe path in package: ${name}`);
13481
+ return join(destination, clean2);
13482
+ }
13483
+ function stripPackageRoot(name) {
13484
+ const clean2 = name.replace(/^\.\//, "").replace(/\/$/, "");
13485
+ const slash = clean2.indexOf("/");
13486
+ return slash === -1 ? "" : clean2.slice(slash + 1);
13487
+ }
13488
+ function text(bytes3, start2, length) {
13489
+ return new TextDecoder().decode(bytes3.subarray(start2, start2 + length)).replace(/\0.*$/, "").trim();
13490
+ }
13491
+ function octal(bytes3, start2, length) {
13492
+ return parseInt(text(bytes3, start2, length).replace(/^0+/, "") || "0", 8);
13493
+ }
13494
+ function parsePax(data) {
13495
+ const value = new TextDecoder().decode(data);
13496
+ const result = {};
13497
+ let offset = 0;
13498
+ while (offset < value.length) {
13499
+ const space = value.indexOf(" ", offset);
13500
+ if (space < 0) break;
13501
+ const length = Number(value.slice(offset, space));
13502
+ if (!Number.isFinite(length) || length <= 0) break;
13503
+ const record2 = value.slice(space + 1, offset + length - 1);
13504
+ const equal2 = record2.indexOf("=");
13505
+ if (equal2 > 0) result[record2.slice(0, equal2)] = record2.slice(equal2 + 1);
13506
+ offset += length;
13507
+ }
13508
+ return result;
13509
+ }
13510
+ function unscoped(name) {
13511
+ return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
13512
+ }
13513
+
13514
+ // src/bin/capabilities.ts
13515
+ function report(ctx) {
13516
+ const commands13 = ctx.kernel.commands.names();
13517
+ const has = (name) => commands13.includes(name);
13518
+ return {
13519
+ schemaVersion: 1,
13520
+ runtime: "sandboxedjs",
13521
+ platform: { os: "linux", arch: "x64", libc: "glibc" },
13522
+ filesystem: { writable: true, root: "/", persistence: "container-lifetime", hostAccess: false },
13523
+ shell: { posix: true, pipelines: true, redirection: true, backgroundProcesses: true },
13524
+ languages: { node: has("node"), python: has("python3"), wasmWasi: has("wasi") },
13525
+ packages: {
13526
+ npm: has("npm"),
13527
+ pip: has("pip"),
13528
+ applicationRegistry: has("pm"),
13529
+ nativeAddons: false,
13530
+ fallbacks: RUNTIME_PACKAGE_FALLBACKS
13531
+ },
13532
+ network: {
13533
+ virtualServers: true,
13534
+ loopback: true,
13535
+ outbound: ctx.kernel.net.policy.allowOutbound,
13536
+ allowedHosts: ctx.kernel.net.policy.allowedHosts,
13537
+ proxy: ctx.kernel.net.proxy !== null,
13538
+ listeningPorts: ctx.kernel.net.listening().map(({ port, proto, program }) => ({ port, proto, program }))
13539
+ },
13540
+ interfaces: {
13541
+ desktopGui: false,
13542
+ hostFilesystem: false,
13543
+ systemPackageManager: false,
13544
+ docker: false
13545
+ },
13546
+ commands: commands13
13547
+ };
13548
+ }
13549
+ var sandboxedjsCapabilities = defineCommand({
13550
+ name: "sandboxedjs-capabilities",
13551
+ aliases: ["sbx-capabilities"],
13552
+ path: "/usr/bin/sandboxedjs-capabilities",
13553
+ summary: "report the runtime capabilities available to tools and agents",
13554
+ usage: "sandboxedjs-capabilities [--json]",
13555
+ run(ctx) {
13556
+ const result = report(ctx);
13557
+ if (ctx.args.includes("--json")) {
13558
+ ctx.line(JSON.stringify(result, null, 2));
13559
+ return 0;
13560
+ }
13561
+ ctx.line("SandboxedJS runtime capabilities");
13562
+ ctx.line(` commands: ${result.commands.length}`);
13563
+ ctx.line(` languages: ${Object.entries(result.languages).filter(([, enabled]) => enabled).map(([name]) => name).join(", ")}`);
13564
+ ctx.line(` outbound network: ${result.network.outbound ? "enabled" : "disabled"}`);
13565
+ ctx.line(` writable filesystem: ${result.filesystem.root} (${result.filesystem.persistence})`);
13566
+ ctx.line(` package fallbacks: ${Object.entries(result.packages.fallbacks).map(([from, to]) => `${from} -> ${to}`).join(", ") || "none"}`);
13567
+ ctx.line("Run with --json for the complete machine-readable inventory.");
13568
+ return 0;
13569
+ }
13570
+ });
13571
+ var commands4 = [sandboxedjsCapabilities];
12949
13572
 
12950
13573
  // src/bin/sed.ts
12951
13574
  var SedParseError = class extends Error {
@@ -15388,8 +16011,8 @@ async function runAwk(ctx) {
15388
16011
  continue;
15389
16012
  }
15390
16013
  try {
15391
- const bytes2 = ctx.vfs.readFile(ctx.path(operand), ctx.cred);
15392
- inputs.push({ name: operand, lines: splitLines(bytes2).lines });
16014
+ const bytes3 = ctx.vfs.readFile(ctx.path(operand), ctx.cred);
16015
+ inputs.push({ name: operand, lines: splitLines(bytes3).lines });
15393
16016
  } catch (e) {
15394
16017
  ctx.reportError(e, operand);
15395
16018
  return 2;
@@ -15532,12 +16155,12 @@ async function followFiles(ctx, paths, intervalMs) {
15532
16155
  if (ctx.signal.aborted) break;
15533
16156
  for (const path of paths) {
15534
16157
  try {
15535
- const bytes2 = ctx.vfs.readFile(ctx.path(path), ctx.cred);
16158
+ const bytes3 = ctx.vfs.readFile(ctx.path(path), ctx.cred);
15536
16159
  const previous = offsets.get(path) ?? 0;
15537
- if (bytes2.length > previous) {
15538
- ctx.write(bytes2.subarray(previous));
15539
- offsets.set(path, bytes2.length);
15540
- } else if (bytes2.length < previous) {
16160
+ if (bytes3.length > previous) {
16161
+ ctx.write(bytes3.subarray(previous));
16162
+ offsets.set(path, bytes3.length);
16163
+ } else if (bytes3.length < previous) {
15541
16164
  offsets.set(path, 0);
15542
16165
  }
15543
16166
  } catch {
@@ -15920,14 +16543,14 @@ var tee = defineCommand({
15920
16543
  { short: "a", long: "append" },
15921
16544
  { short: "i", long: "ignore-interrupts" }
15922
16545
  ]);
15923
- const bytes2 = await ctx.stdin.readAll();
15924
- ctx.write(bytes2);
16546
+ const bytes3 = await ctx.stdin.readAll();
16547
+ ctx.write(bytes3);
15925
16548
  let status = 0;
15926
16549
  for (const target of args.positional) {
15927
16550
  try {
15928
16551
  const abs = ctx.path(target);
15929
- if (args.has("append")) ctx.vfs.appendFile(abs, bytes2, { cred: ctx.cred });
15930
- else ctx.vfs.writeFile(abs, bytes2, { cred: ctx.cred });
16552
+ if (args.has("append")) ctx.vfs.appendFile(abs, bytes3, { cred: ctx.cred });
16553
+ else ctx.vfs.writeFile(abs, bytes3, { cred: ctx.cred });
15931
16554
  } catch (e) {
15932
16555
  status = ctx.reportError(e, target);
15933
16556
  }
@@ -16240,16 +16863,16 @@ var split = defineCommand({
16240
16863
  const [input, prefixRaw] = args.positional;
16241
16864
  const prefix = prefixRaw ?? "x";
16242
16865
  const { sources, ok: ok2 } = await readInputs(ctx, input ? [input] : []);
16243
- const bytes2 = sources[0]?.bytes ?? new Uint8Array(0);
16866
+ const bytes3 = sources[0]?.bytes ?? new Uint8Array(0);
16244
16867
  const suffixLength = args.num("suffix-length", 2);
16245
16868
  const chunks = [];
16246
16869
  const byteSpec = args.str("bytes");
16247
16870
  if (byteSpec !== void 0) {
16248
16871
  const size = parseSize(byteSpec) ?? 1024;
16249
- for (let i = 0; i < bytes2.length; i += size) chunks.push(bytes2.subarray(i, i + size));
16872
+ for (let i = 0; i < bytes3.length; i += size) chunks.push(bytes3.subarray(i, i + size));
16250
16873
  } else {
16251
16874
  const perChunk = args.num("lines", 1e3);
16252
- const { lines } = splitLines(bytes2);
16875
+ const { lines } = splitLines(bytes3);
16253
16876
  for (let i = 0; i < lines.length; i += perChunk) {
16254
16877
  chunks.push(new TextEncoder().encode(joinLines(lines.slice(i, i + perChunk), true)));
16255
16878
  }
@@ -16313,7 +16936,7 @@ var awk = defineCommand({
16313
16936
  usage: "awk [-F fs] [-v var=value] 'program' [FILE]...",
16314
16937
  run: runAwk
16315
16938
  });
16316
- var commands4 = [
16939
+ var commands5 = [
16317
16940
  head,
16318
16941
  tail,
16319
16942
  wc,
@@ -16459,19 +17082,19 @@ var grep = defineCommand({
16459
17082
  let anyMatch = false;
16460
17083
  let status = 1;
16461
17084
  for (const target of targets) {
16462
- let bytes2;
17085
+ let bytes3;
16463
17086
  if (target === "-") {
16464
- bytes2 = await ctx.stdin.readAll();
17087
+ bytes3 = await ctx.stdin.readAll();
16465
17088
  } else {
16466
17089
  try {
16467
- bytes2 = ctx.vfs.readFile(ctx.path(target), ctx.cred);
17090
+ bytes3 = ctx.vfs.readFile(ctx.path(target), ctx.cred);
16468
17091
  } catch (e) {
16469
17092
  if (!args.has("no-messages")) ctx.reportError(e, target);
16470
17093
  status = 2;
16471
17094
  continue;
16472
17095
  }
16473
17096
  }
16474
- const { lines } = splitLines(bytes2);
17097
+ const { lines } = splitLines(bytes3);
16475
17098
  const matched = [];
16476
17099
  let count = 0;
16477
17100
  for (let i = 0; i < lines.length && count < maxCount; i++) {
@@ -17044,7 +17667,7 @@ var cmp = defineCommand({
17044
17667
  return 0;
17045
17668
  }
17046
17669
  });
17047
- var commands5 = [grep, find, xargs, diff, cmp];
17670
+ var commands6 = [grep, find, xargs, diff, cmp];
17048
17671
 
17049
17672
  // src/bin/archive.ts
17050
17673
  init_mode();
@@ -17054,8 +17677,8 @@ var BLOCK = 512;
17054
17677
  var encoder5 = new TextEncoder();
17055
17678
  var decoder7 = new TextDecoder();
17056
17679
  function writeString(block, offset, value, length) {
17057
- const bytes2 = encoder5.encode(value);
17058
- for (let i = 0; i < length; i++) block[offset + i] = i < bytes2.length ? bytes2[i] : 0;
17680
+ const bytes3 = encoder5.encode(value);
17681
+ for (let i = 0; i < length; i++) block[offset + i] = i < bytes3.length ? bytes3[i] : 0;
17059
17682
  }
17060
17683
  function writeOctal(block, offset, value, length) {
17061
17684
  const text2 = value.toString(8).padStart(length - 1, "0");
@@ -17206,23 +17829,23 @@ var tar = defineCommand({
17206
17829
  if (args.has("verbose")) ctx.line(name);
17207
17830
  };
17208
17831
  for (const operand of args.positional) add(resolve(baseDir, operand), operand);
17209
- let bytes3 = createTar(entries2);
17210
- if (compressed) bytes3 = await gzip(bytes3);
17211
- if (archive === void 0 || archive === "-") ctx.write(bytes3);
17212
- else ctx.vfs.writeFile(ctx.path(archive), bytes3, { cred: ctx.cred, mode: 420 });
17832
+ let bytes4 = createTar(entries2);
17833
+ if (compressed) bytes4 = await gzip(bytes4);
17834
+ if (archive === void 0 || archive === "-") ctx.write(bytes4);
17835
+ else ctx.vfs.writeFile(ctx.path(archive), bytes4, { cred: ctx.cred, mode: 420 });
17213
17836
  return 0;
17214
17837
  }
17215
- let bytes2;
17216
- if (archive === void 0 || archive === "-") bytes2 = await ctx.stdin.readAll();
17838
+ let bytes3;
17839
+ if (archive === void 0 || archive === "-") bytes3 = await ctx.stdin.readAll();
17217
17840
  else {
17218
17841
  try {
17219
- bytes2 = ctx.vfs.readFile(ctx.path(archive), ctx.cred);
17842
+ bytes3 = ctx.vfs.readFile(ctx.path(archive), ctx.cred);
17220
17843
  } catch (e) {
17221
17844
  return ctx.reportError(e, archive);
17222
17845
  }
17223
17846
  }
17224
- if (bytes2[0] === 31 && bytes2[1] === 139) bytes2 = await gunzip(bytes2);
17225
- const entries = readTar(bytes2);
17847
+ if (bytes3[0] === 31 && bytes3[1] === 139) bytes3 = await gunzip(bytes3);
17848
+ const entries = readTar(bytes3);
17226
17849
  const strip = args.num("strip-components", 0);
17227
17850
  if (args.has("list")) {
17228
17851
  for (const entry of entries) {
@@ -17359,7 +17982,7 @@ var zlibCompress = defineCommand({
17359
17982
  });
17360
17983
  }
17361
17984
  });
17362
- var commands6 = [tar, gzip2, gunzip2, zcat, zlibCompress];
17985
+ var commands7 = [tar, gzip2, gunzip2, zcat, zlibCompress];
17363
17986
 
17364
17987
  // src/bin/hash.ts
17365
17988
  init_binary();
@@ -17401,8 +18024,8 @@ async function checkSums(ctx, algorithm, files, quiet) {
17401
18024
  checked++;
17402
18025
  const [, expected, name] = m;
17403
18026
  try {
17404
- const bytes2 = ctx.vfs.readFile(ctx.path(name), ctx.cred);
17405
- const actual = await digestHex(algorithm, bytes2);
18027
+ const bytes3 = ctx.vfs.readFile(ctx.path(name), ctx.cred);
18028
+ const actual = await digestHex(algorithm, bytes3);
17406
18029
  if (actual === expected.toLowerCase()) {
17407
18030
  if (!quiet) ctx.line(`${name}: OK`);
17408
18031
  } else {
@@ -17567,7 +18190,7 @@ var mktemp = defineCommand({
17567
18190
  return 0;
17568
18191
  }
17569
18192
  });
17570
- var commands7 = [
18193
+ var commands8 = [
17571
18194
  md5sum,
17572
18195
  sha1sum,
17573
18196
  sha224sum,
@@ -18043,7 +18666,7 @@ var host = defineCommand({
18043
18666
  return 0;
18044
18667
  }
18045
18668
  });
18046
- var commands8 = [curl, wget, ping, ip, ifconfig, ss, netstat, nc, host];
18669
+ var commands9 = [curl, wget, ping, ip, ifconfig, ss, netstat, nc, host];
18047
18670
 
18048
18671
  // src/bin/admin.ts
18049
18672
  init_mode();
@@ -18480,7 +19103,7 @@ sys ${fmt2(Math.floor(ms * 0.2))}
18480
19103
  return code;
18481
19104
  }
18482
19105
  });
18483
- var commands9 = [
19106
+ var commands10 = [
18484
19107
  suCmd,
18485
19108
  sudo,
18486
19109
  useradd,
@@ -18656,7 +19279,7 @@ var helpCmd = defineCommand({
18656
19279
  return 0;
18657
19280
  }
18658
19281
  });
18659
- var commands10 = [man, whatis, apropos, less, helpCmd];
19282
+ var commands11 = [man, whatis, apropos, less, helpCmd];
18660
19283
 
18661
19284
  // src/bin/clipboard.ts
18662
19285
  init_path();
@@ -18671,12 +19294,12 @@ function readSelection(ctx, selection) {
18671
19294
  return new Uint8Array();
18672
19295
  }
18673
19296
  }
18674
- function writeSelection(ctx, selection, bytes2) {
19297
+ function writeSelection(ctx, selection, bytes3) {
18675
19298
  try {
18676
19299
  ctx.vfs.mkdir(CLIPBOARD_DIR, { recursive: true, mode: 511 });
18677
19300
  } catch {
18678
19301
  }
18679
- ctx.vfs.writeFile(selectionPath(selection), bytes2, { privileged: true, mode: 438 });
19302
+ ctx.vfs.writeFile(selectionPath(selection), bytes3, { privileged: true, mode: 438 });
18680
19303
  }
18681
19304
  var xsel = defineCommand({
18682
19305
  name: "xsel",
@@ -18778,8 +19401,8 @@ var wlCopy = defineCommand({
18778
19401
  async run(ctx) {
18779
19402
  const selection = ctx.args.includes("--primary") || ctx.args.includes("-p") ? "primary" : "clipboard";
18780
19403
  const operands = ctx.args.filter((arg) => !arg.startsWith("-"));
18781
- const bytes2 = operands.length ? new TextEncoder().encode(operands.join(" ")) : await ctx.stdin.readAll();
18782
- writeSelection(ctx, selection, bytes2);
19404
+ const bytes3 = operands.length ? new TextEncoder().encode(operands.join(" ")) : await ctx.stdin.readAll();
19405
+ writeSelection(ctx, selection, bytes3);
18783
19406
  return 0;
18784
19407
  }
18785
19408
  });
@@ -18789,13 +19412,13 @@ var wlPaste = defineCommand({
18789
19412
  usage: "wl-paste [--primary] [-n]",
18790
19413
  run(ctx) {
18791
19414
  const selection = ctx.args.includes("--primary") || ctx.args.includes("-p") ? "primary" : "clipboard";
18792
- const bytes2 = readSelection(ctx, selection);
18793
- ctx.write(bytes2);
19415
+ const bytes3 = readSelection(ctx, selection);
19416
+ ctx.write(bytes3);
18794
19417
  if (!ctx.args.includes("-n") && !ctx.args.includes("--no-newline")) ctx.write("\n");
18795
19418
  return 0;
18796
19419
  }
18797
19420
  });
18798
- var commands11 = [xsel, xclip, pbcopy, pbpaste, wlCopy, wlPaste];
19421
+ var commands12 = [xsel, xclip, pbcopy, pbpaste, wlCopy, wlPaste];
18799
19422
 
18800
19423
  // src/node/node.ts
18801
19424
  init_path();
@@ -19243,8 +19866,6 @@ ${lines[index]}`;
19243
19866
  }
19244
19867
  return out;
19245
19868
  }
19246
-
19247
- // src/node/node.ts
19248
19869
  var NODE_VERSION = "v22.12.0";
19249
19870
  new TextEncoder();
19250
19871
  var tempCounter = 0;
@@ -19388,10 +20009,10 @@ async function execute(ctx, invocation) {
19388
20009
  }
19389
20010
  async function captureStdin(ctx) {
19390
20011
  if (ctx.stdin.isTTY || ctx.stdin.interactive) return null;
19391
- const bytes2 = await ctx.stdin.readAll();
19392
- if (bytes2.length === 0) return null;
20012
+ const bytes3 = await ctx.stdin.readAll();
20013
+ if (bytes3.length === 0) return null;
19393
20014
  const path = tempPath("stdin", ctx.proc.pid, ".dat");
19394
- ctx.vfs.writeFile(path, bytes2, { privileged: true, mode: 384 });
20015
+ ctx.vfs.writeFile(path, bytes3, { privileged: true, mode: 384 });
19395
20016
  return path;
19396
20017
  }
19397
20018
  var node = defineCommand({
@@ -19618,7 +20239,7 @@ ${prelude}${preloadRequires(preloads)}${source}
19618
20239
  }
19619
20240
  function resolveScript(ctx, operand) {
19620
20241
  const base2 = ctx.path(operand);
19621
- const candidates2 = [base2, `${base2}.js`, `${base2}.mjs`, `${base2}.cjs`, `${base2}.json`];
20242
+ const candidates2 = [base2, `${base2}.js`, `${base2}.mjs`, `${base2}.cjs`, `${base2}.ts`, `${base2}.tsx`, `${base2}.json`];
19622
20243
  for (const candidate of candidates2) {
19623
20244
  try {
19624
20245
  const st = ctx.vfs.stat(candidate, { cred: ctx.cred });
@@ -19636,7 +20257,7 @@ function resolveScript(ctx, operand) {
19636
20257
  } catch {
19637
20258
  }
19638
20259
  }
19639
- for (const index of ["index.js", "index.mjs", "index.cjs"]) {
20260
+ for (const index of ["index.js", "index.mjs", "index.cjs", "index.ts", "index.tsx"]) {
19640
20261
  const path = join(candidate, index);
19641
20262
  if (ctx.vfs.lexists(path)) return ctx.vfs.realpath(path, ctx.cred);
19642
20263
  }
@@ -19753,6 +20374,13 @@ function checkSyntax(ctx, script) {
19753
20374
  let source = ctx.vfs.readText(script, ctx.cred);
19754
20375
  if (source.startsWith("#!")) source = `//${source.slice(2)}`;
19755
20376
  try {
20377
+ if (script.endsWith(".ts") || script.endsWith(".tsx")) {
20378
+ source = transform(source, {
20379
+ transforms: script.endsWith(".tsx") ? ["typescript", "jsx"] : ["typescript"],
20380
+ filePath: script,
20381
+ production: true
20382
+ }).code;
20383
+ }
19756
20384
  const esm = script.endsWith(".mjs") || !script.endsWith(".cjs") && looksLikeEsm(source);
19757
20385
  const transformed = esm ? transformEsm(source, script) : null;
19758
20386
  new AsyncFunction("exports", "require", "module", "__filename", "__dirname", transformed?.code ?? source);
@@ -21086,7 +21714,7 @@ var wheels_default = {
21086
21714
 
21087
21715
  // package.json
21088
21716
  var package_default = {
21089
- version: "0.2.21"};
21717
+ version: "0.2.23"};
21090
21718
 
21091
21719
  // src/python/extension-abi.ts
21092
21720
  var EXTENSION_ABI = {
@@ -21937,9 +22565,9 @@ var Reader = class {
21937
22565
  at = 0;
21938
22566
  view;
21939
22567
  bytes;
21940
- constructor(bytes2) {
21941
- this.bytes = bytes2;
21942
- this.view = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength);
22568
+ constructor(bytes3) {
22569
+ this.bytes = bytes3;
22570
+ this.view = new DataView(bytes3.buffer, bytes3.byteOffset, bytes3.byteLength);
21943
22571
  }
21944
22572
  need(count) {
21945
22573
  if (this.at + count > this.bytes.length) throw new ProtocolError("payload underrun");
@@ -22025,9 +22653,9 @@ var ByteQueue = class {
22025
22653
  chunks = [];
22026
22654
  length = 0;
22027
22655
  waiters = /* @__PURE__ */ new Set();
22028
- push(bytes2) {
22029
- if (bytes2.length === 0) return;
22030
- const copy = bytes2.slice();
22656
+ push(bytes3) {
22657
+ if (bytes3.length === 0) return;
22658
+ const copy = bytes3.slice();
22031
22659
  this.chunks.push(copy);
22032
22660
  this.length += copy.length;
22033
22661
  this.wake();
@@ -22087,10 +22715,10 @@ var VirtualTcpConnection = class {
22087
22715
  if (this.eof) return new Uint8Array();
22088
22716
  throw new PosixError(Errno.EAGAIN, "socket read would block");
22089
22717
  }
22090
- write(bytes2) {
22718
+ write(bytes3) {
22091
22719
  if (!this.writable) throw new PosixError(this.closed || this.writeClosed ? Errno.EPIPE : Errno.ECONNRESET);
22092
- this.peer.incoming.push(bytes2);
22093
- return bytes2.length;
22720
+ this.peer.incoming.push(bytes3);
22721
+ return bytes3.length;
22094
22722
  }
22095
22723
  async waitForChange() {
22096
22724
  if (this.readable || this.closed) return;
@@ -22373,9 +23001,9 @@ var SO_ERROR = 4;
22373
23001
  var SO_TYPE = 3;
22374
23002
  var SOCK_STREAM = 1;
22375
23003
  function int32(value) {
22376
- const bytes2 = new Uint8Array(4);
22377
- new DataView(bytes2.buffer).setInt32(0, value, true);
22378
- return bytes2;
23004
+ const bytes3 = new Uint8Array(4);
23005
+ new DataView(bytes3.buffer).setInt32(0, value, true);
23006
+ return bytes3;
22379
23007
  }
22380
23008
  function isLoopback(address) {
22381
23009
  if (address === "" || address === "localhost" || address === "0.0.0.0") return true;
@@ -22766,9 +23394,9 @@ function createHostAbiServer(proc) {
22766
23394
  /* ---------------------------------------------------------- entropy */
22767
23395
  case Op.getrandom: {
22768
23396
  const length = Math.min(r.u32(), 65536);
22769
- const bytes2 = new Uint8Array(length);
22770
- crypto.getRandomValues(bytes2);
22771
- return { status: length, payload: bytes2 };
23397
+ const bytes3 = new Uint8Array(length);
23398
+ crypto.getRandomValues(bytes3);
23399
+ return { status: length, payload: bytes3 };
22772
23400
  }
22773
23401
  /* ----------------------------------------------------------- sockets */
22774
23402
  case Op.socket: {
@@ -23254,9 +23882,9 @@ var FIRST_EGRESS_PORT = 48e3;
23254
23882
  var MAX_HEADER_BYTES = 64 * 1024;
23255
23883
  var MAX_BODY_BYTES = 32 * 1024 * 1024;
23256
23884
  var CRLF = "\r\n";
23257
- function indexOfDoubleCrlf(bytes2) {
23258
- for (let i = 3; i < bytes2.length; i++) {
23259
- if (bytes2[i] === 10 && bytes2[i - 1] === 13 && bytes2[i - 2] === 10 && bytes2[i - 3] === 13) return i + 1;
23885
+ function indexOfDoubleCrlf(bytes3) {
23886
+ for (let i = 3; i < bytes3.length; i++) {
23887
+ if (bytes3[i] === 10 && bytes3[i - 1] === 13 && bytes3[i - 2] === 10 && bytes3[i - 3] === 13) return i + 1;
23260
23888
  }
23261
23889
  return -1;
23262
23890
  }
@@ -23521,62 +24149,6 @@ function splitOnce(text2, separator) {
23521
24149
  return at < 0 ? [text2] : [text2.slice(0, at), text2.slice(at + 1)];
23522
24150
  }
23523
24151
 
23524
- // src/browser/playwright-browsers.ts
23525
- init_path();
23526
- var PLAYWRIGHT_REGISTRY = "/root/.cache/ms-playwright";
23527
- var LAYOUTS = {
23528
- "chromium": ["chrome-linux64", "chrome"],
23529
- "chromium-headless-shell": ["chrome-headless-shell-linux64", "chrome-headless-shell"]
23530
- };
23531
- function virtualBrowserFiles(browsersJson) {
23532
- let manifest;
23533
- try {
23534
- manifest = JSON.parse(browsersJson);
23535
- } catch {
23536
- return [];
23537
- }
23538
- const encoder9 = new TextEncoder();
23539
- const files = [];
23540
- for (const browser of manifest.browsers ?? []) {
23541
- const layout = LAYOUTS[browser.name];
23542
- if (!layout) continue;
23543
- const dir3 = join(PLAYWRIGHT_REGISTRY, `${browser.name.replace(/-/g, "_")}-${browser.revision}`);
23544
- files.push({ path: join(dir3, ...layout), data: encoder9.encode(`#!${BUILTIN_INTERPRETER} chrome
23545
- `), mode: 493 });
23546
- files.push({ path: join(dir3, "INSTALLATION_COMPLETE"), data: new Uint8Array() });
23547
- }
23548
- return files;
23549
- }
23550
- function mkdirp(volume, path) {
23551
- let current2 = "";
23552
- for (const part of segments(path)) {
23553
- current2 += `/${part}`;
23554
- try {
23555
- volume.mkdirSync(current2, { mode: 493 });
23556
- } catch (error) {
23557
- if (error.code !== "EEXIST") throw error;
23558
- }
23559
- }
23560
- }
23561
- function installVirtualPlaywrightBrowsers(volume, packageDir) {
23562
- let text2;
23563
- try {
23564
- text2 = new TextDecoder().decode(volume.readFileSync(join(packageDir, "browsers.json")));
23565
- } catch {
23566
- return [];
23567
- }
23568
- const written = [];
23569
- for (const file3 of virtualBrowserFiles(text2)) {
23570
- mkdirp(volume, dirname(file3.path));
23571
- volume.writeFileSync(file3.path, file3.data);
23572
- if (file3.mode !== void 0) {
23573
- volume.chmodSync(file3.path, file3.mode);
23574
- written.push(file3.path);
23575
- }
23576
- }
23577
- return written;
23578
- }
23579
-
23580
24152
  // src/python/substitutions.ts
23581
24153
  var SUBSTITUTED_WHEELS = {
23582
24154
  playwright: /-py3-none-manylinux1_x86_64\.whl$/
@@ -24143,27 +24715,27 @@ async function installRequirements(options) {
24143
24715
  continue;
24144
24716
  }
24145
24717
  options.progress.downloading(distribution.name, distribution.version);
24146
- const bytes2 = await download(options.client, distribution);
24147
- const files = stageWheel(readZip(bytes2));
24718
+ const bytes3 = await download(options.client, distribution);
24719
+ const files = stageWheel(readZip(bytes3));
24148
24720
  staged.push(...distribution.kind === "substituted" ? substituteFiles(distribution.name, files, SITE_PACKAGES) : files);
24149
24721
  installed3.push({ name: distribution.name, version: distribution.version });
24150
24722
  }
24151
24723
  commit(options.vfs, options.cred, staged);
24152
24724
  return { installed: installed3, skipped: solved.skipped };
24153
24725
  }
24154
- function requireArchive(distribution, bytes2) {
24155
- if (bytes2.length > 1 && bytes2[0] === 80 && bytes2[1] === 75) return;
24156
- const opening = new TextDecoder().decode(bytes2.subarray(0, 80)).replace(/\s+/g, " ").trim();
24726
+ function requireArchive(distribution, bytes3) {
24727
+ if (bytes3.length > 1 && bytes3[0] === 80 && bytes3[1] === 75) return;
24728
+ const opening = new TextDecoder().decode(bytes3.subarray(0, 80)).replace(/\s+/g, " ").trim();
24157
24729
  const looksLikeMarkup = /^<!doctype|^<html/i.test(opening);
24158
24730
  throw new Error(
24159
- `${distribution.filename} did not arrive as a wheel from ${distribution.url}: ` + (looksLikeMarkup ? "the server answered with an HTML page, which usually means the wheel is not published at that address and the server returned its index page instead" : `expected a zip archive, got ${bytes2.length} bytes beginning ${JSON.stringify(opening)}`)
24731
+ `${distribution.filename} did not arrive as a wheel from ${distribution.url}: ` + (looksLikeMarkup ? "the server answered with an HTML page, which usually means the wheel is not published at that address and the server returned its index page instead" : `expected a zip archive, got ${bytes3.length} bytes beginning ${JSON.stringify(opening)}`)
24160
24732
  );
24161
24733
  }
24162
24734
  async function download(client, distribution) {
24163
- const bytes2 = await client.bytes(distribution.url, { timeoutMs: 12e4 });
24164
- requireArchive(distribution, bytes2);
24165
- const mismatch = digestMismatch(distribution, bytes2);
24166
- if (!mismatch) return bytes2;
24735
+ const bytes3 = await client.bytes(distribution.url, { timeoutMs: 12e4 });
24736
+ requireArchive(distribution, bytes3);
24737
+ const mismatch = digestMismatch(distribution, bytes3);
24738
+ if (!mismatch) return bytes3;
24167
24739
  const fresh = await refetch(client, distribution);
24168
24740
  if (fresh && !digestMismatch(distribution, fresh)) {
24169
24741
  requireArchive(distribution, fresh);
@@ -24176,22 +24748,22 @@ async function download(client, distribution) {
24176
24748
  async function refetch(client, distribution) {
24177
24749
  const separator = distribution.url.includes("?") ? "&" : "?";
24178
24750
  try {
24179
- const bytes2 = await client.bytes(
24751
+ const bytes3 = await client.bytes(
24180
24752
  `${distribution.url}${separator}sha256=${distribution.sha256}`,
24181
24753
  { timeoutMs: 6e4 }
24182
24754
  );
24183
- return bytes2.length > 1 && bytes2[0] === 80 && bytes2[1] === 75 ? bytes2 : null;
24755
+ return bytes3.length > 1 && bytes3[0] === 80 && bytes3[1] === 75 ? bytes3 : null;
24184
24756
  } catch {
24185
24757
  return null;
24186
24758
  }
24187
24759
  }
24188
- function digestMismatch(distribution, bytes2) {
24760
+ function digestMismatch(distribution, bytes3) {
24189
24761
  if (!distribution.sha256) {
24190
24762
  throw new Error(
24191
24763
  `${distribution.filename} was published without a sha256 digest, so it cannot be verified`
24192
24764
  );
24193
24765
  }
24194
- const actual = [...sha256(bytes2)].map((b) => b.toString(16).padStart(2, "0")).join("");
24766
+ const actual = [...sha256(bytes3)].map((b) => b.toString(16).padStart(2, "0")).join("");
24195
24767
  if (actual === distribution.sha256) return null;
24196
24768
  return `${distribution.filename} failed verification: the index published sha256 ${distribution.sha256} but the download hashes to ${actual}.`;
24197
24769
  }
@@ -24321,9 +24893,9 @@ function outputFor(description, fallback) {
24321
24893
  return {
24322
24894
  write(data) {
24323
24895
  if (broken) return;
24324
- const bytes2 = typeof data === "string" ? new TextEncoder().encode(data) : data;
24325
- if (bytes2.length === 0) return;
24326
- queue.push(bytes2.slice());
24896
+ const bytes3 = typeof data === "string" ? new TextEncoder().encode(data) : data;
24897
+ if (bytes3.length === 0) return;
24898
+ queue.push(bytes3.slice());
24327
24899
  if (!active) done = pump();
24328
24900
  },
24329
24901
  end() {
@@ -25688,9 +26260,9 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25688
26260
  )];
25689
26261
  if (embedded) {
25690
26262
  const binary = atob(embedded);
25691
- const bytes2 = new Uint8Array(binary.length);
25692
- for (let i = 0; i < binary.length; i += 1) bytes2[i] = binary.charCodeAt(i);
25693
- return await read(new Response(bytes2));
26263
+ const bytes3 = new Uint8Array(binary.length);
26264
+ for (let i = 0; i < binary.length; i += 1) bytes3[i] = binary.charCodeAt(i);
26265
+ return await read(new Response(bytes3));
25694
26266
  }
25695
26267
  if (url.startsWith("sbx-wheel:")) {
25696
26268
  const filename = decodeURIComponent(url.slice("sbx-wheel:".length).replace(/^\/+/, ""));
@@ -25759,7 +26331,7 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25759
26331
  let attemptsLeft = 12;
25760
26332
  for (; ; ) {
25761
26333
  try {
25762
- const report = await installRequirements({
26334
+ const report2 = await installRequirements({
25763
26335
  index,
25764
26336
  client,
25765
26337
  vfs: ctx.vfs,
@@ -25780,11 +26352,11 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25780
26352
  }
25781
26353
  }
25782
26354
  });
25783
- for (const skipped of report.skipped) {
26355
+ for (const skipped of report2.skipped) {
25784
26356
  ctx.line(` Skipping ${skipped.name} (marker: ${skipped.marker})`);
25785
26357
  }
25786
26358
  ctx.line(
25787
- `Successfully installed ${report.installed.map((p) => `${p.name}-${p.version}`).join(" ")}`
26359
+ `Successfully installed ${report2.installed.map((p) => `${p.name}-${p.version}`).join(" ")}`
25788
26360
  );
25789
26361
  return 0;
25790
26362
  } catch (error) {
@@ -26170,11 +26742,11 @@ async function loadFactory() {
26170
26742
  function getCompiled() {
26171
26743
  compiled2 ??= (async () => {
26172
26744
  const { factory, wasm } = await loadFactory();
26173
- const bytes2 = wasm.buffer.slice(
26745
+ const bytes3 = wasm.buffer.slice(
26174
26746
  wasm.byteOffset,
26175
26747
  wasm.byteOffset + wasm.byteLength
26176
26748
  );
26177
- return { factory, module: await WebAssembly.compile(bytes2) };
26749
+ return { factory, module: await WebAssembly.compile(bytes3) };
26178
26750
  })();
26179
26751
  void compiled2.catch(() => compiled2 = null);
26180
26752
  return compiled2;
@@ -26322,18 +26894,18 @@ than a packet path, and socket calls report ENOTSUP.`,
26322
26894
  }
26323
26895
  if (module === void 0) return ctx.reportError(new UsageError("a module is required"));
26324
26896
  const abs = ctx.path(module);
26325
- let bytes2;
26897
+ let bytes3;
26326
26898
  try {
26327
- bytes2 = ctx.vfs.readFile(abs, ctx.cred);
26899
+ bytes3 = ctx.vfs.readFile(abs, ctx.cred);
26328
26900
  } catch (error) {
26329
26901
  ctx.reportError(error, abs);
26330
26902
  return EXIT_NOT_FOUND;
26331
26903
  }
26332
- if (!isWasmBinary(bytes2)) {
26904
+ if (!isWasmBinary(bytes3)) {
26333
26905
  return ctx.fail(`${abs}: not a WebAssembly module`, 126);
26334
26906
  }
26335
26907
  Object.assign(ctx.env, env2);
26336
- return await runWasi(ctx, bytes2, {
26908
+ return await runWasi(ctx, bytes3, {
26337
26909
  /* argv[0] is the path as the user wrote it, not the resolved one: a
26338
26910
  * program printing its own usage should echo what was typed. */
26339
26911
  argv: [module, ...rest],
@@ -26344,398 +26916,6 @@ than a packet path, and socket calls report ENOTSUP.`,
26344
26916
  function wasiCommands() {
26345
26917
  return [wasi];
26346
26918
  }
26347
- var platformBuffer = globalThis.Buffer;
26348
- addUint8ArraySupport(addBase64UrlSupport(Buffer$1));
26349
- var Buffer2 = platformBuffer ?? Buffer$1;
26350
- function addUint8ArraySupport(BufferClass) {
26351
- const target = BufferClass;
26352
- if (target.__sandboxedUint8Array) return BufferClass;
26353
- Object.defineProperty(target, "__sandboxedUint8Array", { value: true });
26354
- const asBuffer = (value) => value instanceof Uint8Array && !target.isBuffer(value) ? target.from(value.buffer, value.byteOffset, value.byteLength) : value;
26355
- for (const method of ["indexOf", "lastIndexOf", "includes"]) {
26356
- const original = target.prototype[method];
26357
- target.prototype[method] = function(value, ...rest) {
26358
- return original.call(this, asBuffer(value), ...rest);
26359
- };
26360
- }
26361
- const equals = target.prototype.equals;
26362
- target.prototype.equals = function(other) {
26363
- return equals.call(this, asBuffer(other));
26364
- };
26365
- return BufferClass;
26366
- }
26367
- function addBase64UrlSupport(BufferClass) {
26368
- const target = BufferClass;
26369
- if (target.__sandboxedBase64Url) return BufferClass;
26370
- Object.defineProperty(target, "__sandboxedBase64Url", { value: true });
26371
- const from = target.from.bind(target);
26372
- target.from = (value, encodingOrOffset, length) => from(value, normalizeEncoding(encodingOrOffset), length);
26373
- const byteLength = target.byteLength.bind(target);
26374
- target.byteLength = (value, encoding) => byteLength(value, normalizeEncoding(encoding));
26375
- const isEncoding = target.isEncoding?.bind(target);
26376
- if (isEncoding) target.isEncoding = (encoding) => encoding.toLowerCase() === "base64url" || isEncoding(encoding);
26377
- const toString = target.prototype.toString;
26378
- target.prototype.toString = function(encoding, start2, end) {
26379
- if (encoding?.toLowerCase() !== "base64url") return toString.call(this, encoding, start2, end);
26380
- return toString.call(this, "base64", start2, end).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
26381
- };
26382
- const write = target.prototype.write;
26383
- target.prototype.write = function(...args) {
26384
- const index = typeof args[1] === "string" ? 1 : typeof args[2] === "string" ? 2 : 3;
26385
- if (typeof args[index] === "string") args[index] = normalizeEncoding(args[index]);
26386
- return write.apply(this, args);
26387
- };
26388
- return BufferClass;
26389
- }
26390
- function normalizeEncoding(value) {
26391
- return typeof value === "string" && value.toLowerCase() === "base64url" ? "base64" : value;
26392
- }
26393
-
26394
- // src/pkg/clean-installer.ts
26395
- init_path();
26396
- var CleanPackageInstaller = class _CleanPackageInstaller {
26397
- constructor(volume, options = {}) {
26398
- this.volume = volume;
26399
- this.options = options;
26400
- this.registry = (options.registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
26401
- this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
26402
- }
26403
- volume;
26404
- options;
26405
- registry;
26406
- fetcher;
26407
- metadata = /* @__PURE__ */ new Map();
26408
- tarballs = /* @__PURE__ */ new Map();
26409
- /** Single-version manifests, for the fields the packument omits. */
26410
- details = /* @__PURE__ */ new Map();
26411
- forCwd(cwd) {
26412
- const installer = new _CleanPackageInstaller(this.volume, { ...this.options, cwd });
26413
- installer.metadata = this.metadata;
26414
- installer.tarballs = this.tarballs;
26415
- installer.details = this.details;
26416
- return installer;
26417
- }
26418
- async install(name, version = "latest", options = {}) {
26419
- const cwd = this.options.cwd ?? "/";
26420
- const manifest = await this.installAt(name, version || "latest", join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26421
- if (options.persist !== false) this.persist(cwd, name, version, options.persistDev === true);
26422
- return manifest;
26423
- }
26424
- async installFromManifest(path, options = {}) {
26425
- const project = this.readJson(path);
26426
- const cwd = dirname(path);
26427
- const dependencies = {
26428
- ...project.dependencies ?? {},
26429
- ...options.withDevDeps === false ? {} : project.devDependencies ?? {}
26430
- };
26431
- await this.prefetch(dependencies);
26432
- for (const [name, range] of Object.entries(dependencies)) {
26433
- await this.installAt(name, range, join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26434
- }
26435
- }
26436
- async installAt(name, range, modulesRoot, options, ancestry) {
26437
- const metadata = await this.getMetadata(name);
26438
- const version = resolveVersion(metadata, range);
26439
- const manifest = metadata.versions[version];
26440
- if (!manifest) throw new Error(`No matching version found for ${name}@${range}`);
26441
- const identity = `${name}@${version}`;
26442
- if (!supportsPlatform(manifest)) throw new IncompatiblePlatform(identity, "");
26443
- if (manifest.os?.length || manifest.cpu?.length) {
26444
- const detail = await this.platformDetail(name, version);
26445
- if (!platformListAllows(detail.libc, PLATFORM.libc)) {
26446
- throw new IncompatiblePlatform(identity, ` (needs ${detail.libc?.join(", ")})`);
26447
- }
26448
- if (detail.main?.endsWith(".node")) {
26449
- throw new IncompatiblePlatform(identity, " (native addon; this runtime cannot dlopen)");
26450
- }
26451
- }
26452
- const target = join(modulesRoot, name);
26453
- const installed3 = this.tryReadJson(join(target, "package.json"));
26454
- if (ancestry.has(identity)) return manifest;
26455
- if (installed3?.version !== version) {
26456
- options.onProgress?.(`Fetching ${identity}`);
26457
- const archive = await this.getTarball(manifest.dist.tarball);
26458
- verifyIntegrity(archive, manifest.dist.integrity, manifest.dist.shasum, identity);
26459
- this.removeIfPresent(target);
26460
- mkdirp2(this.volume, target);
26461
- extractNpmTarball(this.volume, archive, target);
26462
- options.onProgress?.(`Installed ${identity}`);
26463
- }
26464
- this.createBinLinks(manifest, target, modulesRoot);
26465
- if (name === "playwright-core") {
26466
- for (const executable of installVirtualPlaywrightBrowsers(this.volume, target)) {
26467
- options.onProgress?.(`Linked ${executable} to the virtual browser`);
26468
- }
26469
- }
26470
- const nextAncestry = new Set(ancestry).add(identity);
26471
- const childRoot = join(target, "node_modules");
26472
- const required = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name2]) => !(name2 in (manifest.optionalDependencies ?? {}))));
26473
- await this.prefetch(required);
26474
- for (const [dependency, dependencyRange] of Object.entries(required)) {
26475
- await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26476
- }
26477
- for (const [dependency, dependencyRange] of Object.entries(manifest.optionalDependencies ?? {})) {
26478
- try {
26479
- await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26480
- } catch (error) {
26481
- if (error instanceof IncompatiblePlatform) continue;
26482
- options.onProgress?.(`Skipped optional ${dependency}: ${error instanceof Error ? error.message : String(error)}`);
26483
- }
26484
- }
26485
- return manifest;
26486
- }
26487
- /**
26488
- * The `libc` and `main` fields, which the abbreviated packument leaves out.
26489
- *
26490
- * Fetched per version rather than as a full packument: the single-version
26491
- * document is a few kilobytes, while the full one for a popular package runs
26492
- * to megabytes. Only packages that already declare `os` or `cpu` ask for it,
26493
- * so an ordinary install of pure-JavaScript dependencies makes no extra
26494
- * requests at all — it is the prebuilt binaries, a handful per project, that
26495
- * need the answer.
26496
- *
26497
- * A failure here is not fatal. Being unable to read `libc` puts the check
26498
- * back where it was before this existed, which is worth strictly less than
26499
- * being right and strictly more than refusing to install.
26500
- */
26501
- async platformDetail(name, version) {
26502
- const key = `${name}@${version}`;
26503
- let request = this.details.get(key);
26504
- if (!request) {
26505
- request = (async () => {
26506
- try {
26507
- const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
26508
- const response = await this.fetcher(`${this.registry}/${encoded}/${version}`);
26509
- if (!response.ok) return {};
26510
- return await response.json();
26511
- } catch {
26512
- return {};
26513
- }
26514
- })();
26515
- this.details.set(key, request);
26516
- }
26517
- return request;
26518
- }
26519
- /** Overlap up to six sibling downloads; filesystem writes remain ordered. */
26520
- async prefetch(dependencies) {
26521
- const entries = Object.entries(dependencies);
26522
- let next = 0;
26523
- await Promise.all(Array.from({ length: Math.min(6, entries.length) }, async () => {
26524
- while (next < entries.length) {
26525
- const [name, range] = entries[next++];
26526
- try {
26527
- const metadata = await this.getMetadata(name);
26528
- const manifest = metadata.versions[resolveVersion(metadata, range)];
26529
- if (!manifest.os?.length && !manifest.cpu?.length && supportsPlatform(manifest)) {
26530
- await this.getTarball(manifest.dist.tarball);
26531
- }
26532
- } catch {
26533
- }
26534
- }
26535
- }));
26536
- }
26537
- async getMetadata(name) {
26538
- let request = this.metadata.get(name);
26539
- if (!request) {
26540
- request = (async () => {
26541
- const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
26542
- const response = await this.fetcher(`${this.registry}/${encoded}`, {
26543
- headers: { Accept: "application/vnd.npm.install-v1+json" }
26544
- });
26545
- if (!response.ok) throw new Error(`registry returned ${response.status} for ${name}`);
26546
- return await response.json();
26547
- })();
26548
- this.metadata.set(name, request);
26549
- void request.catch(() => {
26550
- this.metadata.delete(name);
26551
- });
26552
- }
26553
- return request;
26554
- }
26555
- async getTarball(url) {
26556
- let request = this.tarballs.get(url);
26557
- if (!request) {
26558
- request = (async () => {
26559
- const response = await this.fetcher(url);
26560
- if (!response.ok) throw new Error(`tarball returned ${response.status}: ${url}`);
26561
- return new Uint8Array(await response.arrayBuffer());
26562
- })();
26563
- this.tarballs.set(url, request);
26564
- void request.catch(() => {
26565
- this.tarballs.delete(url);
26566
- });
26567
- }
26568
- return request;
26569
- }
26570
- createBinLinks(manifest, target, modulesRoot) {
26571
- if (!manifest.bin) return;
26572
- const bins = typeof manifest.bin === "string" ? { [unscoped(manifest.name)]: manifest.bin } : manifest.bin;
26573
- const binDir = join(modulesRoot, ".bin");
26574
- mkdirp2(this.volume, binDir);
26575
- for (const [name, path] of Object.entries(bins)) {
26576
- const link = join(binDir, name);
26577
- this.removeIfPresent(link);
26578
- this.volume.symlinkSync(relative(binDir, join(target, path)), link);
26579
- }
26580
- }
26581
- persist(cwd, name, range, dev) {
26582
- const path = join(cwd, "package.json");
26583
- const manifest = this.tryReadJson(path) ?? {};
26584
- const key = dev ? "devDependencies" : "dependencies";
26585
- manifest[key] = { ...manifest[key] ?? {}, [name]: range === "latest" ? "*" : range };
26586
- this.volume.writeFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
26587
- }
26588
- removeIfPresent(path) {
26589
- let stat2;
26590
- try {
26591
- stat2 = this.volume.lstatSync(path);
26592
- } catch {
26593
- return;
26594
- }
26595
- if (!stat2.isDirectory()) return this.volume.unlinkSync(path);
26596
- for (const name of this.volume.readdirSync(path)) this.removeIfPresent(join(path, name));
26597
- this.volume.rmdirSync(path);
26598
- }
26599
- readJson(path) {
26600
- return JSON.parse(new TextDecoder().decode(this.volume.readFileSync(path)));
26601
- }
26602
- tryReadJson(path) {
26603
- try {
26604
- return this.readJson(path);
26605
- } catch {
26606
- return null;
26607
- }
26608
- }
26609
- };
26610
- var PLATFORM = { os: "linux", cpu: "x64", libc: "glibc" };
26611
- var IncompatiblePlatform = class extends Error {
26612
- constructor(identity, detail) {
26613
- super(`${identity} is not compatible with ${PLATFORM.os}/${PLATFORM.cpu}/${PLATFORM.libc}${detail}`);
26614
- this.name = "IncompatiblePlatform";
26615
- }
26616
- };
26617
- function supportsPlatform(manifest) {
26618
- return platformListAllows(manifest.os, PLATFORM.os) && platformListAllows(manifest.cpu, PLATFORM.cpu) && platformListAllows(manifest.libc, PLATFORM.libc);
26619
- }
26620
- function platformListAllows(values, current2) {
26621
- if (!values?.length) return true;
26622
- if (values.includes(`!${current2}`)) return false;
26623
- const positive = values.filter((value) => !value.startsWith("!"));
26624
- return positive.length === 0 || positive.includes(current2) || positive.includes("any");
26625
- }
26626
- function resolveVersion(metadata, range) {
26627
- const tag2 = metadata["dist-tags"]?.[range];
26628
- if (tag2) return tag2;
26629
- if (valid(range) && metadata.versions[range]) return range;
26630
- const found2 = maxSatisfying(Object.keys(metadata.versions), range === "latest" ? "*" : range, { includePrerelease: false });
26631
- if (!found2) throw new Error(`No matching version found for ${metadata.name}@${range}`);
26632
- return found2;
26633
- }
26634
- function verifyIntegrity(data, integrity, shasum, identity) {
26635
- if (integrity) {
26636
- const choices = integrity.trim().split(/\s+/);
26637
- for (const choice of choices) {
26638
- const dash = choice.indexOf("-");
26639
- const algorithm = choice.slice(0, dash);
26640
- const expected = choice.slice(dash + 1).replace(/\?.*$/, "");
26641
- const digest2 = algorithm === "sha512" ? sha512(data) : algorithm === "sha256" ? sha256(data) : null;
26642
- if (digest2 && Buffer2.from(digest2).toString("base64") === expected) return;
26643
- }
26644
- throw new Error(`Integrity check failed for ${identity}`);
26645
- }
26646
- if (shasum && Buffer2.from(sha1(data)).toString("hex") === shasum) return;
26647
- if (shasum) throw new Error(`Legacy checksum check failed for ${identity}`);
26648
- }
26649
- function extractNpmTarball(volume, compressed, destination) {
26650
- const tar2 = ungzip(compressed);
26651
- let offset = 0;
26652
- let longPath = null;
26653
- let paxPath = null;
26654
- while (offset + 512 <= tar2.length) {
26655
- const header = tar2.subarray(offset, offset + 512);
26656
- if (header.every((byte) => byte === 0)) break;
26657
- const size = octal(header, 124, 12);
26658
- const type = String.fromCharCode(header[156] || 48);
26659
- const prefix = text(header, 345, 155);
26660
- let name = longPath ?? paxPath ?? [prefix, text(header, 0, 100)].filter(Boolean).join("/");
26661
- longPath = null;
26662
- paxPath = null;
26663
- const data = tar2.subarray(offset + 512, offset + 512 + size);
26664
- offset += 512 + Math.ceil(size / 512) * 512;
26665
- if (type === "L") {
26666
- longPath = new TextDecoder().decode(data).replace(/\0.*$/, "").trim();
26667
- continue;
26668
- }
26669
- if (type === "x" || type === "g") {
26670
- paxPath = parsePax(data).path ?? null;
26671
- continue;
26672
- }
26673
- name = stripPackageRoot(name);
26674
- if (!name) continue;
26675
- const target = safeTarget(destination, name);
26676
- const mode = octal(header, 100, 8) || 420;
26677
- if (type === "5") {
26678
- mkdirp2(volume, target, mode);
26679
- } else if (type === "2") {
26680
- mkdirp2(volume, dirname(target));
26681
- volume.symlinkSync(text(header, 157, 100), target);
26682
- } else if (type === "1") {
26683
- mkdirp2(volume, dirname(target));
26684
- volume.linkSync(safeTarget(destination, stripPackageRoot(text(header, 157, 100))), target);
26685
- } else if (type === "0" || type === "\0" || type === "7") {
26686
- mkdirp2(volume, dirname(target));
26687
- volume.writeFileSync(target, data.slice());
26688
- volume.chmodSync(target, mode);
26689
- }
26690
- }
26691
- }
26692
- function mkdirp2(volume, path, mode = 493) {
26693
- let current2 = "";
26694
- for (const part of segments(path)) {
26695
- current2 += `/${part}`;
26696
- try {
26697
- volume.mkdirSync(current2, { mode });
26698
- } catch (error) {
26699
- if (error.code !== "EEXIST") throw error;
26700
- if (!volume.lstatSync(current2).isDirectory()) throw error;
26701
- }
26702
- }
26703
- }
26704
- function safeTarget(destination, name) {
26705
- const clean2 = clean(`/${name}`).slice(1);
26706
- if (!clean2 || clean2 === ".." || clean2.startsWith("../") || name.startsWith("/")) throw new Error(`Unsafe path in package: ${name}`);
26707
- return join(destination, clean2);
26708
- }
26709
- function stripPackageRoot(name) {
26710
- const clean2 = name.replace(/^\.\//, "").replace(/\/$/, "");
26711
- const slash = clean2.indexOf("/");
26712
- return slash === -1 ? "" : clean2.slice(slash + 1);
26713
- }
26714
- function text(bytes2, start2, length) {
26715
- return new TextDecoder().decode(bytes2.subarray(start2, start2 + length)).replace(/\0.*$/, "").trim();
26716
- }
26717
- function octal(bytes2, start2, length) {
26718
- return parseInt(text(bytes2, start2, length).replace(/^0+/, "") || "0", 8);
26719
- }
26720
- function parsePax(data) {
26721
- const value = new TextDecoder().decode(data);
26722
- const result = {};
26723
- let offset = 0;
26724
- while (offset < value.length) {
26725
- const space = value.indexOf(" ", offset);
26726
- if (space < 0) break;
26727
- const length = Number(value.slice(offset, space));
26728
- if (!Number.isFinite(length) || length <= 0) break;
26729
- const record2 = value.slice(space + 1, offset + length - 1);
26730
- const equal2 = record2.indexOf("=");
26731
- if (equal2 > 0) result[record2.slice(0, equal2)] = record2.slice(equal2 + 1);
26732
- offset += length;
26733
- }
26734
- return result;
26735
- }
26736
- function unscoped(name) {
26737
- return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
26738
- }
26739
26919
  var DECLARES_EXPORTS = /(?:^|[\s;{)])(?:var|let|const|function|class)\s+exports\b/;
26740
26920
  var NAME = "exports";
26741
26921
  function renameShadowedExports(source) {
@@ -28448,8 +28628,8 @@ var VireoEngine = class _VireoEngine {
28448
28628
  const app = installedVireo(ctx);
28449
28629
  if (!app?.browserEngine) return null;
28450
28630
  const manifest = app.browserEngine;
28451
- const bytes2 = ctx.vfs.readFile(`${app.root}/${manifest.wasm}`, ctx.cred);
28452
- const loaded = await WebAssembly.instantiate(bytes2, {});
28631
+ const bytes3 = ctx.vfs.readFile(`${app.root}/${manifest.wasm}`, ctx.cred);
28632
+ const loaded = await WebAssembly.instantiate(bytes3, {});
28453
28633
  const instance = loaded instanceof WebAssembly.Instance ? loaded : loaded.instance;
28454
28634
  const wasm = instance.exports;
28455
28635
  for (const name of ["memory", "vireo_alloc", "vireo_load_html", "vireo_snapshot_pointer", "vireo_snapshot_length", "vireo_free_document"]) {
@@ -28473,11 +28653,11 @@ var VireoEngine = class _VireoEngine {
28473
28653
  this.wasm.vireo_free_document(handle);
28474
28654
  }
28475
28655
  }
28476
- copy(bytes2) {
28477
- if (!bytes2.length) return 0;
28478
- const pointer = this.wasm.vireo_alloc(bytes2.length);
28656
+ copy(bytes3) {
28657
+ if (!bytes3.length) return 0;
28658
+ const pointer = this.wasm.vireo_alloc(bytes3.length);
28479
28659
  if (!pointer) throw new Error("Vireo ran out of memory");
28480
- new Uint8Array(this.wasm.memory.buffer, pointer, bytes2.length).set(bytes2);
28660
+ new Uint8Array(this.wasm.memory.buffer, pointer, bytes3.length).set(bytes3);
28481
28661
  return pointer;
28482
28662
  }
28483
28663
  };
@@ -28663,8 +28843,8 @@ var SIGNATURE_PATH = "META/signature.json";
28663
28843
  var TRUSTED_KEYS_PATH = "/etc/pm/trusted-keys.json";
28664
28844
  var PackageError = class extends Error {
28665
28845
  };
28666
- async function openPackage(bytes2, trusted) {
28667
- const entries = readZip(bytes2);
28846
+ async function openPackage(bytes3, trusted) {
28847
+ const entries = readZip(bytes3);
28668
28848
  const byName = new Map(entries.map((entry) => [entry.name, entry]));
28669
28849
  const manifestEntry = byName.get(MANIFEST_PATH);
28670
28850
  if (!manifestEntry) {
@@ -28707,10 +28887,10 @@ async function openPackage(bytes2, trusted) {
28707
28887
  const trustedBy = trusted.find((key) => key.publicKey === signature.publicKey) ?? null;
28708
28888
  return { manifest, signature, entries, trustedBy };
28709
28889
  }
28710
- function parseManifest(bytes2) {
28890
+ function parseManifest(bytes3) {
28711
28891
  let parsed;
28712
28892
  try {
28713
- parsed = JSON.parse(new TextDecoder().decode(bytes2));
28893
+ parsed = JSON.parse(new TextDecoder().decode(bytes3));
28714
28894
  } catch (error) {
28715
28895
  throw new PackageError(`${MANIFEST_PATH} is not JSON: ${error.message}`);
28716
28896
  }
@@ -28726,10 +28906,10 @@ function parseManifest(bytes2) {
28726
28906
  }
28727
28907
  return manifest;
28728
28908
  }
28729
- function parseSignature(bytes2) {
28909
+ function parseSignature(bytes3) {
28730
28910
  let parsed;
28731
28911
  try {
28732
- parsed = JSON.parse(new TextDecoder().decode(bytes2));
28912
+ parsed = JSON.parse(new TextDecoder().decode(bytes3));
28733
28913
  } catch (error) {
28734
28914
  throw new PackageError(`${SIGNATURE_PATH} is not JSON: ${error.message}`);
28735
28915
  }
@@ -28777,16 +28957,16 @@ async function verifySignature(manifestBytes, signature) {
28777
28957
  intoBuffer(manifestBytes)
28778
28958
  );
28779
28959
  }
28780
- function intoBuffer(bytes2) {
28781
- return bytes2.slice().buffer;
28960
+ function intoBuffer(bytes3) {
28961
+ return bytes3.slice().buffer;
28782
28962
  }
28783
28963
  function base64ToBytes(text2) {
28784
28964
  const binary = atob(text2);
28785
- const bytes2 = new Uint8Array(binary.length);
28965
+ const bytes3 = new Uint8Array(binary.length);
28786
28966
  for (let index = 0; index < binary.length; index += 1) {
28787
- bytes2[index] = binary.charCodeAt(index);
28967
+ bytes3[index] = binary.charCodeAt(index);
28788
28968
  }
28789
- return bytes2;
28969
+ return bytes3;
28790
28970
  }
28791
28971
  async function fingerprint(publicKey) {
28792
28972
  const digest2 = await digestHex("sha256", base64ToBytes(publicKey));
@@ -29159,8 +29339,8 @@ function listInstalled2(ctx) {
29159
29339
  return 0;
29160
29340
  }
29161
29341
  for (const app of apps.slice().sort((a, b) => a.name.localeCompare(b.name))) {
29162
- const commands12 = app.installedBins.length > 0 ? ` (${app.installedBins.join(", ")})` : "";
29163
- ctx.line(`${app.name} ${app.version}${commands12}`);
29342
+ const commands13 = app.installedBins.length > 0 ? ` (${app.installedBins.join(", ")})` : "";
29343
+ ctx.line(`${app.name} ${app.version}${commands13}`);
29164
29344
  }
29165
29345
  return 0;
29166
29346
  }
@@ -29269,6 +29449,7 @@ function allCommands() {
29269
29449
  ...commands9,
29270
29450
  ...commands10,
29271
29451
  ...commands11,
29452
+ ...commands12,
29272
29453
  ...nodeCommands(),
29273
29454
  ...pythonCommands(),
29274
29455
  ...ffmpegCommands(),
@@ -29313,8 +29494,8 @@ var ContainerFs = class {
29313
29494
  return this.kernel.vfs;
29314
29495
  }
29315
29496
  async readFile(path, encoding) {
29316
- const bytes2 = this.vfs.readFile(clean(path));
29317
- return encoding ? new TextDecoder().decode(bytes2) : bytes2;
29497
+ const bytes3 = this.vfs.readFile(clean(path));
29498
+ return encoding ? new TextDecoder().decode(bytes3) : bytes3;
29318
29499
  }
29319
29500
  async writeFile(path, data, opts = {}) {
29320
29501
  const abs = clean(path);
@@ -29640,9 +29821,9 @@ var KernelChildProcess = class {
29640
29821
  this.exitCode = code;
29641
29822
  this.emit("exit", code);
29642
29823
  }
29643
- append(stream, text2) {
29824
+ append(stream, value, text2 = typeof value === "string" ? value : new TextDecoder().decode(value)) {
29644
29825
  this[stream] += text2;
29645
- this.emit(stream, text2);
29826
+ this.emit(stream, value);
29646
29827
  }
29647
29828
  };
29648
29829
  var ChildOutput = class {
@@ -29661,7 +29842,7 @@ var ChildOutput = class {
29661
29842
  write(data) {
29662
29843
  if (this.closedState) return;
29663
29844
  const text2 = typeof data === "string" ? data : this.decoder.decode(data, { stream: true });
29664
- if (text2) this.child.append(this.stream, text2);
29845
+ if (text2 || data instanceof Uint8Array) this.child.append(this.stream, data, text2);
29665
29846
  }
29666
29847
  end() {
29667
29848
  if (this.closedState) return;
@@ -30162,6 +30343,13 @@ var CommonJsEngine = class {
30162
30343
  }
30163
30344
  evaluate(module, source) {
30164
30345
  if (source.startsWith("#!")) source = source.replace(/^#![^\n]*(?:\n|$)/, "");
30346
+ if (isTypeScript(module.filename)) {
30347
+ source = transform(source, {
30348
+ transforms: module.filename.endsWith(".tsx") ? ["typescript", "jsx"] : ["typescript"],
30349
+ filePath: module.filename,
30350
+ production: true
30351
+ }).code;
30352
+ }
30165
30353
  const transformed = transformEsm(source, module.filename);
30166
30354
  const esmBody = transformed?.code ?? source;
30167
30355
  const body = transformAsyncContext(esmBody, module.filename) ?? esmBody;
@@ -30424,6 +30612,9 @@ Require stack:
30424
30612
  return error;
30425
30613
  }
30426
30614
  };
30615
+ function isTypeScript(filename) {
30616
+ return filename.endsWith(".ts") || filename.endsWith(".tsx");
30617
+ }
30427
30618
  var namespaces = /* @__PURE__ */ new WeakMap();
30428
30619
  function namespaceOf(exports) {
30429
30620
  if (exports === null || typeof exports !== "object" && typeof exports !== "function") {
@@ -31709,13 +31900,13 @@ var Z_NO_FLUSH = 0;
31709
31900
  var Z_SYNC_FLUSH = 2;
31710
31901
  var Z_FULL_FLUSH = 3;
31711
31902
  var Z_FINISH = 4;
31712
- var bytes = (data) => {
31903
+ var bytes2 = (data) => {
31713
31904
  if (typeof data === "string") return new Uint8Array(Buffer2.from(data, "utf8"));
31714
31905
  if (data instanceof ArrayBuffer) return new Uint8Array(data);
31715
31906
  return data;
31716
31907
  };
31717
31908
  function codec(run3) {
31718
- const sync2 = (data, options) => Buffer2.from(run3(bytes(data), options));
31909
+ const sync2 = (data, options) => Buffer2.from(run3(bytes2(data), options));
31719
31910
  const async_ = (data, options, callback) => {
31720
31911
  const done = typeof options === "function" ? options : callback;
31721
31912
  const settings = typeof options === "function" ? void 0 : options;
@@ -32065,6 +32256,8 @@ var VirtualServerResponse = class extends streamModule5.Writable {
32065
32256
  completed;
32066
32257
  constructor(request) {
32067
32258
  super();
32259
+ this.on("error", () => {
32260
+ });
32068
32261
  this.req = request;
32069
32262
  this.completed = new Promise((resolve3) => {
32070
32263
  this.resolve = resolve3;
@@ -32194,9 +32387,9 @@ var VirtualSocket = class extends streamModule5.Duplex {
32194
32387
  _read() {
32195
32388
  }
32196
32389
  _write(chunk, encoding, callback) {
32197
- const bytes2 = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk, encoding);
32390
+ const bytes3 = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk, encoding);
32198
32391
  try {
32199
- this.peer?.data(new Uint8Array(bytes2));
32392
+ this.peer?.data(new Uint8Array(bytes3));
32200
32393
  callback();
32201
32394
  } catch (error) {
32202
32395
  callback(error);
@@ -32220,9 +32413,9 @@ var VirtualSocket = class extends streamModule5.Duplex {
32220
32413
  this.peer = null;
32221
32414
  }
32222
32415
  /** Bytes arriving from the far end. */
32223
- deliver(bytes2) {
32416
+ deliver(bytes3) {
32224
32417
  if (this.destroyed || this.hungUp) return;
32225
- this.push(Buffer2.from(bytes2));
32418
+ this.push(Buffer2.from(bytes3));
32226
32419
  }
32227
32420
  /** The far end went away; let the server's stream end cleanly. */
32228
32421
  peerClosed() {
@@ -32377,7 +32570,7 @@ var VirtualHttpRouter = class {
32377
32570
  request.socket = socket;
32378
32571
  item.server.emit("upgrade", request, socket, Buffer2.alloc(0));
32379
32572
  return {
32380
- send: (bytes2) => socket.deliver(bytes2),
32573
+ send: (bytes3) => socket.deliver(bytes3),
32381
32574
  close: () => socket.peerClosed()
32382
32575
  };
32383
32576
  }
@@ -32603,9 +32796,9 @@ var VirtualClientRequest = class extends streamModule5.Writable {
32603
32796
  }
32604
32797
  const result = remote ?? await this.router.request(this.target.port, init);
32605
32798
  const body_ = result.body;
32606
- const bytes2 = typeof body_ === "string" ? new TextEncoder().encode(body_) : body_ instanceof ArrayBuffer ? new Uint8Array(body_) : body_ ?? new Uint8Array();
32799
+ const bytes3 = typeof body_ === "string" ? new TextEncoder().encode(body_) : body_ instanceof ArrayBuffer ? new Uint8Array(body_) : body_ ?? new Uint8Array();
32607
32800
  const status = result.statusCode ?? 200;
32608
- return new VirtualClientResponse(status, result.statusMessage ?? STATUS_CODES[status] ?? "", lowercaseHeaders(result.headers), bytes2);
32801
+ return new VirtualClientResponse(status, result.statusMessage ?? STATUS_CODES[status] ?? "", lowercaseHeaders(result.headers), bytes3);
32609
32802
  }
32610
32803
  async viaFetch(body) {
32611
32804
  const fetchImpl = this.fetchImpl ?? globalThis.fetch;
@@ -32629,8 +32822,8 @@ var VirtualClientRequest = class extends streamModule5.Writable {
32629
32822
  response.headers.forEach((value, key) => {
32630
32823
  received[key.toLowerCase()] = value;
32631
32824
  });
32632
- const bytes2 = new Uint8Array(await response.arrayBuffer());
32633
- return new VirtualClientResponse(response.status, response.statusText, received, bytes2);
32825
+ const bytes3 = new Uint8Array(await response.arrayBuffer());
32826
+ return new VirtualClientResponse(response.status, response.statusText, received, bytes3);
32634
32827
  }
32635
32828
  };
32636
32829
  function lowercaseHeaders(headers) {
@@ -32722,9 +32915,9 @@ function createVirtualFetch(router, options = {}) {
32722
32915
  for (const part of Array.isArray(value) ? value : [value]) responseHeaders.append(name, String(part));
32723
32916
  }
32724
32917
  const raw = result.body;
32725
- const bytes2 = typeof raw === "string" ? new TextEncoder().encode(raw) : raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw ?? new Uint8Array();
32918
+ const bytes3 = typeof raw === "string" ? new TextEncoder().encode(raw) : raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw ?? new Uint8Array();
32726
32919
  const nullBody = status === 204 || status === 205 || status === 304 || request.method === "HEAD";
32727
- return new Response(nullBody ? null : new Uint8Array(bytes2), {
32920
+ return new Response(nullBody ? null : new Uint8Array(bytes3), {
32728
32921
  status,
32729
32922
  statusText: result.statusMessage ?? STATUS_CODES[status] ?? "",
32730
32923
  headers: responseHeaders
@@ -32970,7 +33163,7 @@ function createTestModule(host2) {
32970
33163
  });
32971
33164
  };
32972
33165
  const hasOnly = (node2) => Boolean(node2.options.only) || node2.kind === "suite" && node2.children.some(hasOnly);
32973
- const report = (depth, outcome, name, started, detail) => {
33166
+ const report2 = (depth, outcome, name, started, detail) => {
32974
33167
  if (tap()) {
32975
33168
  tapIndex += 1;
32976
33169
  const ok2 = outcome === "fail" ? "not ok" : "ok";
@@ -33017,13 +33210,13 @@ ${indent(detail, 4)}
33017
33210
  if (runOnly && !options.only) return true;
33018
33211
  if (options.skip) {
33019
33212
  record2("skip", display);
33020
- report(depth, "skip", name, started);
33213
+ report2(depth, "skip", name, started);
33021
33214
  return true;
33022
33215
  }
33023
33216
  if (!fn) {
33024
33217
  const outcome = options.todo ? "todo" : "skip";
33025
33218
  record2(outcome, display);
33026
- report(depth, outcome, name, started);
33219
+ report2(depth, outcome, name, started);
33027
33220
  return true;
33028
33221
  }
33029
33222
  const controller = new AbortController();
@@ -33087,21 +33280,21 @@ ${indent(detail, 4)}
33087
33280
  }
33088
33281
  if (skipped) {
33089
33282
  record2("skip", display);
33090
- report(depth, "skip", name, started);
33283
+ report2(depth, "skip", name, started);
33091
33284
  return true;
33092
33285
  }
33093
33286
  if (error !== void 0) {
33094
33287
  if (todo) {
33095
33288
  record2("todo", display);
33096
- report(depth, "todo", name, started);
33289
+ report2(depth, "todo", name, started);
33097
33290
  return true;
33098
33291
  }
33099
33292
  record2("fail", display, error);
33100
- report(depth, "fail", name, started, errorText(error));
33293
+ report2(depth, "fail", name, started, errorText(error));
33101
33294
  return false;
33102
33295
  }
33103
33296
  record2(todo ? "todo" : "pass", display);
33104
- report(depth, todo ? "todo" : "pass", name, started);
33297
+ report2(depth, todo ? "todo" : "pass", name, started);
33105
33298
  return true;
33106
33299
  };
33107
33300
  const runSuite = async (suite, depth, runOnly) => {
@@ -33116,7 +33309,7 @@ ${indent(detail, 4)}
33116
33309
  `);
33117
33310
  if (suite.options.skip) {
33118
33311
  for (const child of suite.children) if (child.kind === "test") record2("skip", fullName(child));
33119
- report(depth, "skip", suite.name, started);
33312
+ report2(depth, "skip", suite.name, started);
33120
33313
  return true;
33121
33314
  }
33122
33315
  }
@@ -33128,10 +33321,10 @@ ${indent(detail, 4)}
33128
33321
  for (const child of suite.children) {
33129
33322
  if (child.kind === "test") {
33130
33323
  record2("cancelled", fullName(child), error);
33131
- report(depth + (isRoot ? 0 : 1), "cancelled", child.name, started, errorText(error));
33324
+ report2(depth + (isRoot ? 0 : 1), "cancelled", child.name, started, errorText(error));
33132
33325
  }
33133
33326
  }
33134
- if (!isRoot) report(depth, "fail", suite.name, started);
33327
+ if (!isRoot) report2(depth, "fail", suite.name, started);
33135
33328
  return false;
33136
33329
  }
33137
33330
  const only = runOnly || settings().only === true && suite.children.some(hasOnly);
@@ -33511,7 +33704,7 @@ var ChildProcess = class extends EventEmitter4 {
33511
33704
  this.stdin = new streamModule5.Writable({
33512
33705
  write: (chunk, _encoding, done) => {
33513
33706
  try {
33514
- handle.sendStdin(typeof chunk === "string" ? chunk : Buffer2.from(chunk).toString("utf8"));
33707
+ handle.sendStdin(typeof chunk === "string" ? chunk : new Uint8Array(chunk));
33515
33708
  } catch {
33516
33709
  }
33517
33710
  done();
@@ -33530,8 +33723,8 @@ var ChildProcess = class extends EventEmitter4 {
33530
33723
  const pipe = this.stdio[event.fd];
33531
33724
  pipe?.push(Buffer2.from(event.text));
33532
33725
  });
33533
- handle.on("stdout", (text2) => this.stdout.write(text2));
33534
- handle.on("stderr", (text2) => this.stderr.write(text2));
33726
+ handle.on("stdout", (value) => this.stdout.write(typeof value === "string" ? value : Buffer2.from(value)));
33727
+ handle.on("stderr", (value) => this.stderr.write(typeof value === "string" ? value : Buffer2.from(value)));
33535
33728
  handle.on("exit", (code) => this.finish(code));
33536
33729
  referenceChanged(1);
33537
33730
  try {
@@ -34518,7 +34711,7 @@ function createCoreModules(options) {
34518
34711
  });
34519
34712
  processObject.stdin = stdin;
34520
34713
  Reflect.deleteProperty(processObject, "browser");
34521
- const fs = createFsModule(volume, () => cwd, options.stdinPath, defer);
34714
+ const fs = createFsModule(volume, () => cwd, options.stdinPath, defer, stdin);
34522
34715
  processObject.loadEnvFile = (path2 = ".env") => {
34523
34716
  const parsed = parseEnv(fs.readFileSync(path2, "utf8"));
34524
34717
  for (const [key, value] of Object.entries(parsed)) {
@@ -34890,7 +35083,7 @@ function createPathModule(cwd) {
34890
35083
  path.default = path;
34891
35084
  return path;
34892
35085
  }
34893
- function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35086
+ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask, stdin) {
34894
35087
  const fds = /* @__PURE__ */ new Map();
34895
35088
  let nextFd = 3;
34896
35089
  if (stdinPath) fds.set(0, { path: stdinPath, position: 0, flags: "r" });
@@ -34901,7 +35094,7 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
34901
35094
  if (typeof value !== "string") throw new TypeError("path must be a string, Buffer, or URL");
34902
35095
  return value.startsWith("/") ? clean(value) : resolve(cwd(), value);
34903
35096
  };
34904
- const bytes2 = (data, encoding) => {
35097
+ const bytes3 = (data, encoding) => {
34905
35098
  if (typeof data === "string") return new Uint8Array(Buffer2.from(data, encoding));
34906
35099
  if (Buffer2.isBuffer(data) || data instanceof Uint8Array) return new Uint8Array(data);
34907
35100
  if (data instanceof ArrayBuffer) return new Uint8Array(data);
@@ -34963,12 +35156,12 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
34963
35156
  readFileSync: (path, options) => read(path, typeof options === "object" && options ? options.encoding : options),
34964
35157
  writeFileSync: (path, data, options) => {
34965
35158
  const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
34966
- volume.writeFileSync(abs(path), bytes2(data, encoding ?? void 0));
35159
+ volume.writeFileSync(abs(path), bytes3(data, encoding ?? void 0));
34967
35160
  if (typeof options === "object" && options?.mode !== void 0) volume.chmodSync(abs(path), options.mode);
34968
35161
  },
34969
35162
  appendFileSync: (path, data, options) => {
34970
35163
  const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
34971
- volume.appendFileSync(abs(path), bytes2(data, encoding ?? void 0));
35164
+ volume.appendFileSync(abs(path), bytes3(data, encoding ?? void 0));
34972
35165
  },
34973
35166
  existsSync: (path) => {
34974
35167
  try {
@@ -35059,7 +35252,7 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35059
35252
  offset = 0;
35060
35253
  length = data.length;
35061
35254
  }
35062
- const input = bytes2(data);
35255
+ const input = bytes3(data);
35063
35256
  const chunk = input.subarray(offset ?? 0, (offset ?? 0) + (length ?? input.length));
35064
35257
  const size = volume.lstatSync(file3.path).size;
35065
35258
  const append = file3.flags.startsWith("a") || (position ?? file3.position) >= size;
@@ -35184,9 +35377,9 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35184
35377
  const self = this;
35185
35378
  const append = () => {
35186
35379
  try {
35187
- const bytes3 = typeof chunk === "string" ? Buffer2.from(chunk, encoding) : chunk;
35188
- volume.appendFileSync(self.path, new Uint8Array(bytes3));
35189
- self.bytesWritten += bytes3.length;
35380
+ const bytes4 = typeof chunk === "string" ? Buffer2.from(chunk, encoding) : chunk;
35381
+ volume.appendFileSync(self.path, new Uint8Array(bytes4));
35382
+ self.bytesWritten += bytes4.length;
35190
35383
  done();
35191
35384
  } catch (error) {
35192
35385
  done(error);
@@ -35387,6 +35580,57 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35387
35580
  ({ offset, length, position } = options);
35388
35581
  }
35389
35582
  const start2 = offset ?? 0;
35583
+ if (fd === 0 && stdin) {
35584
+ const requested = length ?? buffer.byteLength - start2;
35585
+ const finish = (chunk) => {
35586
+ const source = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk);
35587
+ const count = Math.min(requested, source.byteLength);
35588
+ buffer.set(source.subarray(0, count), start2);
35589
+ if (count < source.byteLength && typeof stdin.unshift === "function") {
35590
+ stdin.unshift(source.subarray(count));
35591
+ }
35592
+ cb(null, count, buffer);
35593
+ };
35594
+ const available2 = stdin.read();
35595
+ if (available2 !== null) {
35596
+ defer(() => finish(available2));
35597
+ return;
35598
+ }
35599
+ if (stdin.readableEnded || stdin.destroyed) {
35600
+ defer(() => cb(null, 0, buffer));
35601
+ return;
35602
+ }
35603
+ let settled = false;
35604
+ const cleanup = () => {
35605
+ stdin.removeListener("readable", onReadable);
35606
+ stdin.removeListener("end", onEnd);
35607
+ stdin.removeListener("error", onError);
35608
+ };
35609
+ const onReadable = () => {
35610
+ if (settled) return;
35611
+ const chunk = stdin.read();
35612
+ if (chunk === null) return;
35613
+ settled = true;
35614
+ cleanup();
35615
+ finish(chunk);
35616
+ };
35617
+ const onEnd = () => {
35618
+ if (settled) return;
35619
+ settled = true;
35620
+ cleanup();
35621
+ cb(null, 0, buffer);
35622
+ };
35623
+ const onError = (error) => {
35624
+ if (settled) return;
35625
+ settled = true;
35626
+ cleanup();
35627
+ cb(error);
35628
+ };
35629
+ stdin.on("readable", onReadable);
35630
+ stdin.once("end", onEnd);
35631
+ stdin.once("error", onError);
35632
+ return;
35633
+ }
35390
35634
  runThenCall(() => [fs.readSync(fd, buffer, start2, length ?? buffer.byteLength - start2, position ?? null), buffer], cb);
35391
35635
  };
35392
35636
  fs.write = (fd, data, ...rest) => {
@@ -35478,8 +35722,8 @@ function createBufferBuiltin() {
35478
35722
  }
35479
35723
  },
35480
35724
  isAscii: (input) => {
35481
- const bytes2 = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
35482
- for (const byte of bytes2) if (byte > 127) return false;
35725
+ const bytes3 = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
35726
+ for (const byte of bytes3) if (byte > 127) return false;
35483
35727
  return true;
35484
35728
  }
35485
35729
  };
@@ -36118,37 +36362,37 @@ var MemoryVolume = class {
36118
36362
  writeFileSync(path, data) {
36119
36363
  const key = this.key(path);
36120
36364
  this.requireParent(key, "open");
36121
- const bytes2 = typeof data === "string" ? encoder7.encode(data) : data.slice();
36365
+ const bytes3 = typeof data === "string" ? encoder7.encode(data) : data.slice();
36122
36366
  const current2 = this.entries.get(key);
36123
36367
  if (current2?.kind === "directory") throw new VolumeError("EISDIR", "open", key);
36124
36368
  if (current2?.kind === "symlink") throw new VolumeError("EINVAL", "open", key);
36125
36369
  if (current2) {
36126
- current2.data = bytes2;
36370
+ current2.data = bytes3;
36127
36371
  this.touchChanged(current2, true);
36128
36372
  } else {
36129
- this.entries.set(key, this.inode("file", 438, bytes2));
36373
+ this.entries.set(key, this.inode("file", 438, bytes3));
36130
36374
  }
36131
36375
  }
36132
36376
  appendFileSync(path, data) {
36133
36377
  const key = this.key(path);
36134
- const bytes2 = typeof data === "string" ? encoder7.encode(data) : data;
36378
+ const bytes3 = typeof data === "string" ? encoder7.encode(data) : data;
36135
36379
  const current2 = this.entries.get(key);
36136
- if (!current2) return this.writeFileSync(key, bytes2);
36380
+ if (!current2) return this.writeFileSync(key, bytes3);
36137
36381
  if (current2.kind !== "file") throw new VolumeError(current2.kind === "directory" ? "EISDIR" : "EINVAL", "open", key);
36138
36382
  const length = current2.data.length;
36139
- const needed = length + bytes2.length;
36383
+ const needed = length + bytes3.length;
36140
36384
  const backing = current2.data.buffer;
36141
36385
  const ownsTail = current2.data.byteOffset === 0 && backing instanceof ArrayBuffer && backing.byteLength >= needed && appendCapacity.get(current2) === backing;
36142
36386
  if (ownsTail) {
36143
36387
  const grown = new Uint8Array(backing, 0, needed);
36144
- grown.set(bytes2, length);
36388
+ grown.set(bytes3, length);
36145
36389
  current2.data = grown;
36146
36390
  } else {
36147
36391
  const capacity = Math.max(needed, length * 2, 64 * 1024);
36148
36392
  const buffer = new ArrayBuffer(capacity);
36149
36393
  const grown = new Uint8Array(buffer, 0, needed);
36150
36394
  grown.set(current2.data);
36151
- grown.set(bytes2, length);
36395
+ grown.set(bytes3, length);
36152
36396
  current2.data = grown;
36153
36397
  appendCapacity.set(current2, buffer);
36154
36398
  }
@@ -36721,9 +36965,9 @@ var MirroringVolume = class {
36721
36965
  } catch {
36722
36966
  }
36723
36967
  try {
36724
- const bytes2 = mirror.readFileSync(source);
36968
+ const bytes3 = mirror.readFileSync(source);
36725
36969
  this.ensureDirectory(dirname(destination));
36726
- this.inner.writeFileSync(destination, bytes2);
36970
+ this.inner.writeFileSync(destination, bytes3);
36727
36971
  } catch {
36728
36972
  }
36729
36973
  };
@@ -37105,9 +37349,9 @@ var OutboundTcp = class {
37105
37349
  const bridge = new VirtualTcpConnection({ address, port }, { address: local.address, port: local.port });
37106
37350
  guest.pairWith(bridge);
37107
37351
  bridge.pairWith(guest);
37108
- host2.onData((bytes2) => {
37352
+ host2.onData((bytes3) => {
37109
37353
  try {
37110
- bridge.write(bytes2);
37354
+ bridge.write(bytes3);
37111
37355
  } catch {
37112
37356
  host2.close();
37113
37357
  }
@@ -37162,9 +37406,9 @@ function createNodeTcpDialer() {
37162
37406
  let onClose = null;
37163
37407
  let closed = false;
37164
37408
  socket.on("data", (chunk) => {
37165
- const bytes2 = new Uint8Array(chunk);
37166
- if (onData) onData(bytes2);
37167
- else pending.push(bytes2);
37409
+ const bytes3 = new Uint8Array(chunk);
37410
+ if (onData) onData(bytes3);
37411
+ else pending.push(bytes3);
37168
37412
  });
37169
37413
  const finish = () => {
37170
37414
  if (closed) return;
@@ -37183,8 +37427,8 @@ function createNodeTcpDialer() {
37183
37427
  socket.on("connect", () => {
37184
37428
  socket.setNoDelay(true);
37185
37429
  resolve3({
37186
- write(bytes2) {
37187
- socket.write(bytes2);
37430
+ write(bytes3) {
37431
+ socket.write(bytes3);
37188
37432
  },
37189
37433
  end() {
37190
37434
  socket.end();
@@ -37236,8 +37480,7 @@ function translate(error, host2, port) {
37236
37480
 
37237
37481
  // src/worker/local-runtime-pod.ts
37238
37482
  var WASM_ALIASES = {
37239
- esbuild: "esbuild-wasm",
37240
- rollup: "@rollup/wasm-node"
37483
+ ...RUNTIME_PACKAGE_FALLBACKS
37241
37484
  };
37242
37485
  var ProcessExit = class extends Error {
37243
37486
  constructor(code) {
@@ -37397,7 +37640,7 @@ var PodChildProcess = class {
37397
37640
  /* The child is launched asynchronously, but a parent may write and close
37398
37641
  * its input synchronously right after spawning. Holding both until the
37399
37642
  * child exists is what keeps `echo hi | child` from losing the `hi`. */
37400
- pendingInput = "";
37643
+ pendingInput = [];
37401
37644
  inputEnded = false;
37402
37645
  on(event, listener) {
37403
37646
  let set = this.listeners.get(event);
@@ -37421,15 +37664,13 @@ var PodChildProcess = class {
37421
37664
  (child) => {
37422
37665
  this.child = child;
37423
37666
  if (this.cancelled) child.kill();
37424
- if (this.pendingInput !== "") {
37425
- child.write(this.pendingInput);
37426
- this.pendingInput = "";
37427
- }
37667
+ for (const chunk of this.pendingInput.splice(0)) child.write(chunk);
37428
37668
  if (this.inputEnded) child.endInput?.();
37429
- child.on("output", (chunk) => {
37669
+ const outputEvent = child.rawOutput ? "raw-output" : "output";
37670
+ child.on(outputEvent, (chunk) => {
37430
37671
  const text2 = typeof chunk === "string" ? chunk : this.outText.decode(chunk, { stream: true });
37431
37672
  this.stdout += text2;
37432
- this.emit("stdout", text2);
37673
+ this.emit("stdout", chunk);
37433
37674
  });
37434
37675
  child.on("error", (chunk) => {
37435
37676
  const text2 = typeof chunk === "string" ? chunk : this.errText.decode(chunk, { stream: true });
@@ -37451,7 +37692,7 @@ var PodChildProcess = class {
37451
37692
  }
37452
37693
  sendStdin(data) {
37453
37694
  if (this.child) this.child.write(data);
37454
- else this.pendingInput += data;
37695
+ else this.pendingInput.push(data);
37455
37696
  }
37456
37697
  /** Signal EOF, so a child reading stdin to the end can finish. */
37457
37698
  endStdin() {
@@ -37811,14 +38052,14 @@ ${headers.join("\r\n")}\r
37811
38052
  `);
37812
38053
  connection.write(request);
37813
38054
  if (body.length) connection.write(body);
37814
- const bytes2 = [];
38055
+ const bytes3 = [];
37815
38056
  let combined = new Uint8Array();
37816
38057
  for (; ; ) {
37817
38058
  try {
37818
38059
  const chunk = connection.read(64 * 1024);
37819
38060
  if (chunk.length === 0) break;
37820
- bytes2.push(chunk);
37821
- combined = joinBytes(bytes2);
38061
+ bytes3.push(chunk);
38062
+ combined = joinBytes(bytes3);
37822
38063
  const headerEnd = findBytes(combined, new Uint8Array([13, 10, 13, 10]));
37823
38064
  if (headerEnd < 0) continue;
37824
38065
  const headerText = new TextDecoder().decode(combined.subarray(0, headerEnd));
@@ -37884,11 +38125,11 @@ function findBytes(haystack, needle) {
37884
38125
  }
37885
38126
  return -1;
37886
38127
  }
37887
- function parseHttpResponse(bytes2) {
38128
+ function parseHttpResponse(bytes3) {
37888
38129
  const marker = new Uint8Array([13, 10, 13, 10]);
37889
- const headerEnd = findBytes(bytes2, marker);
38130
+ const headerEnd = findBytes(bytes3, marker);
37890
38131
  if (headerEnd < 0) throw new Error("Python server returned an incomplete HTTP response");
37891
- const text2 = new TextDecoder().decode(bytes2.subarray(0, headerEnd));
38132
+ const text2 = new TextDecoder().decode(bytes3.subarray(0, headerEnd));
37892
38133
  const lines = text2.split("\r\n");
37893
38134
  const status = /HTTP\/\d\.\d\s+(\d+)(?:\s+(.*))?/.exec(lines.shift() ?? "");
37894
38135
  if (!status) throw new Error("Python server returned an invalid HTTP status line");
@@ -37897,7 +38138,7 @@ function parseHttpResponse(bytes2) {
37897
38138
  const separator = line.indexOf(":");
37898
38139
  if (separator > 0) headers[line.slice(0, separator).toLowerCase()] = line.slice(separator + 1).trim();
37899
38140
  }
37900
- let body = bytes2.slice(headerEnd + marker.length);
38141
+ let body = bytes3.slice(headerEnd + marker.length);
37901
38142
  if (CHUNKED.test(headers["transfer-encoding"] ?? "")) {
37902
38143
  body = decodeChunked(body).body;
37903
38144
  delete headers["transfer-encoding"];
@@ -37911,19 +38152,19 @@ function parseHttpResponse(bytes2) {
37911
38152
  };
37912
38153
  }
37913
38154
  var CHUNKED = /^(?:transfer-encoding:.*)?\bchunked\b/im;
37914
- function decodeChunked(bytes2) {
38155
+ function decodeChunked(bytes3) {
37915
38156
  const parts = [];
37916
38157
  const crlf = new Uint8Array([13, 10]);
37917
38158
  for (let at = 0; ; ) {
37918
- const lineEnd = findBytes(bytes2.subarray(at), crlf);
38159
+ const lineEnd = findBytes(bytes3.subarray(at), crlf);
37919
38160
  if (lineEnd < 0) return { body: joinBytes(parts), complete: false };
37920
- const header = new TextDecoder().decode(bytes2.subarray(at, at + lineEnd)).split(";")[0].trim();
38161
+ const header = new TextDecoder().decode(bytes3.subarray(at, at + lineEnd)).split(";")[0].trim();
37921
38162
  const size = /^[0-9a-f]+$/i.test(header) ? Number.parseInt(header, 16) : Number.NaN;
37922
38163
  if (!Number.isInteger(size)) throw new Error("Python server returned an invalid chunked response");
37923
38164
  at += lineEnd + crlf.length;
37924
38165
  if (size === 0) return { body: joinBytes(parts), complete: true };
37925
- if (at + size + crlf.length > bytes2.length) return { body: joinBytes(parts), complete: false };
37926
- parts.push(bytes2.subarray(at, at + size));
38166
+ if (at + size + crlf.length > bytes3.length) return { body: joinBytes(parts), complete: false };
38167
+ parts.push(bytes3.subarray(at, at + size));
37927
38168
  at += size + crlf.length;
37928
38169
  }
37929
38170
  }
@@ -38106,7 +38347,7 @@ var WorkerProcess = class extends EventEmitter4 {
38106
38347
  */
38107
38348
  write(data) {
38108
38349
  if (this.inheritedInput) {
38109
- this.inheritedInput.sendStdin(typeof data === "string" ? data : new TextDecoder().decode(data));
38350
+ this.inheritedInput.sendStdin(data);
38110
38351
  return;
38111
38352
  }
38112
38353
  if (this.started) this.worker.postMessage({ type: "stdin", data });
@@ -38270,7 +38511,9 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38270
38511
  this.startChild(worker, children, message, ownedChildren);
38271
38512
  return;
38272
38513
  case "child-stdin":
38273
- children.get(message.id)?.sendStdin?.(String(message.data));
38514
+ children.get(message.id)?.sendStdin?.(
38515
+ message.data instanceof Uint8Array ? message.data : String(message.data)
38516
+ );
38274
38517
  return;
38275
38518
  case "child-stdin-end":
38276
38519
  children.get(message.id)?.endStdin?.();
@@ -38312,20 +38555,22 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38312
38555
  return;
38313
38556
  }
38314
38557
  });
38315
- worker.postMessage({
38316
- type: "start",
38317
- buffers,
38318
- script,
38319
- cwd,
38320
- env: env2,
38321
- argv: Array.isArray(options.argv) ? options.argv : ["/usr/bin/node", script, ...args.slice(1)],
38322
- aliases: this.aliases,
38323
- ...typeof options.stdinPath === "string" ? { stdinPath: options.stdinPath } : {},
38324
- ...options.interactiveStdin ? { interactiveStdin: true } : {},
38325
- ...options.tty ? { tty: true } : {},
38326
- ...this.networkPolicy ? { network: this.networkPolicy } : {}
38327
- });
38328
- process2.begin();
38558
+ setTimeout(() => {
38559
+ worker.postMessage({
38560
+ type: "start",
38561
+ buffers,
38562
+ script,
38563
+ cwd,
38564
+ env: env2,
38565
+ argv: Array.isArray(options.argv) ? options.argv : ["/usr/bin/node", script, ...args.slice(1)],
38566
+ aliases: this.aliases,
38567
+ ...typeof options.stdinPath === "string" ? { stdinPath: options.stdinPath } : {},
38568
+ ...options.interactiveStdin ? { interactiveStdin: true } : {},
38569
+ ...options.tty ? { tty: true } : {},
38570
+ ...this.networkPolicy ? { network: this.networkPolicy } : {}
38571
+ });
38572
+ process2.begin();
38573
+ }, 0);
38329
38574
  return process2;
38330
38575
  }
38331
38576
  /** Start an asynchronous child on the host's behalf and relay its events. */
@@ -38363,16 +38608,20 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38363
38608
  handle.on("exit", () => owned.delete(handle));
38364
38609
  let stdout = "";
38365
38610
  let stderr = "";
38611
+ const stdoutDecoder = new TextDecoder();
38612
+ const stderrDecoder = new TextDecoder();
38366
38613
  const live = request.inheritStdio ? streamTo : null;
38367
38614
  const restoreInput = live?.inheritInput(handle);
38368
38615
  if (restoreInput) handle.on("exit", restoreInput);
38369
- handle.on("stdout", (text2) => {
38616
+ handle.on("stdout", (value) => {
38617
+ const text2 = typeof value === "string" ? value : stdoutDecoder.decode(value, { stream: true });
38370
38618
  stdout += text2;
38371
- live?.output(text2);
38619
+ live?.output(value);
38372
38620
  });
38373
- handle.on("stderr", (text2) => {
38621
+ handle.on("stderr", (value) => {
38622
+ const text2 = typeof value === "string" ? value : stderrDecoder.decode(value, { stream: true });
38374
38623
  stderr += text2;
38375
- live?.error(text2);
38624
+ live?.error(value);
38376
38625
  });
38377
38626
  handle.on("exit", (code) => resolve3({ status: code, stdout, stderr, signal: null }));
38378
38627
  handle.exec();
@@ -38443,8 +38692,8 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38443
38692
  const id = this.nextRequestId++;
38444
38693
  this.upgraded.set(id, socket);
38445
38694
  socket.on("data", (chunk) => {
38446
- const bytes2 = new Uint8Array(chunk);
38447
- worker.postMessage({ type: "ws-data", id, data: bytes2 });
38695
+ const bytes3 = new Uint8Array(chunk);
38696
+ worker.postMessage({ type: "ws-data", id, data: bytes3 });
38448
38697
  });
38449
38698
  const drop = () => {
38450
38699
  if (!this.upgraded.delete(id)) return;
@@ -38584,7 +38833,8 @@ var Container = class _Container {
38584
38833
  const network = {
38585
38834
  allowOutbound: opts.network?.allowOutbound ?? false,
38586
38835
  allowedHosts: opts.network?.allowedHosts ?? null,
38587
- ...opts.network?.proxy ? { proxy: opts.network.proxy } : {}
38836
+ ...opts.network?.proxy ? { proxy: opts.network.proxy } : {},
38837
+ ...opts.network?.secrets ? { secrets: opts.network.secrets } : {}
38588
38838
  };
38589
38839
  const podOptions = {
38590
38840
  workdir: opts.cwd ?? "/",
@@ -38900,17 +39150,17 @@ var Container = class _Container {
38900
39150
  body: init.body ?? null
38901
39151
  });
38902
39152
  const bodyRaw = res.body;
38903
- const bytes2 = bodyRaw instanceof Uint8Array ? bodyRaw : (
39153
+ const bytes3 = bodyRaw instanceof Uint8Array ? bodyRaw : (
38904
39154
  // The binary dispatcher answers with an ArrayBuffer.
38905
39155
  bodyRaw instanceof ArrayBuffer ? new Uint8Array(bodyRaw) : typeof bodyRaw === "string" ? new TextEncoder().encode(bodyRaw) : new Uint8Array(0)
38906
39156
  );
38907
- const body = typeof bodyRaw === "string" ? bodyRaw : new TextDecoder().decode(bytes2);
39157
+ const body = typeof bodyRaw === "string" ? bodyRaw : new TextDecoder().decode(bytes3);
38908
39158
  return {
38909
39159
  status: res.statusCode ?? 200,
38910
39160
  statusText: res.statusMessage ?? "",
38911
39161
  headers: res.headers ?? {},
38912
39162
  body,
38913
- bytes: bytes2,
39163
+ bytes: bytes3,
38914
39164
  json() {
38915
39165
  return JSON.parse(body);
38916
39166
  }
@@ -39543,7 +39793,7 @@ function serveContainerOn(port, box) {
39543
39793
  headers: request.headers,
39544
39794
  ...request.body ? { body: new Uint8Array(request.body) } : {}
39545
39795
  });
39546
- const bytes2 = response.bytes.slice();
39796
+ const bytes3 = response.bytes.slice();
39547
39797
  port.postMessage(
39548
39798
  {
39549
39799
  id: request.id,
@@ -39551,10 +39801,10 @@ function serveContainerOn(port, box) {
39551
39801
  status: response.status,
39552
39802
  statusText: response.statusText,
39553
39803
  headers: response.headers,
39554
- body: bytes2.buffer
39804
+ body: bytes3.buffer
39555
39805
  }
39556
39806
  },
39557
- [bytes2.buffer]
39807
+ [bytes3.buffer]
39558
39808
  );
39559
39809
  } catch (error) {
39560
39810
  const message = new TextEncoder().encode(error instanceof Error ? error.message : String(error));
@@ -39640,8 +39890,8 @@ async function createPreview(box, options = {}) {
39640
39890
  Number(data.port),
39641
39891
  { method: "GET", path: data.path ?? "/", headers: data.headers ?? {} },
39642
39892
  {
39643
- data: (bytes2) => {
39644
- const carrier = bytes2.slice().buffer;
39893
+ data: (bytes3) => {
39894
+ const carrier = bytes3.slice().buffer;
39645
39895
  reply({ type: WS_DATA, id, data: carrier }, [carrier]);
39646
39896
  },
39647
39897
  close: () => {
@@ -39723,8 +39973,8 @@ function gitFilesystem(ctx) {
39723
39973
  const encoding = (opts) => typeof opts === "string" ? opts : opts?.encoding;
39724
39974
  return { promises: {
39725
39975
  async readFile(path, opts) {
39726
- const bytes2 = Buffer2.from(ctx.vfs.readFile(ctx.path(path), ctx.cred));
39727
- return encoding(opts) ? bytes2.toString(encoding(opts)) : bytes2;
39976
+ const bytes3 = Buffer2.from(ctx.vfs.readFile(ctx.path(path), ctx.cred));
39977
+ return encoding(opts) ? bytes3.toString(encoding(opts)) : bytes3;
39728
39978
  },
39729
39979
  async writeFile(path, data, opts) {
39730
39980
  ctx.vfs.writeFile(ctx.path(path), data, { cred: ctx.cred, mode: opts?.mode });
@@ -39916,8 +40166,8 @@ var signed = (value) => {
39916
40166
  }
39917
40167
  };
39918
40168
  var str = (s) => {
39919
- const bytes2 = [...new TextEncoder().encode(s)];
39920
- return [...leb(bytes2.length), ...bytes2];
40169
+ const bytes3 = [...new TextEncoder().encode(s)];
40170
+ return [...leb(bytes3.length), ...bytes3];
39921
40171
  };
39922
40172
  var section = (id, data) => [id, ...leb(data.length), ...data];
39923
40173
  function compileInstruction({ op, next }) {