sandboxedjs 0.2.22 → 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.cjs CHANGED
@@ -4,13 +4,13 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var pako = require('pako');
6
6
  var sha256 = require('@noble/hashes/sha256');
7
- var acorn = require('acorn');
8
- var jsx = require('acorn-jsx');
9
- var sucrase = require('sucrase');
10
7
  var index_js = require('buffer/index.js');
11
8
  var sha512 = require('@noble/hashes/sha512');
12
9
  var sha1 = require('@noble/hashes/sha1');
13
10
  var semver = require('semver');
11
+ var acorn = require('acorn');
12
+ var jsx = require('acorn-jsx');
13
+ var sucrase = require('sucrase');
14
14
  var EventEmitter4 = require('events/events.js');
15
15
  var resolve_exports = require('resolve.exports');
16
16
  var pathModule = require('path-browserify');
@@ -4147,9 +4147,9 @@ async function randomUuid() {
4147
4147
  const { randomUUID } = await nodeCrypto();
4148
4148
  return randomUUID();
4149
4149
  }
4150
- function toHex(bytes2) {
4150
+ function toHex(bytes3) {
4151
4151
  let out = "";
4152
- for (const byte of bytes2) out += byte.toString(16).padStart(2, "0");
4152
+ for (const byte of bytes3) out += byte.toString(16).padStart(2, "0");
4153
4153
  return out;
4154
4154
  }
4155
4155
  function md5Hex(input) {
@@ -4887,12 +4887,12 @@ var Vfs = class {
4887
4887
  writeFile(abs, data, opts = {}) {
4888
4888
  const cred = opts.privileged ? void 0 : opts.cred;
4889
4889
  const real = this.resolvePath(abs, { cred });
4890
- const bytes2 = typeof data === "string" ? encoder.encode(data) : data;
4890
+ const bytes3 = typeof data === "string" ? encoder.encode(data) : data;
4891
4891
  const virt = this.lookupVirtual(real);
4892
4892
  if (virt) {
4893
4893
  if (!virt.write) throw new exports.SysError("EACCES", "write", real);
4894
4894
  this.require(this.statFromVirtual(real, virt), W_OK, cred, "open", real);
4895
- virt.write(bytes2, opts.append ?? false);
4895
+ virt.write(bytes3, opts.append ?? false);
4896
4896
  return;
4897
4897
  }
4898
4898
  if (this.isUnderProvider(real)) throw new exports.SysError("ENOENT", "open", real);
@@ -4907,8 +4907,8 @@ var Vfs = class {
4907
4907
  this.require(pst, W_OK | X_OK, cred, "open", real);
4908
4908
  }
4909
4909
  try {
4910
- if (opts.append && existing) this.volume.appendFileSync(real, bytes2);
4911
- else this.volume.writeFileSync(real, bytes2);
4910
+ if (opts.append && existing) this.volume.appendFileSync(real, bytes3);
4911
+ else this.volume.writeFileSync(real, bytes3);
4912
4912
  } catch (e) {
4913
4913
  throw toSysError(e, "open", real);
4914
4914
  }
@@ -5160,7 +5160,7 @@ var Vfs = class {
5160
5160
  usage(abs = "/") {
5161
5161
  let files = 0;
5162
5162
  let dirs = 0;
5163
- let bytes2 = 0;
5163
+ let bytes3 = 0;
5164
5164
  for (const p of this.walk(abs)) {
5165
5165
  let st = null;
5166
5166
  try {
@@ -5171,10 +5171,10 @@ var Vfs = class {
5171
5171
  if (st.isDirectory()) dirs++;
5172
5172
  else {
5173
5173
  files++;
5174
- bytes2 += st.size;
5174
+ bytes3 += st.size;
5175
5175
  }
5176
5176
  }
5177
- return { files, dirs, bytes: bytes2 };
5177
+ return { files, dirs, bytes: bytes3 };
5178
5178
  }
5179
5179
  };
5180
5180
 
@@ -5258,10 +5258,10 @@ var Pipe = class _Pipe {
5258
5258
  write(data) {
5259
5259
  if (this.readerClosed) throw new exports.SysError("EPIPE", "write");
5260
5260
  if (this.writerClosed) return;
5261
- const bytes2 = this.icrnl && !this.raw ? translateCarriageReturns(toBytes(data)) : toBytes(data);
5262
- if (bytes2.length === 0) return;
5263
- this.chunks.push(bytes2);
5264
- this.buffered += bytes2.length;
5261
+ const bytes3 = this.icrnl && !this.raw ? translateCarriageReturns(toBytes(data)) : toBytes(data);
5262
+ if (bytes3.length === 0) return;
5263
+ this.chunks.push(bytes3);
5264
+ this.buffered += bytes3.length;
5265
5265
  this.wake();
5266
5266
  }
5267
5267
  end() {
@@ -5351,15 +5351,15 @@ var Pipe = class _Pipe {
5351
5351
  return p;
5352
5352
  }
5353
5353
  };
5354
- function translateCarriageReturns(bytes2) {
5355
- if (!bytes2.includes(CR)) return bytes2;
5356
- const out = new Uint8Array(bytes2.length);
5354
+ function translateCarriageReturns(bytes3) {
5355
+ if (!bytes3.includes(CR)) return bytes3;
5356
+ const out = new Uint8Array(bytes3.length);
5357
5357
  let length = 0;
5358
- for (let index = 0; index < bytes2.length; index += 1) {
5359
- const byte = bytes2[index];
5358
+ for (let index = 0; index < bytes3.length; index += 1) {
5359
+ const byte = bytes3[index];
5360
5360
  if (byte === CR) {
5361
5361
  out[length++] = LF;
5362
- if (bytes2[index + 1] === LF) index += 1;
5362
+ if (bytes3[index + 1] === LF) index += 1;
5363
5363
  } else {
5364
5364
  out[length++] = byte;
5365
5365
  }
@@ -5405,11 +5405,11 @@ var BufferSink = class {
5405
5405
  }
5406
5406
  write(data) {
5407
5407
  if (this._closed) return;
5408
- const bytes2 = toBytes(data);
5409
- if (bytes2.length === 0) return;
5410
- this.chunks.push(bytes2);
5411
- this.total += bytes2.length;
5412
- this.onWrite?.(bytes2);
5408
+ const bytes3 = toBytes(data);
5409
+ if (bytes3.length === 0) return;
5410
+ this.chunks.push(bytes3);
5411
+ this.total += bytes3.length;
5412
+ this.onWrite?.(bytes3);
5413
5413
  }
5414
5414
  end() {
5415
5415
  this._closed = true;
@@ -6298,8 +6298,8 @@ var SIZEOF_FDSTAT = 24;
6298
6298
  var SIZEOF_DIRENT = 24;
6299
6299
  var SIZEOF_SUBSCRIPTION = 48;
6300
6300
  var SIZEOF_EVENT = 32;
6301
- function isWasmBinary(bytes2) {
6302
- return bytes2.length >= 4 && bytes2[0] === 0 && bytes2[1] === 97 && bytes2[2] === 115 && bytes2[3] === 109;
6301
+ function isWasmBinary(bytes3) {
6302
+ return bytes3.length >= 4 && bytes3[0] === 0 && bytes3[1] === 97 && bytes3[2] === 115 && bytes3[3] === 109;
6303
6303
  }
6304
6304
 
6305
6305
  // src/wasi/host.ts
@@ -7089,8 +7089,8 @@ function defaultSleep(milliseconds) {
7089
7089
  // src/wasi/run.ts
7090
7090
  var compiled = /* @__PURE__ */ new Map();
7091
7091
  var MAX_CACHED_MODULES = 32;
7092
- async function runWasi(ctx, bytes2, options = {}) {
7093
- if (!isWasmBinary(bytes2)) {
7092
+ async function runWasi(ctx, bytes3, options = {}) {
7093
+ if (!isWasmBinary(bytes3)) {
7094
7094
  ctx.warn("cannot execute binary file: not a WebAssembly module");
7095
7095
  return EXIT_NOT_EXECUTABLE;
7096
7096
  }
@@ -7114,7 +7114,7 @@ async function runWasi(ctx, bytes2, options = {}) {
7114
7114
  });
7115
7115
  let instance;
7116
7116
  try {
7117
- const module = await compile(bytes2);
7117
+ const module = await compile(bytes3);
7118
7118
  instance = await WebAssembly.instantiate(module, {
7119
7119
  ...options.imports,
7120
7120
  wasi_snapshot_preview1: host2.wasiImport,
@@ -7150,15 +7150,15 @@ async function runWasi(ctx, bytes2, options = {}) {
7150
7150
  }
7151
7151
  }
7152
7152
  }
7153
- async function compile(bytes2) {
7154
- const key = await digest(bytes2);
7153
+ async function compile(bytes3) {
7154
+ const key = await digest(bytes3);
7155
7155
  const hit = compiled.get(key);
7156
7156
  if (hit) {
7157
7157
  compiled.delete(key);
7158
7158
  compiled.set(key, hit);
7159
7159
  return hit;
7160
7160
  }
7161
- const module = await WebAssembly.compile(sliceForWasm(bytes2));
7161
+ const module = await WebAssembly.compile(sliceForWasm(bytes3));
7162
7162
  compiled.set(key, module);
7163
7163
  if (compiled.size > MAX_CACHED_MODULES) {
7164
7164
  const oldest = compiled.keys().next().value;
@@ -7166,12 +7166,12 @@ async function compile(bytes2) {
7166
7166
  }
7167
7167
  return module;
7168
7168
  }
7169
- async function digest(bytes2) {
7170
- const hash = await crypto.subtle.digest("SHA-256", sliceForWasm(bytes2));
7169
+ async function digest(bytes3) {
7170
+ const hash = await crypto.subtle.digest("SHA-256", sliceForWasm(bytes3));
7171
7171
  return Array.from(new Uint8Array(hash, 0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
7172
7172
  }
7173
- function sliceForWasm(bytes2) {
7174
- return bytes2.buffer.slice(bytes2.byteOffset, bytes2.byteOffset + bytes2.byteLength);
7173
+ function sliceForWasm(bytes3) {
7174
+ return bytes3.buffer.slice(bytes3.byteOffset, bytes3.byteOffset + bytes3.byteLength);
7175
7175
  }
7176
7176
  async function primeStdin(ctx) {
7177
7177
  let pending = new Uint8Array(0);
@@ -7203,19 +7203,19 @@ function describeStartupFailure(error) {
7203
7203
  }
7204
7204
 
7205
7205
  // src/compat/execution.ts
7206
- function binaryDigest(bytes2) {
7207
- return Array.from(sha256.sha256(bytes2), (b) => b.toString(16).padStart(2, "0")).join("");
7206
+ function binaryDigest(bytes3) {
7207
+ return Array.from(sha256.sha256(bytes3), (b) => b.toString(16).padStart(2, "0")).join("");
7208
7208
  }
7209
- function isElfBinary(bytes2) {
7210
- return bytes2[0] === 127 && bytes2[1] === 69 && bytes2[2] === 76 && bytes2[3] === 70;
7209
+ function isElfBinary(bytes3) {
7210
+ return bytes3[0] === 127 && bytes3[1] === 69 && bytes3[2] === 76 && bytes3[3] === 70;
7211
7211
  }
7212
- function inspectElf(bytes2) {
7213
- 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");
7214
- const littleEndian = bytes2[5] === 1;
7215
- const machine = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength).getUint16(18, littleEndian);
7212
+ function inspectElf(bytes3) {
7213
+ 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");
7214
+ const littleEndian = bytes3[5] === 1;
7215
+ const machine = new DataView(bytes3.buffer, bytes3.byteOffset, bytes3.byteLength).getUint16(18, littleEndian);
7216
7216
  return {
7217
7217
  format: "elf",
7218
- bits: bytes2[4] === 2 ? 64 : 32,
7218
+ bits: bytes3[4] === 2 ? 64 : 32,
7219
7219
  machine,
7220
7220
  littleEndian,
7221
7221
  architecture: { 3: "x86", 62: "x86_64", 40: "arm", 183: "aarch64", 243: "riscv" }[machine] ?? `machine-${machine}`
@@ -7242,14 +7242,14 @@ var BinaryExecutionRegistry = class {
7242
7242
  return this.backends.map(({ id, tier }) => ({ id, tier }));
7243
7243
  }
7244
7244
  async run(ctx, path) {
7245
- const bytes2 = ctx.vfs.readFile(path, ctx.cred);
7245
+ const bytes3 = ctx.vfs.readFile(path, ctx.cred);
7246
7246
  let info2;
7247
7247
  try {
7248
- info2 = inspectElf(bytes2);
7248
+ info2 = inspectElf(bytes3);
7249
7249
  } catch (error) {
7250
7250
  return ctx.fail(String(error), 126);
7251
7251
  }
7252
- const request = { path, bytes: bytes2, info: info2, sha256: binaryDigest(bytes2) };
7252
+ const request = { path, bytes: bytes3, info: info2, sha256: binaryDigest(bytes3) };
7253
7253
  const reasons = [];
7254
7254
  const backends = [...this.backends];
7255
7255
  for (const tier of ["compatibility", "translation", "emulation"]) {
@@ -7272,10 +7272,10 @@ var BinaryExecutionRegistry = class {
7272
7272
  }
7273
7273
  };
7274
7274
  function checkedWasm(artifact) {
7275
- const bytes2 = artifact.bytes.slice();
7276
- if (!/^[a-f0-9]{64}$/i.test(artifact.sha256) || binaryDigest(bytes2) !== artifact.sha256.toLowerCase()) throw new Error("Wasm artifact integrity mismatch");
7277
- if (!WebAssembly.validate(bytes2)) throw new Error("invalid WebAssembly artifact");
7278
- return bytes2;
7275
+ const bytes3 = artifact.bytes.slice();
7276
+ if (!/^[a-f0-9]{64}$/i.test(artifact.sha256) || binaryDigest(bytes3) !== artifact.sha256.toLowerCase()) throw new Error("Wasm artifact integrity mismatch");
7277
+ if (!WebAssembly.validate(bytes3)) throw new Error("invalid WebAssembly artifact");
7278
+ return bytes3;
7279
7279
  }
7280
7280
  function installWasmCommands(kernel, artifacts) {
7281
7281
  const names = /* @__PURE__ */ new Set();
@@ -7284,7 +7284,7 @@ function installWasmCommands(kernel, artifacts) {
7284
7284
  names.add(artifact.name);
7285
7285
  return { name: artifact.name, bytes: checkedWasm(artifact) };
7286
7286
  });
7287
- for (const { name, bytes: bytes2 } of checked) kernel.installCommand({ name, run: (ctx) => runWasi(ctx, bytes2) });
7287
+ for (const { name, bytes: bytes3 } of checked) kernel.installCommand({ name, run: (ctx) => runWasi(ctx, bytes3) });
7288
7288
  }
7289
7289
  function createWasmCompatibilityBackend(id, entries) {
7290
7290
  const ports = new Map(entries.map((entry) => {
@@ -7292,8 +7292,8 @@ function createWasmCompatibilityBackend(id, entries) {
7292
7292
  return [entry.elfSha256.toLowerCase(), checkedWasm(entry.wasm)];
7293
7293
  }));
7294
7294
  return { id, tier: "compatibility", prepare(request) {
7295
- const bytes2 = ports.get(request.sha256);
7296
- return bytes2 ? { supported: true, program: { run: (ctx) => runWasi(ctx, bytes2, { argv: [request.path, ...ctx.args] }) } } : { supported: false, reason: "no port for this binary digest" };
7295
+ const bytes3 = ports.get(request.sha256);
7296
+ return bytes3 ? { supported: true, program: { run: (ctx) => runWasi(ctx, bytes3, { argv: [request.path, ...ctx.args] }) } } : { supported: false, reason: "no port for this binary digest" };
7297
7297
  } };
7298
7298
  }
7299
7299
  function createTranslationBackend(translator, maxCacheBytes = 32 * 1024 * 1024) {
@@ -7302,32 +7302,32 @@ function createTranslationBackend(translator, maxCacheBytes = 32 * 1024 * 1024)
7302
7302
  let size = 0;
7303
7303
  return { id: translator.id, tier: "translation", async prepare(request, signal) {
7304
7304
  if (!translator.supports(request.info)) return { supported: false, reason: "unsupported ELF architecture" };
7305
- let bytes2 = cache.get(request.sha256);
7306
- if (bytes2) {
7305
+ let bytes3 = cache.get(request.sha256);
7306
+ if (bytes3) {
7307
7307
  cache.delete(request.sha256);
7308
- cache.set(request.sha256, bytes2);
7308
+ cache.set(request.sha256, bytes3);
7309
7309
  } else {
7310
7310
  const output = await translator.translate(request, signal);
7311
7311
  if (signal.aborted) return { supported: false, reason: "cancelled" };
7312
7312
  if (!output) return { supported: false, reason: "translator declined this program" };
7313
- bytes2 = output.slice();
7314
- if (!WebAssembly.validate(bytes2.slice())) throw new Error(`${translator.id}: invalid translator output`);
7315
- if (bytes2.byteLength <= maxCacheBytes) {
7313
+ bytes3 = output.slice();
7314
+ if (!WebAssembly.validate(bytes3.slice())) throw new Error(`${translator.id}: invalid translator output`);
7315
+ if (bytes3.byteLength <= maxCacheBytes) {
7316
7316
  const previous = cache.get(request.sha256);
7317
7317
  if (previous) {
7318
7318
  size -= previous.byteLength;
7319
7319
  cache.delete(request.sha256);
7320
7320
  }
7321
- while (size + bytes2.byteLength > maxCacheBytes && cache.size) {
7321
+ while (size + bytes3.byteLength > maxCacheBytes && cache.size) {
7322
7322
  const key = cache.keys().next().value;
7323
7323
  size -= cache.get(key).byteLength;
7324
7324
  cache.delete(key);
7325
7325
  }
7326
- cache.set(request.sha256, bytes2);
7327
- size += bytes2.byteLength;
7326
+ cache.set(request.sha256, bytes3);
7327
+ size += bytes3.byteLength;
7328
7328
  }
7329
7329
  }
7330
- const artifact = bytes2;
7330
+ const artifact = bytes3;
7331
7331
  return { supported: true, program: { run: (ctx) => runWasi(ctx, artifact, { argv: [request.path, ...ctx.args] }) } };
7332
7332
  } };
7333
7333
  }
@@ -8376,18 +8376,18 @@ function createSysProvider(kernel) {
8376
8376
  }
8377
8377
 
8378
8378
  // src/net/proxy-fetch.ts
8379
- function toBase64(bytes2) {
8379
+ function toBase64(bytes3) {
8380
8380
  let text2 = "";
8381
- for (let at = 0; at < bytes2.length; at += 32768) {
8382
- text2 += String.fromCharCode(...bytes2.subarray(at, at + 32768));
8381
+ for (let at = 0; at < bytes3.length; at += 32768) {
8382
+ text2 += String.fromCharCode(...bytes3.subarray(at, at + 32768));
8383
8383
  }
8384
8384
  return btoa(text2);
8385
8385
  }
8386
8386
  function fromBase64(text2) {
8387
8387
  const binary = atob(text2);
8388
- const bytes2 = new Uint8Array(binary.length);
8389
- for (let at = 0; at < binary.length; at += 1) bytes2[at] = binary.charCodeAt(at);
8390
- return bytes2;
8388
+ const bytes3 = new Uint8Array(binary.length);
8389
+ for (let at = 0; at < binary.length; at += 1) bytes3[at] = binary.charCodeAt(at);
8390
+ return bytes3;
8391
8391
  }
8392
8392
  async function proxyExchange(proxy, request, fetchImpl = fetch) {
8393
8393
  let answer;
@@ -8474,6 +8474,93 @@ async function discoverEgress(fetchImpl = fetch) {
8474
8474
  return await found;
8475
8475
  }
8476
8476
 
8477
+ // src/net/secrets.ts
8478
+ var PLACEHOLDER = /\{\{secret:([A-Za-z_][A-Za-z0-9_]*)\}\}/g;
8479
+ var REDACTED = "[sealed]";
8480
+ var SecretRefused = class extends Error {
8481
+ code = "EACCES";
8482
+ };
8483
+ function hostBound(secret, hostname) {
8484
+ return secret.hosts.some((host2) => hostname === host2 || hostname.endsWith(`.${host2}`));
8485
+ }
8486
+ function mentionsSecret(text2) {
8487
+ PLACEHOLDER.lastIndex = 0;
8488
+ return PLACEHOLDER.test(text2);
8489
+ }
8490
+ function substituteSecrets(text2, hostname, secrets) {
8491
+ return text2.replace(PLACEHOLDER, (_match, name) => {
8492
+ const secret = Object.prototype.hasOwnProperty.call(secrets, name) ? secrets[name] : void 0;
8493
+ if (!secret) {
8494
+ throw new SecretRefused(`no sealed secret named ${name} is configured for this container`);
8495
+ }
8496
+ if (!hostBound(secret, hostname)) {
8497
+ throw new SecretRefused(
8498
+ `the sealed secret ${name} is not bound to ${hostname}; it may only be sent to ${secret.hosts.join(", ") || "no host"}`
8499
+ );
8500
+ }
8501
+ return secret.value;
8502
+ });
8503
+ }
8504
+ function sealRequest(request, secrets) {
8505
+ const url = new URL(request.url);
8506
+ if (mentionsSecret(decodeURIComponent(url.href))) {
8507
+ throw new SecretRefused("a sealed secret can only be used in a request header, not in the URL");
8508
+ }
8509
+ const used = [];
8510
+ let headers = null;
8511
+ request.headers.forEach((value, name) => {
8512
+ if (!mentionsSecret(value)) return;
8513
+ headers ??= new Headers(request.headers);
8514
+ headers.set(name, substituteSecrets(value, url.hostname, secrets));
8515
+ PLACEHOLDER.lastIndex = 0;
8516
+ for (const match2 of value.matchAll(PLACEHOLDER)) used.push(match2[1]);
8517
+ });
8518
+ return headers ? { request: new Request(request, { headers }), used } : { request, used };
8519
+ }
8520
+ function redactResponse(response, secrets) {
8521
+ const values = Object.values(secrets).map((secret) => secret.value).filter((value) => value.length > 0);
8522
+ if (values.length === 0) return response;
8523
+ const headers = new Headers();
8524
+ response.headers.forEach((value, name) => headers.set(name, redactText(value, values)));
8525
+ const init = { status: response.status, statusText: response.statusText, headers };
8526
+ if (!response.body) return new Response(null, init);
8527
+ headers.delete("content-length");
8528
+ return new Response(response.body.pipeThrough(redactingStream(values)), init);
8529
+ }
8530
+ function redactText(text2, values) {
8531
+ let out = text2;
8532
+ for (const value of values) out = out.split(value).join(REDACTED);
8533
+ return out;
8534
+ }
8535
+ function redactingStream(values) {
8536
+ const needles = values.map((value) => latin1(new TextEncoder().encode(value)));
8537
+ const hold = Math.max(...needles.map((needle) => needle.length)) - 1;
8538
+ let pending = "";
8539
+ return new TransformStream({
8540
+ transform(chunk, controller) {
8541
+ pending = redactText(pending + latin1(chunk), needles);
8542
+ if (pending.length <= hold) return;
8543
+ controller.enqueue(bytes(pending.slice(0, pending.length - hold)));
8544
+ pending = pending.slice(pending.length - hold);
8545
+ },
8546
+ flush(controller) {
8547
+ if (pending) controller.enqueue(bytes(redactText(pending, needles)));
8548
+ }
8549
+ });
8550
+ }
8551
+ function latin1(chunk) {
8552
+ let out = "";
8553
+ for (let at = 0; at < chunk.length; at += 32768) {
8554
+ out += String.fromCharCode(...chunk.subarray(at, at + 32768));
8555
+ }
8556
+ return out;
8557
+ }
8558
+ function bytes(text2) {
8559
+ const out = new Uint8Array(text2.length);
8560
+ for (let index = 0; index < text2.length; index += 1) out[index] = text2.charCodeAt(index);
8561
+ return out;
8562
+ }
8563
+
8477
8564
  // src/net/policy.ts
8478
8565
  function isLoopbackHostname(hostname) {
8479
8566
  const host2 = hostname.replace(/^\[|\]$/g, "").toLowerCase();
@@ -8511,6 +8598,24 @@ function requestUrl(input) {
8511
8598
  return input.url;
8512
8599
  }
8513
8600
  function policedFetch(policy, fetchImpl) {
8601
+ const secrets = policy.secrets && Object.keys(policy.secrets).length > 0 ? policy.secrets : null;
8602
+ if (!secrets) return policedPlainFetch(policy, fetchImpl);
8603
+ const plain = policedPlainFetch(policy, fetchImpl);
8604
+ return (async (input, init) => {
8605
+ const url = requestUrl(input);
8606
+ if (!outboundAllowed(policy, url)) {
8607
+ throw Object.assign(new TypeError("fetch failed"), { cause: outboundBlockedError(url) });
8608
+ }
8609
+ let sealed;
8610
+ try {
8611
+ sealed = sealRequest(new Request(input, init), secrets).request;
8612
+ } catch (error) {
8613
+ throw Object.assign(new TypeError("fetch failed"), { cause: error });
8614
+ }
8615
+ return redactResponse(await plain(sealed), secrets);
8616
+ });
8617
+ }
8618
+ function policedPlainFetch(policy, fetchImpl) {
8514
8619
  return (async (input, init) => {
8515
8620
  const url = requestUrl(input);
8516
8621
  if (!outboundAllowed(policy, url)) {
@@ -8747,22 +8852,22 @@ var NetworkStack = class {
8747
8852
  `;
8748
8853
  return out;
8749
8854
  }
8750
- countTx(bytes2, iface = "eth0") {
8855
+ countTx(bytes3, iface = "eth0") {
8751
8856
  const i = this.interface(iface);
8752
8857
  if (!i) return;
8753
- i.txBytes += bytes2;
8754
- i.txPackets += Math.max(1, Math.ceil(bytes2 / 1400));
8858
+ i.txBytes += bytes3;
8859
+ i.txPackets += Math.max(1, Math.ceil(bytes3 / 1400));
8755
8860
  }
8756
- countRx(bytes2, iface = "eth0") {
8861
+ countRx(bytes3, iface = "eth0") {
8757
8862
  const i = this.interface(iface);
8758
8863
  if (!i) return;
8759
- i.rxBytes += bytes2;
8760
- i.rxPackets += Math.max(1, Math.ceil(bytes2 / 1400));
8864
+ i.rxBytes += bytes3;
8865
+ i.rxPackets += Math.max(1, Math.ceil(bytes3 / 1400));
8761
8866
  }
8762
8867
  };
8763
8868
  function randomMac() {
8764
- const bytes2 = [2, 66, 172, 17, 0, 2];
8765
- return bytes2.map((b) => b.toString(16).padStart(2, "0")).join(":");
8869
+ const bytes3 = [2, 66, 172, 17, 0, 2];
8870
+ return bytes3.map((b) => b.toString(16).padStart(2, "0")).join(":");
8766
8871
  }
8767
8872
  function hexIp(ip2) {
8768
8873
  return ip2.split(".").reverse().map((o) => Number(o).toString(16).padStart(2, "0").toUpperCase()).join("");
@@ -9207,15 +9312,15 @@ var Parser = class {
9207
9312
  if (this.isWord("-p")) this.next();
9208
9313
  }
9209
9314
  }
9210
- const commands12 = [this.parseCommand()];
9315
+ const commands13 = [this.parseCommand()];
9211
9316
  const stderrToo = [];
9212
9317
  while (this.isOp("|") || this.isOp("|&")) {
9213
9318
  stderrToo.push(this.next().value === "|&");
9214
9319
  this.skipNewlines();
9215
- commands12.push(this.parseCommand());
9320
+ commands13.push(this.parseCommand());
9216
9321
  }
9217
- if (commands12.length === 1 && !negated && !timed) return commands12[0];
9218
- return { type: "pipeline", commands: commands12, negated, stderrToo, timed };
9322
+ if (commands13.length === 1 && !negated && !timed) return commands13[0];
9323
+ return { type: "pipeline", commands: commands13, negated, stderrToo, timed };
9219
9324
  }
9220
9325
  // ── commands ─────────────────────────────────────────────────────────────
9221
9326
  parseCommand() {
@@ -10835,8 +10940,8 @@ var decoder4 = new TextDecoder();
10835
10940
  async function readInputs(ctx, operands, opts = {}) {
10836
10941
  const stdinName = opts.stdinName ?? "-";
10837
10942
  if (operands.length === 0) {
10838
- const bytes2 = await ctx.stdin.readAll();
10839
- return { sources: [{ name: stdinName, bytes: bytes2 }], ok: true };
10943
+ const bytes3 = await ctx.stdin.readAll();
10944
+ return { sources: [{ name: stdinName, bytes: bytes3 }], ok: true };
10840
10945
  }
10841
10946
  const sources = [];
10842
10947
  let ok2 = true;
@@ -10861,8 +10966,8 @@ async function readInputs(ctx, operands, opts = {}) {
10861
10966
  }
10862
10967
  return { sources, ok: ok2 };
10863
10968
  }
10864
- function splitLines(bytes2) {
10865
- const text2 = decoder4.decode(bytes2);
10969
+ function splitLines(bytes3) {
10970
+ const text2 = decoder4.decode(bytes3);
10866
10971
  if (text2 === "") return { lines: [], trailingNewline: true };
10867
10972
  const trailingNewline = text2.endsWith("\n");
10868
10973
  const body = trailingNewline ? text2.slice(0, -1) : text2;
@@ -10874,11 +10979,11 @@ function joinLines(lines, trailingNewline = true) {
10874
10979
  }
10875
10980
  var SI_UNITS = ["", "k", "M", "G", "T", "P", "E"];
10876
10981
  var IEC_UNITS = ["", "K", "M", "G", "T", "P", "E"];
10877
- function humanSize(bytes2, opts = {}) {
10982
+ function humanSize(bytes3, opts = {}) {
10878
10983
  const base2 = opts.si ? 1e3 : 1024;
10879
10984
  const units = opts.si ? SI_UNITS : IEC_UNITS;
10880
- if (bytes2 < base2) return String(bytes2);
10881
- let value = bytes2;
10985
+ if (bytes3 < base2) return String(bytes3);
10986
+ let value = bytes3;
10882
10987
  let unit = 0;
10883
10988
  while (value >= base2 && unit < units.length - 1) {
10884
10989
  value /= base2;
@@ -11168,7 +11273,7 @@ var cat = defineCommand({
11168
11273
  let lineNumber = 1;
11169
11274
  let lastWasBlank = false;
11170
11275
  for (const operand of operands) {
11171
- let bytes2;
11276
+ let bytes3;
11172
11277
  if (operand === "-") {
11173
11278
  if (plain) {
11174
11279
  for (; ; ) {
@@ -11179,7 +11284,7 @@ var cat = defineCommand({
11179
11284
  }
11180
11285
  continue;
11181
11286
  }
11182
- bytes2 = await ctx.stdin.readAll();
11287
+ bytes3 = await ctx.stdin.readAll();
11183
11288
  } else {
11184
11289
  try {
11185
11290
  const abs = ctx.path(operand);
@@ -11189,17 +11294,17 @@ var cat = defineCommand({
11189
11294
  status = 1;
11190
11295
  continue;
11191
11296
  }
11192
- bytes2 = ctx.vfs.readFile(abs, ctx.cred);
11297
+ bytes3 = ctx.vfs.readFile(abs, ctx.cred);
11193
11298
  } catch (e) {
11194
11299
  status = ctx.reportError(e, operand);
11195
11300
  continue;
11196
11301
  }
11197
11302
  }
11198
11303
  if (plain) {
11199
- ctx.write(bytes2);
11304
+ ctx.write(bytes3);
11200
11305
  continue;
11201
11306
  }
11202
- const text2 = new TextDecoder().decode(bytes2);
11307
+ const text2 = new TextDecoder().decode(bytes3);
11203
11308
  const hadTrailing = text2.endsWith("\n");
11204
11309
  const parts = (hadTrailing ? text2.slice(0, -1) : text2).split("\n");
11205
11310
  for (const raw of parts) {
@@ -12053,15 +12158,15 @@ function describeFile(ctx, abs, st, mime) {
12053
12158
  }
12054
12159
  if (st.isCharacterDevice()) return mime ? "inode/chardevice" : "character special";
12055
12160
  if (st.size === 0) return mime ? "inode/x-empty" : "empty";
12056
- const bytes2 = ctx.vfs.readFile(abs, ctx.cred).subarray(0, 512);
12057
- const magic = [...bytes2.subarray(0, 4)];
12161
+ const bytes3 = ctx.vfs.readFile(abs, ctx.cred).subarray(0, 512);
12162
+ const magic = [...bytes3.subarray(0, 4)];
12058
12163
  if (magic[0] === 127 && magic[1] === 69 && magic[2] === 76 && magic[3] === 70) {
12059
12164
  return mime ? "application/x-executable" : "ELF 64-bit LSB executable, x86-64";
12060
12165
  }
12061
12166
  if (magic[0] === 31 && magic[1] === 139) return mime ? "application/gzip" : "gzip compressed data";
12062
12167
  if (magic[0] === 80 && magic[1] === 75) return mime ? "application/zip" : "Zip archive data";
12063
12168
  if (magic[0] === 137 && magic[1] === 80) return mime ? "image/png" : "PNG image data";
12064
- const text2 = new TextDecoder().decode(bytes2);
12169
+ const text2 = new TextDecoder().decode(bytes3);
12065
12170
  const printable = [...text2].every((c) => c === "\n" || c === " " || c === "\r" || c >= " " && c <= "~" || c.charCodeAt(0) > 127);
12066
12171
  if (!printable) return mime ? "application/octet-stream" : "data";
12067
12172
  if (text2.startsWith("#!")) {
@@ -12964,6 +13069,523 @@ var commands3 = [
12964
13069
  clear,
12965
13070
  sync
12966
13071
  ];
13072
+ var platformBuffer = globalThis.Buffer;
13073
+ addUint8ArraySupport(addBase64UrlSupport(index_js.Buffer));
13074
+ var Buffer2 = platformBuffer ?? index_js.Buffer;
13075
+ function addUint8ArraySupport(BufferClass) {
13076
+ const target = BufferClass;
13077
+ if (target.__sandboxedUint8Array) return BufferClass;
13078
+ Object.defineProperty(target, "__sandboxedUint8Array", { value: true });
13079
+ const asBuffer = (value) => value instanceof Uint8Array && !target.isBuffer(value) ? target.from(value.buffer, value.byteOffset, value.byteLength) : value;
13080
+ for (const method of ["indexOf", "lastIndexOf", "includes"]) {
13081
+ const original = target.prototype[method];
13082
+ target.prototype[method] = function(value, ...rest) {
13083
+ return original.call(this, asBuffer(value), ...rest);
13084
+ };
13085
+ }
13086
+ const equals = target.prototype.equals;
13087
+ target.prototype.equals = function(other) {
13088
+ return equals.call(this, asBuffer(other));
13089
+ };
13090
+ return BufferClass;
13091
+ }
13092
+ function addBase64UrlSupport(BufferClass) {
13093
+ const target = BufferClass;
13094
+ if (target.__sandboxedBase64Url) return BufferClass;
13095
+ Object.defineProperty(target, "__sandboxedBase64Url", { value: true });
13096
+ const from = target.from.bind(target);
13097
+ target.from = (value, encodingOrOffset, length) => from(value, normalizeEncoding(encodingOrOffset), length);
13098
+ const byteLength = target.byteLength.bind(target);
13099
+ target.byteLength = (value, encoding) => byteLength(value, normalizeEncoding(encoding));
13100
+ const isEncoding = target.isEncoding?.bind(target);
13101
+ if (isEncoding) target.isEncoding = (encoding) => encoding.toLowerCase() === "base64url" || isEncoding(encoding);
13102
+ const toString = target.prototype.toString;
13103
+ target.prototype.toString = function(encoding, start2, end) {
13104
+ if (encoding?.toLowerCase() !== "base64url") return toString.call(this, encoding, start2, end);
13105
+ return toString.call(this, "base64", start2, end).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
13106
+ };
13107
+ const write = target.prototype.write;
13108
+ target.prototype.write = function(...args) {
13109
+ const index = typeof args[1] === "string" ? 1 : typeof args[2] === "string" ? 2 : 3;
13110
+ if (typeof args[index] === "string") args[index] = normalizeEncoding(args[index]);
13111
+ return write.apply(this, args);
13112
+ };
13113
+ return BufferClass;
13114
+ }
13115
+ function normalizeEncoding(value) {
13116
+ return typeof value === "string" && value.toLowerCase() === "base64url" ? "base64" : value;
13117
+ }
13118
+
13119
+ // src/pkg/clean-installer.ts
13120
+ init_path();
13121
+
13122
+ // src/browser/playwright-browsers.ts
13123
+ init_path();
13124
+ var PLAYWRIGHT_REGISTRY = "/root/.cache/ms-playwright";
13125
+ var LAYOUTS = {
13126
+ "chromium": ["chrome-linux64", "chrome"],
13127
+ "chromium-headless-shell": ["chrome-headless-shell-linux64", "chrome-headless-shell"]
13128
+ };
13129
+ function virtualBrowserFiles(browsersJson) {
13130
+ let manifest;
13131
+ try {
13132
+ manifest = JSON.parse(browsersJson);
13133
+ } catch {
13134
+ return [];
13135
+ }
13136
+ const encoder9 = new TextEncoder();
13137
+ const files = [];
13138
+ for (const browser of manifest.browsers ?? []) {
13139
+ const layout = LAYOUTS[browser.name];
13140
+ if (!layout) continue;
13141
+ const dir3 = join(PLAYWRIGHT_REGISTRY, `${browser.name.replace(/-/g, "_")}-${browser.revision}`);
13142
+ files.push({ path: join(dir3, ...layout), data: encoder9.encode(`#!${BUILTIN_INTERPRETER} chrome
13143
+ `), mode: 493 });
13144
+ files.push({ path: join(dir3, "INSTALLATION_COMPLETE"), data: new Uint8Array() });
13145
+ }
13146
+ return files;
13147
+ }
13148
+ function mkdirp(volume, path) {
13149
+ let current2 = "";
13150
+ for (const part of segments(path)) {
13151
+ current2 += `/${part}`;
13152
+ try {
13153
+ volume.mkdirSync(current2, { mode: 493 });
13154
+ } catch (error) {
13155
+ if (error.code !== "EEXIST") throw error;
13156
+ }
13157
+ }
13158
+ }
13159
+ function installVirtualPlaywrightBrowsers(volume, packageDir) {
13160
+ let text2;
13161
+ try {
13162
+ text2 = new TextDecoder().decode(volume.readFileSync(join(packageDir, "browsers.json")));
13163
+ } catch {
13164
+ return [];
13165
+ }
13166
+ const written = [];
13167
+ for (const file3 of virtualBrowserFiles(text2)) {
13168
+ mkdirp(volume, dirname(file3.path));
13169
+ volume.writeFileSync(file3.path, file3.data);
13170
+ if (file3.mode !== void 0) {
13171
+ volume.chmodSync(file3.path, file3.mode);
13172
+ written.push(file3.path);
13173
+ }
13174
+ }
13175
+ return written;
13176
+ }
13177
+
13178
+ // src/pkg/clean-installer.ts
13179
+ var RUNTIME_PACKAGE_FALLBACKS = {
13180
+ esbuild: "esbuild-wasm",
13181
+ rollup: "@rollup/wasm-node"
13182
+ };
13183
+ var CleanPackageInstaller = class _CleanPackageInstaller {
13184
+ constructor(volume, options = {}) {
13185
+ this.volume = volume;
13186
+ this.options = options;
13187
+ this.registry = (options.registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
13188
+ this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
13189
+ }
13190
+ volume;
13191
+ options;
13192
+ registry;
13193
+ fetcher;
13194
+ metadata = /* @__PURE__ */ new Map();
13195
+ tarballs = /* @__PURE__ */ new Map();
13196
+ /** Single-version manifests, for the fields the packument omits. */
13197
+ details = /* @__PURE__ */ new Map();
13198
+ forCwd(cwd) {
13199
+ const installer = new _CleanPackageInstaller(this.volume, { ...this.options, cwd });
13200
+ installer.metadata = this.metadata;
13201
+ installer.tarballs = this.tarballs;
13202
+ installer.details = this.details;
13203
+ return installer;
13204
+ }
13205
+ async install(name, version = "latest", options = {}) {
13206
+ const cwd = this.options.cwd ?? "/";
13207
+ const manifest = await this.installAt(name, version || "latest", join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
13208
+ if (options.persist !== false) this.persist(cwd, name, version, options.persistDev === true);
13209
+ return manifest;
13210
+ }
13211
+ async installFromManifest(path, options = {}) {
13212
+ const project = this.readJson(path);
13213
+ const cwd = dirname(path);
13214
+ const dependencies = {
13215
+ ...project.dependencies ?? {},
13216
+ ...options.withDevDeps === false ? {} : project.devDependencies ?? {}
13217
+ };
13218
+ await this.prefetch(dependencies);
13219
+ for (const [name, range] of Object.entries(dependencies)) {
13220
+ await this.installAt(name, range, join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
13221
+ }
13222
+ }
13223
+ async installAt(name, range, modulesRoot, options, ancestry) {
13224
+ const metadata = await this.getMetadata(name);
13225
+ const version = resolveVersion(metadata, range);
13226
+ const manifest = metadata.versions[version];
13227
+ if (!manifest) throw new Error(`No matching version found for ${name}@${range}`);
13228
+ const identity = `${name}@${version}`;
13229
+ if (!supportsPlatform(manifest)) throw new IncompatiblePlatform(identity, "");
13230
+ if (manifest.os?.length || manifest.cpu?.length) {
13231
+ const detail = await this.platformDetail(name, version);
13232
+ if (!platformListAllows(detail.libc, PLATFORM.libc)) {
13233
+ throw new IncompatiblePlatform(identity, ` (needs ${detail.libc?.join(", ")})`);
13234
+ }
13235
+ if (detail.main?.endsWith(".node")) {
13236
+ throw new IncompatiblePlatform(identity, " (native addon; this runtime cannot dlopen)");
13237
+ }
13238
+ }
13239
+ const target = join(modulesRoot, name);
13240
+ const installed3 = this.tryReadJson(join(target, "package.json"));
13241
+ if (ancestry.has(identity)) return manifest;
13242
+ if (installed3?.version !== version) {
13243
+ options.onProgress?.(`Fetching ${identity}`);
13244
+ const archive = await this.getTarball(manifest.dist.tarball);
13245
+ verifyIntegrity(archive, manifest.dist.integrity, manifest.dist.shasum, identity);
13246
+ this.removeIfPresent(target);
13247
+ mkdirp2(this.volume, target);
13248
+ extractNpmTarball(this.volume, archive, target);
13249
+ options.onProgress?.(`Installed ${identity}`);
13250
+ }
13251
+ this.createBinLinks(manifest, target, modulesRoot);
13252
+ if (name === "playwright-core") {
13253
+ for (const executable of installVirtualPlaywrightBrowsers(this.volume, target)) {
13254
+ options.onProgress?.(`Linked ${executable} to the virtual browser`);
13255
+ }
13256
+ }
13257
+ const nextAncestry = new Set(ancestry).add(identity);
13258
+ const fallback = RUNTIME_PACKAGE_FALLBACKS[name];
13259
+ if (fallback && fallback !== name) {
13260
+ await this.installAt(fallback, version, modulesRoot, options, nextAncestry);
13261
+ }
13262
+ const childRoot = join(target, "node_modules");
13263
+ const required = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name2]) => !(name2 in (manifest.optionalDependencies ?? {}))));
13264
+ await this.prefetch(required);
13265
+ for (const [dependency, dependencyRange] of Object.entries(required)) {
13266
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
13267
+ }
13268
+ for (const [dependency, dependencyRange] of Object.entries(manifest.optionalDependencies ?? {})) {
13269
+ try {
13270
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
13271
+ } catch (error) {
13272
+ if (error instanceof IncompatiblePlatform) continue;
13273
+ options.onProgress?.(`Skipped optional ${dependency}: ${error instanceof Error ? error.message : String(error)}`);
13274
+ }
13275
+ }
13276
+ return manifest;
13277
+ }
13278
+ /**
13279
+ * The `libc` and `main` fields, which the abbreviated packument leaves out.
13280
+ *
13281
+ * Fetched per version rather than as a full packument: the single-version
13282
+ * document is a few kilobytes, while the full one for a popular package runs
13283
+ * to megabytes. Only packages that already declare `os` or `cpu` ask for it,
13284
+ * so an ordinary install of pure-JavaScript dependencies makes no extra
13285
+ * requests at all — it is the prebuilt binaries, a handful per project, that
13286
+ * need the answer.
13287
+ *
13288
+ * A failure here is not fatal. Being unable to read `libc` puts the check
13289
+ * back where it was before this existed, which is worth strictly less than
13290
+ * being right and strictly more than refusing to install.
13291
+ */
13292
+ async platformDetail(name, version) {
13293
+ const key = `${name}@${version}`;
13294
+ let request = this.details.get(key);
13295
+ if (!request) {
13296
+ request = (async () => {
13297
+ try {
13298
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
13299
+ const response = await this.fetcher(`${this.registry}/${encoded}/${version}`);
13300
+ if (!response.ok) return {};
13301
+ return await response.json();
13302
+ } catch {
13303
+ return {};
13304
+ }
13305
+ })();
13306
+ this.details.set(key, request);
13307
+ }
13308
+ return request;
13309
+ }
13310
+ /** Overlap up to six sibling downloads; filesystem writes remain ordered. */
13311
+ async prefetch(dependencies) {
13312
+ const entries = Object.entries(dependencies);
13313
+ let next = 0;
13314
+ await Promise.all(Array.from({ length: Math.min(6, entries.length) }, async () => {
13315
+ while (next < entries.length) {
13316
+ const [name, range] = entries[next++];
13317
+ try {
13318
+ const metadata = await this.getMetadata(name);
13319
+ const manifest = metadata.versions[resolveVersion(metadata, range)];
13320
+ if (!manifest.os?.length && !manifest.cpu?.length && supportsPlatform(manifest)) {
13321
+ await this.getTarball(manifest.dist.tarball);
13322
+ }
13323
+ } catch {
13324
+ }
13325
+ }
13326
+ }));
13327
+ }
13328
+ async getMetadata(name) {
13329
+ let request = this.metadata.get(name);
13330
+ if (!request) {
13331
+ request = (async () => {
13332
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
13333
+ const response = await this.fetcher(`${this.registry}/${encoded}`, {
13334
+ headers: { Accept: "application/vnd.npm.install-v1+json" }
13335
+ });
13336
+ if (!response.ok) throw new Error(`registry returned ${response.status} for ${name}`);
13337
+ return await response.json();
13338
+ })();
13339
+ this.metadata.set(name, request);
13340
+ void request.catch(() => {
13341
+ this.metadata.delete(name);
13342
+ });
13343
+ }
13344
+ return request;
13345
+ }
13346
+ async getTarball(url) {
13347
+ let request = this.tarballs.get(url);
13348
+ if (!request) {
13349
+ request = (async () => {
13350
+ const response = await this.fetcher(url);
13351
+ if (!response.ok) throw new Error(`tarball returned ${response.status}: ${url}`);
13352
+ return new Uint8Array(await response.arrayBuffer());
13353
+ })();
13354
+ this.tarballs.set(url, request);
13355
+ void request.catch(() => {
13356
+ this.tarballs.delete(url);
13357
+ });
13358
+ }
13359
+ return request;
13360
+ }
13361
+ createBinLinks(manifest, target, modulesRoot) {
13362
+ if (!manifest.bin) return;
13363
+ const bins = typeof manifest.bin === "string" ? { [unscoped(manifest.name)]: manifest.bin } : manifest.bin;
13364
+ const binDir = join(modulesRoot, ".bin");
13365
+ mkdirp2(this.volume, binDir);
13366
+ for (const [name, path] of Object.entries(bins)) {
13367
+ const link = join(binDir, name);
13368
+ this.removeIfPresent(link);
13369
+ this.volume.symlinkSync(relative(binDir, join(target, path)), link);
13370
+ }
13371
+ }
13372
+ persist(cwd, name, range, dev) {
13373
+ const path = join(cwd, "package.json");
13374
+ const manifest = this.tryReadJson(path) ?? {};
13375
+ const key = dev ? "devDependencies" : "dependencies";
13376
+ manifest[key] = { ...manifest[key] ?? {}, [name]: range === "latest" ? "*" : range };
13377
+ this.volume.writeFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
13378
+ }
13379
+ removeIfPresent(path) {
13380
+ let stat2;
13381
+ try {
13382
+ stat2 = this.volume.lstatSync(path);
13383
+ } catch {
13384
+ return;
13385
+ }
13386
+ if (!stat2.isDirectory()) return this.volume.unlinkSync(path);
13387
+ for (const name of this.volume.readdirSync(path)) this.removeIfPresent(join(path, name));
13388
+ this.volume.rmdirSync(path);
13389
+ }
13390
+ readJson(path) {
13391
+ return JSON.parse(new TextDecoder().decode(this.volume.readFileSync(path)));
13392
+ }
13393
+ tryReadJson(path) {
13394
+ try {
13395
+ return this.readJson(path);
13396
+ } catch {
13397
+ return null;
13398
+ }
13399
+ }
13400
+ };
13401
+ var PLATFORM = { os: "linux", cpu: "x64", libc: "glibc" };
13402
+ var IncompatiblePlatform = class extends Error {
13403
+ constructor(identity, detail) {
13404
+ super(`${identity} is not compatible with ${PLATFORM.os}/${PLATFORM.cpu}/${PLATFORM.libc}${detail}`);
13405
+ this.name = "IncompatiblePlatform";
13406
+ }
13407
+ };
13408
+ function supportsPlatform(manifest) {
13409
+ return platformListAllows(manifest.os, PLATFORM.os) && platformListAllows(manifest.cpu, PLATFORM.cpu) && platformListAllows(manifest.libc, PLATFORM.libc);
13410
+ }
13411
+ function platformListAllows(values, current2) {
13412
+ if (!values?.length) return true;
13413
+ if (values.includes(`!${current2}`)) return false;
13414
+ const positive = values.filter((value) => !value.startsWith("!"));
13415
+ return positive.length === 0 || positive.includes(current2) || positive.includes("any");
13416
+ }
13417
+ function resolveVersion(metadata, range) {
13418
+ const tag2 = metadata["dist-tags"]?.[range];
13419
+ if (tag2) return tag2;
13420
+ if (semver.valid(range) && metadata.versions[range]) return range;
13421
+ const found2 = semver.maxSatisfying(Object.keys(metadata.versions), range === "latest" ? "*" : range, { includePrerelease: false });
13422
+ if (!found2) throw new Error(`No matching version found for ${metadata.name}@${range}`);
13423
+ return found2;
13424
+ }
13425
+ function verifyIntegrity(data, integrity, shasum, identity) {
13426
+ if (integrity) {
13427
+ const choices = integrity.trim().split(/\s+/);
13428
+ for (const choice of choices) {
13429
+ const dash = choice.indexOf("-");
13430
+ const algorithm = choice.slice(0, dash);
13431
+ const expected = choice.slice(dash + 1).replace(/\?.*$/, "");
13432
+ const digest2 = algorithm === "sha512" ? sha512.sha512(data) : algorithm === "sha256" ? sha256.sha256(data) : null;
13433
+ if (digest2 && Buffer2.from(digest2).toString("base64") === expected) return;
13434
+ }
13435
+ throw new Error(`Integrity check failed for ${identity}`);
13436
+ }
13437
+ if (shasum && Buffer2.from(sha1.sha1(data)).toString("hex") === shasum) return;
13438
+ if (shasum) throw new Error(`Legacy checksum check failed for ${identity}`);
13439
+ }
13440
+ function extractNpmTarball(volume, compressed, destination) {
13441
+ const tar2 = pako.ungzip(compressed);
13442
+ let offset = 0;
13443
+ let longPath = null;
13444
+ let paxPath = null;
13445
+ while (offset + 512 <= tar2.length) {
13446
+ const header = tar2.subarray(offset, offset + 512);
13447
+ if (header.every((byte) => byte === 0)) break;
13448
+ const size = octal(header, 124, 12);
13449
+ const type = String.fromCharCode(header[156] || 48);
13450
+ const prefix = text(header, 345, 155);
13451
+ let name = longPath ?? paxPath ?? [prefix, text(header, 0, 100)].filter(Boolean).join("/");
13452
+ longPath = null;
13453
+ paxPath = null;
13454
+ const data = tar2.subarray(offset + 512, offset + 512 + size);
13455
+ offset += 512 + Math.ceil(size / 512) * 512;
13456
+ if (type === "L") {
13457
+ longPath = new TextDecoder().decode(data).replace(/\0.*$/, "").trim();
13458
+ continue;
13459
+ }
13460
+ if (type === "x" || type === "g") {
13461
+ paxPath = parsePax(data).path ?? null;
13462
+ continue;
13463
+ }
13464
+ name = stripPackageRoot(name);
13465
+ if (!name) continue;
13466
+ const target = safeTarget(destination, name);
13467
+ const mode = octal(header, 100, 8) || 420;
13468
+ if (type === "5") {
13469
+ mkdirp2(volume, target, mode);
13470
+ } else if (type === "2") {
13471
+ mkdirp2(volume, dirname(target));
13472
+ volume.symlinkSync(text(header, 157, 100), target);
13473
+ } else if (type === "1") {
13474
+ mkdirp2(volume, dirname(target));
13475
+ volume.linkSync(safeTarget(destination, stripPackageRoot(text(header, 157, 100))), target);
13476
+ } else if (type === "0" || type === "\0" || type === "7") {
13477
+ mkdirp2(volume, dirname(target));
13478
+ volume.writeFileSync(target, data.slice());
13479
+ volume.chmodSync(target, mode);
13480
+ }
13481
+ }
13482
+ }
13483
+ function mkdirp2(volume, path, mode = 493) {
13484
+ let current2 = "";
13485
+ for (const part of segments(path)) {
13486
+ current2 += `/${part}`;
13487
+ try {
13488
+ volume.mkdirSync(current2, { mode });
13489
+ } catch (error) {
13490
+ if (error.code !== "EEXIST") throw error;
13491
+ if (!volume.lstatSync(current2).isDirectory()) throw error;
13492
+ }
13493
+ }
13494
+ }
13495
+ function safeTarget(destination, name) {
13496
+ const clean2 = clean(`/${name}`).slice(1);
13497
+ if (!clean2 || clean2 === ".." || clean2.startsWith("../") || name.startsWith("/")) throw new Error(`Unsafe path in package: ${name}`);
13498
+ return join(destination, clean2);
13499
+ }
13500
+ function stripPackageRoot(name) {
13501
+ const clean2 = name.replace(/^\.\//, "").replace(/\/$/, "");
13502
+ const slash = clean2.indexOf("/");
13503
+ return slash === -1 ? "" : clean2.slice(slash + 1);
13504
+ }
13505
+ function text(bytes3, start2, length) {
13506
+ return new TextDecoder().decode(bytes3.subarray(start2, start2 + length)).replace(/\0.*$/, "").trim();
13507
+ }
13508
+ function octal(bytes3, start2, length) {
13509
+ return parseInt(text(bytes3, start2, length).replace(/^0+/, "") || "0", 8);
13510
+ }
13511
+ function parsePax(data) {
13512
+ const value = new TextDecoder().decode(data);
13513
+ const result = {};
13514
+ let offset = 0;
13515
+ while (offset < value.length) {
13516
+ const space = value.indexOf(" ", offset);
13517
+ if (space < 0) break;
13518
+ const length = Number(value.slice(offset, space));
13519
+ if (!Number.isFinite(length) || length <= 0) break;
13520
+ const record2 = value.slice(space + 1, offset + length - 1);
13521
+ const equal2 = record2.indexOf("=");
13522
+ if (equal2 > 0) result[record2.slice(0, equal2)] = record2.slice(equal2 + 1);
13523
+ offset += length;
13524
+ }
13525
+ return result;
13526
+ }
13527
+ function unscoped(name) {
13528
+ return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
13529
+ }
13530
+
13531
+ // src/bin/capabilities.ts
13532
+ function report(ctx) {
13533
+ const commands13 = ctx.kernel.commands.names();
13534
+ const has = (name) => commands13.includes(name);
13535
+ return {
13536
+ schemaVersion: 1,
13537
+ runtime: "sandboxedjs",
13538
+ platform: { os: "linux", arch: "x64", libc: "glibc" },
13539
+ filesystem: { writable: true, root: "/", persistence: "container-lifetime", hostAccess: false },
13540
+ shell: { posix: true, pipelines: true, redirection: true, backgroundProcesses: true },
13541
+ languages: { node: has("node"), python: has("python3"), wasmWasi: has("wasi") },
13542
+ packages: {
13543
+ npm: has("npm"),
13544
+ pip: has("pip"),
13545
+ applicationRegistry: has("pm"),
13546
+ nativeAddons: false,
13547
+ fallbacks: RUNTIME_PACKAGE_FALLBACKS
13548
+ },
13549
+ network: {
13550
+ virtualServers: true,
13551
+ loopback: true,
13552
+ outbound: ctx.kernel.net.policy.allowOutbound,
13553
+ allowedHosts: ctx.kernel.net.policy.allowedHosts,
13554
+ proxy: ctx.kernel.net.proxy !== null,
13555
+ listeningPorts: ctx.kernel.net.listening().map(({ port, proto, program }) => ({ port, proto, program }))
13556
+ },
13557
+ interfaces: {
13558
+ desktopGui: false,
13559
+ hostFilesystem: false,
13560
+ systemPackageManager: false,
13561
+ docker: false
13562
+ },
13563
+ commands: commands13
13564
+ };
13565
+ }
13566
+ var sandboxedjsCapabilities = defineCommand({
13567
+ name: "sandboxedjs-capabilities",
13568
+ aliases: ["sbx-capabilities"],
13569
+ path: "/usr/bin/sandboxedjs-capabilities",
13570
+ summary: "report the runtime capabilities available to tools and agents",
13571
+ usage: "sandboxedjs-capabilities [--json]",
13572
+ run(ctx) {
13573
+ const result = report(ctx);
13574
+ if (ctx.args.includes("--json")) {
13575
+ ctx.line(JSON.stringify(result, null, 2));
13576
+ return 0;
13577
+ }
13578
+ ctx.line("SandboxedJS runtime capabilities");
13579
+ ctx.line(` commands: ${result.commands.length}`);
13580
+ ctx.line(` languages: ${Object.entries(result.languages).filter(([, enabled]) => enabled).map(([name]) => name).join(", ")}`);
13581
+ ctx.line(` outbound network: ${result.network.outbound ? "enabled" : "disabled"}`);
13582
+ ctx.line(` writable filesystem: ${result.filesystem.root} (${result.filesystem.persistence})`);
13583
+ ctx.line(` package fallbacks: ${Object.entries(result.packages.fallbacks).map(([from, to]) => `${from} -> ${to}`).join(", ") || "none"}`);
13584
+ ctx.line("Run with --json for the complete machine-readable inventory.");
13585
+ return 0;
13586
+ }
13587
+ });
13588
+ var commands4 = [sandboxedjsCapabilities];
12967
13589
 
12968
13590
  // src/bin/sed.ts
12969
13591
  var SedParseError = class extends Error {
@@ -15406,8 +16028,8 @@ async function runAwk(ctx) {
15406
16028
  continue;
15407
16029
  }
15408
16030
  try {
15409
- const bytes2 = ctx.vfs.readFile(ctx.path(operand), ctx.cred);
15410
- inputs.push({ name: operand, lines: splitLines(bytes2).lines });
16031
+ const bytes3 = ctx.vfs.readFile(ctx.path(operand), ctx.cred);
16032
+ inputs.push({ name: operand, lines: splitLines(bytes3).lines });
15411
16033
  } catch (e) {
15412
16034
  ctx.reportError(e, operand);
15413
16035
  return 2;
@@ -15550,12 +16172,12 @@ async function followFiles(ctx, paths, intervalMs) {
15550
16172
  if (ctx.signal.aborted) break;
15551
16173
  for (const path of paths) {
15552
16174
  try {
15553
- const bytes2 = ctx.vfs.readFile(ctx.path(path), ctx.cred);
16175
+ const bytes3 = ctx.vfs.readFile(ctx.path(path), ctx.cred);
15554
16176
  const previous = offsets.get(path) ?? 0;
15555
- if (bytes2.length > previous) {
15556
- ctx.write(bytes2.subarray(previous));
15557
- offsets.set(path, bytes2.length);
15558
- } else if (bytes2.length < previous) {
16177
+ if (bytes3.length > previous) {
16178
+ ctx.write(bytes3.subarray(previous));
16179
+ offsets.set(path, bytes3.length);
16180
+ } else if (bytes3.length < previous) {
15559
16181
  offsets.set(path, 0);
15560
16182
  }
15561
16183
  } catch {
@@ -15938,14 +16560,14 @@ var tee = defineCommand({
15938
16560
  { short: "a", long: "append" },
15939
16561
  { short: "i", long: "ignore-interrupts" }
15940
16562
  ]);
15941
- const bytes2 = await ctx.stdin.readAll();
15942
- ctx.write(bytes2);
16563
+ const bytes3 = await ctx.stdin.readAll();
16564
+ ctx.write(bytes3);
15943
16565
  let status = 0;
15944
16566
  for (const target of args.positional) {
15945
16567
  try {
15946
16568
  const abs = ctx.path(target);
15947
- if (args.has("append")) ctx.vfs.appendFile(abs, bytes2, { cred: ctx.cred });
15948
- else ctx.vfs.writeFile(abs, bytes2, { cred: ctx.cred });
16569
+ if (args.has("append")) ctx.vfs.appendFile(abs, bytes3, { cred: ctx.cred });
16570
+ else ctx.vfs.writeFile(abs, bytes3, { cred: ctx.cred });
15949
16571
  } catch (e) {
15950
16572
  status = ctx.reportError(e, target);
15951
16573
  }
@@ -16258,16 +16880,16 @@ var split = defineCommand({
16258
16880
  const [input, prefixRaw] = args.positional;
16259
16881
  const prefix = prefixRaw ?? "x";
16260
16882
  const { sources, ok: ok2 } = await readInputs(ctx, input ? [input] : []);
16261
- const bytes2 = sources[0]?.bytes ?? new Uint8Array(0);
16883
+ const bytes3 = sources[0]?.bytes ?? new Uint8Array(0);
16262
16884
  const suffixLength = args.num("suffix-length", 2);
16263
16885
  const chunks = [];
16264
16886
  const byteSpec = args.str("bytes");
16265
16887
  if (byteSpec !== void 0) {
16266
16888
  const size = parseSize(byteSpec) ?? 1024;
16267
- for (let i = 0; i < bytes2.length; i += size) chunks.push(bytes2.subarray(i, i + size));
16889
+ for (let i = 0; i < bytes3.length; i += size) chunks.push(bytes3.subarray(i, i + size));
16268
16890
  } else {
16269
16891
  const perChunk = args.num("lines", 1e3);
16270
- const { lines } = splitLines(bytes2);
16892
+ const { lines } = splitLines(bytes3);
16271
16893
  for (let i = 0; i < lines.length; i += perChunk) {
16272
16894
  chunks.push(new TextEncoder().encode(joinLines(lines.slice(i, i + perChunk), true)));
16273
16895
  }
@@ -16331,7 +16953,7 @@ var awk = defineCommand({
16331
16953
  usage: "awk [-F fs] [-v var=value] 'program' [FILE]...",
16332
16954
  run: runAwk
16333
16955
  });
16334
- var commands4 = [
16956
+ var commands5 = [
16335
16957
  head,
16336
16958
  tail,
16337
16959
  wc,
@@ -16477,19 +17099,19 @@ var grep = defineCommand({
16477
17099
  let anyMatch = false;
16478
17100
  let status = 1;
16479
17101
  for (const target of targets) {
16480
- let bytes2;
17102
+ let bytes3;
16481
17103
  if (target === "-") {
16482
- bytes2 = await ctx.stdin.readAll();
17104
+ bytes3 = await ctx.stdin.readAll();
16483
17105
  } else {
16484
17106
  try {
16485
- bytes2 = ctx.vfs.readFile(ctx.path(target), ctx.cred);
17107
+ bytes3 = ctx.vfs.readFile(ctx.path(target), ctx.cred);
16486
17108
  } catch (e) {
16487
17109
  if (!args.has("no-messages")) ctx.reportError(e, target);
16488
17110
  status = 2;
16489
17111
  continue;
16490
17112
  }
16491
17113
  }
16492
- const { lines } = splitLines(bytes2);
17114
+ const { lines } = splitLines(bytes3);
16493
17115
  const matched = [];
16494
17116
  let count = 0;
16495
17117
  for (let i = 0; i < lines.length && count < maxCount; i++) {
@@ -17062,7 +17684,7 @@ var cmp = defineCommand({
17062
17684
  return 0;
17063
17685
  }
17064
17686
  });
17065
- var commands5 = [grep, find, xargs, diff, cmp];
17687
+ var commands6 = [grep, find, xargs, diff, cmp];
17066
17688
 
17067
17689
  // src/bin/archive.ts
17068
17690
  init_mode();
@@ -17072,8 +17694,8 @@ var BLOCK = 512;
17072
17694
  var encoder5 = new TextEncoder();
17073
17695
  var decoder7 = new TextDecoder();
17074
17696
  function writeString(block, offset, value, length) {
17075
- const bytes2 = encoder5.encode(value);
17076
- for (let i = 0; i < length; i++) block[offset + i] = i < bytes2.length ? bytes2[i] : 0;
17697
+ const bytes3 = encoder5.encode(value);
17698
+ for (let i = 0; i < length; i++) block[offset + i] = i < bytes3.length ? bytes3[i] : 0;
17077
17699
  }
17078
17700
  function writeOctal(block, offset, value, length) {
17079
17701
  const text2 = value.toString(8).padStart(length - 1, "0");
@@ -17224,23 +17846,23 @@ var tar = defineCommand({
17224
17846
  if (args.has("verbose")) ctx.line(name);
17225
17847
  };
17226
17848
  for (const operand of args.positional) add(resolve(baseDir, operand), operand);
17227
- let bytes3 = createTar(entries2);
17228
- if (compressed) bytes3 = await gzip(bytes3);
17229
- if (archive === void 0 || archive === "-") ctx.write(bytes3);
17230
- else ctx.vfs.writeFile(ctx.path(archive), bytes3, { cred: ctx.cred, mode: 420 });
17849
+ let bytes4 = createTar(entries2);
17850
+ if (compressed) bytes4 = await gzip(bytes4);
17851
+ if (archive === void 0 || archive === "-") ctx.write(bytes4);
17852
+ else ctx.vfs.writeFile(ctx.path(archive), bytes4, { cred: ctx.cred, mode: 420 });
17231
17853
  return 0;
17232
17854
  }
17233
- let bytes2;
17234
- if (archive === void 0 || archive === "-") bytes2 = await ctx.stdin.readAll();
17855
+ let bytes3;
17856
+ if (archive === void 0 || archive === "-") bytes3 = await ctx.stdin.readAll();
17235
17857
  else {
17236
17858
  try {
17237
- bytes2 = ctx.vfs.readFile(ctx.path(archive), ctx.cred);
17859
+ bytes3 = ctx.vfs.readFile(ctx.path(archive), ctx.cred);
17238
17860
  } catch (e) {
17239
17861
  return ctx.reportError(e, archive);
17240
17862
  }
17241
17863
  }
17242
- if (bytes2[0] === 31 && bytes2[1] === 139) bytes2 = await gunzip(bytes2);
17243
- const entries = readTar(bytes2);
17864
+ if (bytes3[0] === 31 && bytes3[1] === 139) bytes3 = await gunzip(bytes3);
17865
+ const entries = readTar(bytes3);
17244
17866
  const strip = args.num("strip-components", 0);
17245
17867
  if (args.has("list")) {
17246
17868
  for (const entry of entries) {
@@ -17377,7 +17999,7 @@ var zlibCompress = defineCommand({
17377
17999
  });
17378
18000
  }
17379
18001
  });
17380
- var commands6 = [tar, gzip2, gunzip2, zcat, zlibCompress];
18002
+ var commands7 = [tar, gzip2, gunzip2, zcat, zlibCompress];
17381
18003
 
17382
18004
  // src/bin/hash.ts
17383
18005
  init_binary();
@@ -17419,8 +18041,8 @@ async function checkSums(ctx, algorithm, files, quiet) {
17419
18041
  checked++;
17420
18042
  const [, expected, name] = m;
17421
18043
  try {
17422
- const bytes2 = ctx.vfs.readFile(ctx.path(name), ctx.cred);
17423
- const actual = await digestHex(algorithm, bytes2);
18044
+ const bytes3 = ctx.vfs.readFile(ctx.path(name), ctx.cred);
18045
+ const actual = await digestHex(algorithm, bytes3);
17424
18046
  if (actual === expected.toLowerCase()) {
17425
18047
  if (!quiet) ctx.line(`${name}: OK`);
17426
18048
  } else {
@@ -17585,7 +18207,7 @@ var mktemp = defineCommand({
17585
18207
  return 0;
17586
18208
  }
17587
18209
  });
17588
- var commands7 = [
18210
+ var commands8 = [
17589
18211
  md5sum,
17590
18212
  sha1sum,
17591
18213
  sha224sum,
@@ -18061,7 +18683,7 @@ var host = defineCommand({
18061
18683
  return 0;
18062
18684
  }
18063
18685
  });
18064
- var commands8 = [curl, wget, ping, ip, ifconfig, ss, netstat, nc, host];
18686
+ var commands9 = [curl, wget, ping, ip, ifconfig, ss, netstat, nc, host];
18065
18687
 
18066
18688
  // src/bin/admin.ts
18067
18689
  init_mode();
@@ -18498,7 +19120,7 @@ sys ${fmt2(Math.floor(ms * 0.2))}
18498
19120
  return code;
18499
19121
  }
18500
19122
  });
18501
- var commands9 = [
19123
+ var commands10 = [
18502
19124
  suCmd,
18503
19125
  sudo,
18504
19126
  useradd,
@@ -18674,7 +19296,7 @@ var helpCmd = defineCommand({
18674
19296
  return 0;
18675
19297
  }
18676
19298
  });
18677
- var commands10 = [man, whatis, apropos, less, helpCmd];
19299
+ var commands11 = [man, whatis, apropos, less, helpCmd];
18678
19300
 
18679
19301
  // src/bin/clipboard.ts
18680
19302
  init_path();
@@ -18689,12 +19311,12 @@ function readSelection(ctx, selection) {
18689
19311
  return new Uint8Array();
18690
19312
  }
18691
19313
  }
18692
- function writeSelection(ctx, selection, bytes2) {
19314
+ function writeSelection(ctx, selection, bytes3) {
18693
19315
  try {
18694
19316
  ctx.vfs.mkdir(CLIPBOARD_DIR, { recursive: true, mode: 511 });
18695
19317
  } catch {
18696
19318
  }
18697
- ctx.vfs.writeFile(selectionPath(selection), bytes2, { privileged: true, mode: 438 });
19319
+ ctx.vfs.writeFile(selectionPath(selection), bytes3, { privileged: true, mode: 438 });
18698
19320
  }
18699
19321
  var xsel = defineCommand({
18700
19322
  name: "xsel",
@@ -18796,8 +19418,8 @@ var wlCopy = defineCommand({
18796
19418
  async run(ctx) {
18797
19419
  const selection = ctx.args.includes("--primary") || ctx.args.includes("-p") ? "primary" : "clipboard";
18798
19420
  const operands = ctx.args.filter((arg) => !arg.startsWith("-"));
18799
- const bytes2 = operands.length ? new TextEncoder().encode(operands.join(" ")) : await ctx.stdin.readAll();
18800
- writeSelection(ctx, selection, bytes2);
19421
+ const bytes3 = operands.length ? new TextEncoder().encode(operands.join(" ")) : await ctx.stdin.readAll();
19422
+ writeSelection(ctx, selection, bytes3);
18801
19423
  return 0;
18802
19424
  }
18803
19425
  });
@@ -18807,13 +19429,13 @@ var wlPaste = defineCommand({
18807
19429
  usage: "wl-paste [--primary] [-n]",
18808
19430
  run(ctx) {
18809
19431
  const selection = ctx.args.includes("--primary") || ctx.args.includes("-p") ? "primary" : "clipboard";
18810
- const bytes2 = readSelection(ctx, selection);
18811
- ctx.write(bytes2);
19432
+ const bytes3 = readSelection(ctx, selection);
19433
+ ctx.write(bytes3);
18812
19434
  if (!ctx.args.includes("-n") && !ctx.args.includes("--no-newline")) ctx.write("\n");
18813
19435
  return 0;
18814
19436
  }
18815
19437
  });
18816
- var commands11 = [xsel, xclip, pbcopy, pbpaste, wlCopy, wlPaste];
19438
+ var commands12 = [xsel, xclip, pbcopy, pbpaste, wlCopy, wlPaste];
18817
19439
 
18818
19440
  // src/node/node.ts
18819
19441
  init_path();
@@ -19404,10 +20026,10 @@ async function execute(ctx, invocation) {
19404
20026
  }
19405
20027
  async function captureStdin(ctx) {
19406
20028
  if (ctx.stdin.isTTY || ctx.stdin.interactive) return null;
19407
- const bytes2 = await ctx.stdin.readAll();
19408
- if (bytes2.length === 0) return null;
20029
+ const bytes3 = await ctx.stdin.readAll();
20030
+ if (bytes3.length === 0) return null;
19409
20031
  const path = tempPath("stdin", ctx.proc.pid, ".dat");
19410
- ctx.vfs.writeFile(path, bytes2, { privileged: true, mode: 384 });
20032
+ ctx.vfs.writeFile(path, bytes3, { privileged: true, mode: 384 });
19411
20033
  return path;
19412
20034
  }
19413
20035
  var node = defineCommand({
@@ -21109,7 +21731,7 @@ var wheels_default = {
21109
21731
 
21110
21732
  // package.json
21111
21733
  var package_default = {
21112
- version: "0.2.22"};
21734
+ version: "0.2.23"};
21113
21735
 
21114
21736
  // src/python/extension-abi.ts
21115
21737
  var EXTENSION_ABI = {
@@ -21960,9 +22582,9 @@ var Reader = class {
21960
22582
  at = 0;
21961
22583
  view;
21962
22584
  bytes;
21963
- constructor(bytes2) {
21964
- this.bytes = bytes2;
21965
- this.view = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength);
22585
+ constructor(bytes3) {
22586
+ this.bytes = bytes3;
22587
+ this.view = new DataView(bytes3.buffer, bytes3.byteOffset, bytes3.byteLength);
21966
22588
  }
21967
22589
  need(count) {
21968
22590
  if (this.at + count > this.bytes.length) throw new ProtocolError("payload underrun");
@@ -22048,9 +22670,9 @@ var ByteQueue = class {
22048
22670
  chunks = [];
22049
22671
  length = 0;
22050
22672
  waiters = /* @__PURE__ */ new Set();
22051
- push(bytes2) {
22052
- if (bytes2.length === 0) return;
22053
- const copy = bytes2.slice();
22673
+ push(bytes3) {
22674
+ if (bytes3.length === 0) return;
22675
+ const copy = bytes3.slice();
22054
22676
  this.chunks.push(copy);
22055
22677
  this.length += copy.length;
22056
22678
  this.wake();
@@ -22110,10 +22732,10 @@ var VirtualTcpConnection = class {
22110
22732
  if (this.eof) return new Uint8Array();
22111
22733
  throw new PosixError(Errno.EAGAIN, "socket read would block");
22112
22734
  }
22113
- write(bytes2) {
22735
+ write(bytes3) {
22114
22736
  if (!this.writable) throw new PosixError(this.closed || this.writeClosed ? Errno.EPIPE : Errno.ECONNRESET);
22115
- this.peer.incoming.push(bytes2);
22116
- return bytes2.length;
22737
+ this.peer.incoming.push(bytes3);
22738
+ return bytes3.length;
22117
22739
  }
22118
22740
  async waitForChange() {
22119
22741
  if (this.readable || this.closed) return;
@@ -22396,9 +23018,9 @@ var SO_ERROR = 4;
22396
23018
  var SO_TYPE = 3;
22397
23019
  var SOCK_STREAM = 1;
22398
23020
  function int32(value) {
22399
- const bytes2 = new Uint8Array(4);
22400
- new DataView(bytes2.buffer).setInt32(0, value, true);
22401
- return bytes2;
23021
+ const bytes3 = new Uint8Array(4);
23022
+ new DataView(bytes3.buffer).setInt32(0, value, true);
23023
+ return bytes3;
22402
23024
  }
22403
23025
  function isLoopback(address) {
22404
23026
  if (address === "" || address === "localhost" || address === "0.0.0.0") return true;
@@ -22789,9 +23411,9 @@ function createHostAbiServer(proc) {
22789
23411
  /* ---------------------------------------------------------- entropy */
22790
23412
  case Op.getrandom: {
22791
23413
  const length = Math.min(r.u32(), 65536);
22792
- const bytes2 = new Uint8Array(length);
22793
- crypto.getRandomValues(bytes2);
22794
- return { status: length, payload: bytes2 };
23414
+ const bytes3 = new Uint8Array(length);
23415
+ crypto.getRandomValues(bytes3);
23416
+ return { status: length, payload: bytes3 };
22795
23417
  }
22796
23418
  /* ----------------------------------------------------------- sockets */
22797
23419
  case Op.socket: {
@@ -23277,9 +23899,9 @@ var FIRST_EGRESS_PORT = 48e3;
23277
23899
  var MAX_HEADER_BYTES = 64 * 1024;
23278
23900
  var MAX_BODY_BYTES = 32 * 1024 * 1024;
23279
23901
  var CRLF = "\r\n";
23280
- function indexOfDoubleCrlf(bytes2) {
23281
- for (let i = 3; i < bytes2.length; i++) {
23282
- if (bytes2[i] === 10 && bytes2[i - 1] === 13 && bytes2[i - 2] === 10 && bytes2[i - 3] === 13) return i + 1;
23902
+ function indexOfDoubleCrlf(bytes3) {
23903
+ for (let i = 3; i < bytes3.length; i++) {
23904
+ if (bytes3[i] === 10 && bytes3[i - 1] === 13 && bytes3[i - 2] === 10 && bytes3[i - 3] === 13) return i + 1;
23283
23905
  }
23284
23906
  return -1;
23285
23907
  }
@@ -23544,62 +24166,6 @@ function splitOnce(text2, separator) {
23544
24166
  return at < 0 ? [text2] : [text2.slice(0, at), text2.slice(at + 1)];
23545
24167
  }
23546
24168
 
23547
- // src/browser/playwright-browsers.ts
23548
- init_path();
23549
- var PLAYWRIGHT_REGISTRY = "/root/.cache/ms-playwright";
23550
- var LAYOUTS = {
23551
- "chromium": ["chrome-linux64", "chrome"],
23552
- "chromium-headless-shell": ["chrome-headless-shell-linux64", "chrome-headless-shell"]
23553
- };
23554
- function virtualBrowserFiles(browsersJson) {
23555
- let manifest;
23556
- try {
23557
- manifest = JSON.parse(browsersJson);
23558
- } catch {
23559
- return [];
23560
- }
23561
- const encoder9 = new TextEncoder();
23562
- const files = [];
23563
- for (const browser of manifest.browsers ?? []) {
23564
- const layout = LAYOUTS[browser.name];
23565
- if (!layout) continue;
23566
- const dir3 = join(PLAYWRIGHT_REGISTRY, `${browser.name.replace(/-/g, "_")}-${browser.revision}`);
23567
- files.push({ path: join(dir3, ...layout), data: encoder9.encode(`#!${BUILTIN_INTERPRETER} chrome
23568
- `), mode: 493 });
23569
- files.push({ path: join(dir3, "INSTALLATION_COMPLETE"), data: new Uint8Array() });
23570
- }
23571
- return files;
23572
- }
23573
- function mkdirp(volume, path) {
23574
- let current2 = "";
23575
- for (const part of segments(path)) {
23576
- current2 += `/${part}`;
23577
- try {
23578
- volume.mkdirSync(current2, { mode: 493 });
23579
- } catch (error) {
23580
- if (error.code !== "EEXIST") throw error;
23581
- }
23582
- }
23583
- }
23584
- function installVirtualPlaywrightBrowsers(volume, packageDir) {
23585
- let text2;
23586
- try {
23587
- text2 = new TextDecoder().decode(volume.readFileSync(join(packageDir, "browsers.json")));
23588
- } catch {
23589
- return [];
23590
- }
23591
- const written = [];
23592
- for (const file3 of virtualBrowserFiles(text2)) {
23593
- mkdirp(volume, dirname(file3.path));
23594
- volume.writeFileSync(file3.path, file3.data);
23595
- if (file3.mode !== void 0) {
23596
- volume.chmodSync(file3.path, file3.mode);
23597
- written.push(file3.path);
23598
- }
23599
- }
23600
- return written;
23601
- }
23602
-
23603
24169
  // src/python/substitutions.ts
23604
24170
  var SUBSTITUTED_WHEELS = {
23605
24171
  playwright: /-py3-none-manylinux1_x86_64\.whl$/
@@ -24166,27 +24732,27 @@ async function installRequirements(options) {
24166
24732
  continue;
24167
24733
  }
24168
24734
  options.progress.downloading(distribution.name, distribution.version);
24169
- const bytes2 = await download(options.client, distribution);
24170
- const files = stageWheel(readZip(bytes2));
24735
+ const bytes3 = await download(options.client, distribution);
24736
+ const files = stageWheel(readZip(bytes3));
24171
24737
  staged.push(...distribution.kind === "substituted" ? substituteFiles(distribution.name, files, SITE_PACKAGES) : files);
24172
24738
  installed3.push({ name: distribution.name, version: distribution.version });
24173
24739
  }
24174
24740
  commit(options.vfs, options.cred, staged);
24175
24741
  return { installed: installed3, skipped: solved.skipped };
24176
24742
  }
24177
- function requireArchive(distribution, bytes2) {
24178
- if (bytes2.length > 1 && bytes2[0] === 80 && bytes2[1] === 75) return;
24179
- const opening = new TextDecoder().decode(bytes2.subarray(0, 80)).replace(/\s+/g, " ").trim();
24743
+ function requireArchive(distribution, bytes3) {
24744
+ if (bytes3.length > 1 && bytes3[0] === 80 && bytes3[1] === 75) return;
24745
+ const opening = new TextDecoder().decode(bytes3.subarray(0, 80)).replace(/\s+/g, " ").trim();
24180
24746
  const looksLikeMarkup = /^<!doctype|^<html/i.test(opening);
24181
24747
  throw new Error(
24182
- `${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)}`)
24748
+ `${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)}`)
24183
24749
  );
24184
24750
  }
24185
24751
  async function download(client, distribution) {
24186
- const bytes2 = await client.bytes(distribution.url, { timeoutMs: 12e4 });
24187
- requireArchive(distribution, bytes2);
24188
- const mismatch = digestMismatch(distribution, bytes2);
24189
- if (!mismatch) return bytes2;
24752
+ const bytes3 = await client.bytes(distribution.url, { timeoutMs: 12e4 });
24753
+ requireArchive(distribution, bytes3);
24754
+ const mismatch = digestMismatch(distribution, bytes3);
24755
+ if (!mismatch) return bytes3;
24190
24756
  const fresh = await refetch(client, distribution);
24191
24757
  if (fresh && !digestMismatch(distribution, fresh)) {
24192
24758
  requireArchive(distribution, fresh);
@@ -24199,22 +24765,22 @@ async function download(client, distribution) {
24199
24765
  async function refetch(client, distribution) {
24200
24766
  const separator = distribution.url.includes("?") ? "&" : "?";
24201
24767
  try {
24202
- const bytes2 = await client.bytes(
24768
+ const bytes3 = await client.bytes(
24203
24769
  `${distribution.url}${separator}sha256=${distribution.sha256}`,
24204
24770
  { timeoutMs: 6e4 }
24205
24771
  );
24206
- return bytes2.length > 1 && bytes2[0] === 80 && bytes2[1] === 75 ? bytes2 : null;
24772
+ return bytes3.length > 1 && bytes3[0] === 80 && bytes3[1] === 75 ? bytes3 : null;
24207
24773
  } catch {
24208
24774
  return null;
24209
24775
  }
24210
24776
  }
24211
- function digestMismatch(distribution, bytes2) {
24777
+ function digestMismatch(distribution, bytes3) {
24212
24778
  if (!distribution.sha256) {
24213
24779
  throw new Error(
24214
24780
  `${distribution.filename} was published without a sha256 digest, so it cannot be verified`
24215
24781
  );
24216
24782
  }
24217
- const actual = [...sha256.sha256(bytes2)].map((b) => b.toString(16).padStart(2, "0")).join("");
24783
+ const actual = [...sha256.sha256(bytes3)].map((b) => b.toString(16).padStart(2, "0")).join("");
24218
24784
  if (actual === distribution.sha256) return null;
24219
24785
  return `${distribution.filename} failed verification: the index published sha256 ${distribution.sha256} but the download hashes to ${actual}.`;
24220
24786
  }
@@ -24344,9 +24910,9 @@ function outputFor(description, fallback) {
24344
24910
  return {
24345
24911
  write(data) {
24346
24912
  if (broken) return;
24347
- const bytes2 = typeof data === "string" ? new TextEncoder().encode(data) : data;
24348
- if (bytes2.length === 0) return;
24349
- queue.push(bytes2.slice());
24913
+ const bytes3 = typeof data === "string" ? new TextEncoder().encode(data) : data;
24914
+ if (bytes3.length === 0) return;
24915
+ queue.push(bytes3.slice());
24350
24916
  if (!active) done = pump();
24351
24917
  },
24352
24918
  end() {
@@ -25711,9 +26277,9 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25711
26277
  )];
25712
26278
  if (embedded) {
25713
26279
  const binary = atob(embedded);
25714
- const bytes2 = new Uint8Array(binary.length);
25715
- for (let i = 0; i < binary.length; i += 1) bytes2[i] = binary.charCodeAt(i);
25716
- return await read(new Response(bytes2));
26280
+ const bytes3 = new Uint8Array(binary.length);
26281
+ for (let i = 0; i < binary.length; i += 1) bytes3[i] = binary.charCodeAt(i);
26282
+ return await read(new Response(bytes3));
25717
26283
  }
25718
26284
  if (url.startsWith("sbx-wheel:")) {
25719
26285
  const filename = decodeURIComponent(url.slice("sbx-wheel:".length).replace(/^\/+/, ""));
@@ -25782,7 +26348,7 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25782
26348
  let attemptsLeft = 12;
25783
26349
  for (; ; ) {
25784
26350
  try {
25785
- const report = await installRequirements({
26351
+ const report2 = await installRequirements({
25786
26352
  index,
25787
26353
  client,
25788
26354
  vfs: ctx.vfs,
@@ -25803,11 +26369,11 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25803
26369
  }
25804
26370
  }
25805
26371
  });
25806
- for (const skipped of report.skipped) {
26372
+ for (const skipped of report2.skipped) {
25807
26373
  ctx.line(` Skipping ${skipped.name} (marker: ${skipped.marker})`);
25808
26374
  }
25809
26375
  ctx.line(
25810
- `Successfully installed ${report.installed.map((p) => `${p.name}-${p.version}`).join(" ")}`
26376
+ `Successfully installed ${report2.installed.map((p) => `${p.name}-${p.version}`).join(" ")}`
25811
26377
  );
25812
26378
  return 0;
25813
26379
  } catch (error) {
@@ -26193,11 +26759,11 @@ async function loadFactory() {
26193
26759
  function getCompiled() {
26194
26760
  compiled2 ??= (async () => {
26195
26761
  const { factory, wasm } = await loadFactory();
26196
- const bytes2 = wasm.buffer.slice(
26762
+ const bytes3 = wasm.buffer.slice(
26197
26763
  wasm.byteOffset,
26198
26764
  wasm.byteOffset + wasm.byteLength
26199
26765
  );
26200
- return { factory, module: await WebAssembly.compile(bytes2) };
26766
+ return { factory, module: await WebAssembly.compile(bytes3) };
26201
26767
  })();
26202
26768
  void compiled2.catch(() => compiled2 = null);
26203
26769
  return compiled2;
@@ -26345,18 +26911,18 @@ than a packet path, and socket calls report ENOTSUP.`,
26345
26911
  }
26346
26912
  if (module === void 0) return ctx.reportError(new UsageError("a module is required"));
26347
26913
  const abs = ctx.path(module);
26348
- let bytes2;
26914
+ let bytes3;
26349
26915
  try {
26350
- bytes2 = ctx.vfs.readFile(abs, ctx.cred);
26916
+ bytes3 = ctx.vfs.readFile(abs, ctx.cred);
26351
26917
  } catch (error) {
26352
26918
  ctx.reportError(error, abs);
26353
26919
  return EXIT_NOT_FOUND;
26354
26920
  }
26355
- if (!isWasmBinary(bytes2)) {
26921
+ if (!isWasmBinary(bytes3)) {
26356
26922
  return ctx.fail(`${abs}: not a WebAssembly module`, 126);
26357
26923
  }
26358
26924
  Object.assign(ctx.env, env2);
26359
- return await runWasi(ctx, bytes2, {
26925
+ return await runWasi(ctx, bytes3, {
26360
26926
  /* argv[0] is the path as the user wrote it, not the resolved one: a
26361
26927
  * program printing its own usage should echo what was typed. */
26362
26928
  argv: [module, ...rest],
@@ -26367,398 +26933,6 @@ than a packet path, and socket calls report ENOTSUP.`,
26367
26933
  function wasiCommands() {
26368
26934
  return [wasi];
26369
26935
  }
26370
- var platformBuffer = globalThis.Buffer;
26371
- addUint8ArraySupport(addBase64UrlSupport(index_js.Buffer));
26372
- var Buffer2 = platformBuffer ?? index_js.Buffer;
26373
- function addUint8ArraySupport(BufferClass) {
26374
- const target = BufferClass;
26375
- if (target.__sandboxedUint8Array) return BufferClass;
26376
- Object.defineProperty(target, "__sandboxedUint8Array", { value: true });
26377
- const asBuffer = (value) => value instanceof Uint8Array && !target.isBuffer(value) ? target.from(value.buffer, value.byteOffset, value.byteLength) : value;
26378
- for (const method of ["indexOf", "lastIndexOf", "includes"]) {
26379
- const original = target.prototype[method];
26380
- target.prototype[method] = function(value, ...rest) {
26381
- return original.call(this, asBuffer(value), ...rest);
26382
- };
26383
- }
26384
- const equals = target.prototype.equals;
26385
- target.prototype.equals = function(other) {
26386
- return equals.call(this, asBuffer(other));
26387
- };
26388
- return BufferClass;
26389
- }
26390
- function addBase64UrlSupport(BufferClass) {
26391
- const target = BufferClass;
26392
- if (target.__sandboxedBase64Url) return BufferClass;
26393
- Object.defineProperty(target, "__sandboxedBase64Url", { value: true });
26394
- const from = target.from.bind(target);
26395
- target.from = (value, encodingOrOffset, length) => from(value, normalizeEncoding(encodingOrOffset), length);
26396
- const byteLength = target.byteLength.bind(target);
26397
- target.byteLength = (value, encoding) => byteLength(value, normalizeEncoding(encoding));
26398
- const isEncoding = target.isEncoding?.bind(target);
26399
- if (isEncoding) target.isEncoding = (encoding) => encoding.toLowerCase() === "base64url" || isEncoding(encoding);
26400
- const toString = target.prototype.toString;
26401
- target.prototype.toString = function(encoding, start2, end) {
26402
- if (encoding?.toLowerCase() !== "base64url") return toString.call(this, encoding, start2, end);
26403
- return toString.call(this, "base64", start2, end).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
26404
- };
26405
- const write = target.prototype.write;
26406
- target.prototype.write = function(...args) {
26407
- const index = typeof args[1] === "string" ? 1 : typeof args[2] === "string" ? 2 : 3;
26408
- if (typeof args[index] === "string") args[index] = normalizeEncoding(args[index]);
26409
- return write.apply(this, args);
26410
- };
26411
- return BufferClass;
26412
- }
26413
- function normalizeEncoding(value) {
26414
- return typeof value === "string" && value.toLowerCase() === "base64url" ? "base64" : value;
26415
- }
26416
-
26417
- // src/pkg/clean-installer.ts
26418
- init_path();
26419
- var CleanPackageInstaller = class _CleanPackageInstaller {
26420
- constructor(volume, options = {}) {
26421
- this.volume = volume;
26422
- this.options = options;
26423
- this.registry = (options.registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
26424
- this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
26425
- }
26426
- volume;
26427
- options;
26428
- registry;
26429
- fetcher;
26430
- metadata = /* @__PURE__ */ new Map();
26431
- tarballs = /* @__PURE__ */ new Map();
26432
- /** Single-version manifests, for the fields the packument omits. */
26433
- details = /* @__PURE__ */ new Map();
26434
- forCwd(cwd) {
26435
- const installer = new _CleanPackageInstaller(this.volume, { ...this.options, cwd });
26436
- installer.metadata = this.metadata;
26437
- installer.tarballs = this.tarballs;
26438
- installer.details = this.details;
26439
- return installer;
26440
- }
26441
- async install(name, version = "latest", options = {}) {
26442
- const cwd = this.options.cwd ?? "/";
26443
- const manifest = await this.installAt(name, version || "latest", join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26444
- if (options.persist !== false) this.persist(cwd, name, version, options.persistDev === true);
26445
- return manifest;
26446
- }
26447
- async installFromManifest(path, options = {}) {
26448
- const project = this.readJson(path);
26449
- const cwd = dirname(path);
26450
- const dependencies = {
26451
- ...project.dependencies ?? {},
26452
- ...options.withDevDeps === false ? {} : project.devDependencies ?? {}
26453
- };
26454
- await this.prefetch(dependencies);
26455
- for (const [name, range] of Object.entries(dependencies)) {
26456
- await this.installAt(name, range, join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26457
- }
26458
- }
26459
- async installAt(name, range, modulesRoot, options, ancestry) {
26460
- const metadata = await this.getMetadata(name);
26461
- const version = resolveVersion(metadata, range);
26462
- const manifest = metadata.versions[version];
26463
- if (!manifest) throw new Error(`No matching version found for ${name}@${range}`);
26464
- const identity = `${name}@${version}`;
26465
- if (!supportsPlatform(manifest)) throw new IncompatiblePlatform(identity, "");
26466
- if (manifest.os?.length || manifest.cpu?.length) {
26467
- const detail = await this.platformDetail(name, version);
26468
- if (!platformListAllows(detail.libc, PLATFORM.libc)) {
26469
- throw new IncompatiblePlatform(identity, ` (needs ${detail.libc?.join(", ")})`);
26470
- }
26471
- if (detail.main?.endsWith(".node")) {
26472
- throw new IncompatiblePlatform(identity, " (native addon; this runtime cannot dlopen)");
26473
- }
26474
- }
26475
- const target = join(modulesRoot, name);
26476
- const installed3 = this.tryReadJson(join(target, "package.json"));
26477
- if (ancestry.has(identity)) return manifest;
26478
- if (installed3?.version !== version) {
26479
- options.onProgress?.(`Fetching ${identity}`);
26480
- const archive = await this.getTarball(manifest.dist.tarball);
26481
- verifyIntegrity(archive, manifest.dist.integrity, manifest.dist.shasum, identity);
26482
- this.removeIfPresent(target);
26483
- mkdirp2(this.volume, target);
26484
- extractNpmTarball(this.volume, archive, target);
26485
- options.onProgress?.(`Installed ${identity}`);
26486
- }
26487
- this.createBinLinks(manifest, target, modulesRoot);
26488
- if (name === "playwright-core") {
26489
- for (const executable of installVirtualPlaywrightBrowsers(this.volume, target)) {
26490
- options.onProgress?.(`Linked ${executable} to the virtual browser`);
26491
- }
26492
- }
26493
- const nextAncestry = new Set(ancestry).add(identity);
26494
- const childRoot = join(target, "node_modules");
26495
- const required = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name2]) => !(name2 in (manifest.optionalDependencies ?? {}))));
26496
- await this.prefetch(required);
26497
- for (const [dependency, dependencyRange] of Object.entries(required)) {
26498
- await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26499
- }
26500
- for (const [dependency, dependencyRange] of Object.entries(manifest.optionalDependencies ?? {})) {
26501
- try {
26502
- await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26503
- } catch (error) {
26504
- if (error instanceof IncompatiblePlatform) continue;
26505
- options.onProgress?.(`Skipped optional ${dependency}: ${error instanceof Error ? error.message : String(error)}`);
26506
- }
26507
- }
26508
- return manifest;
26509
- }
26510
- /**
26511
- * The `libc` and `main` fields, which the abbreviated packument leaves out.
26512
- *
26513
- * Fetched per version rather than as a full packument: the single-version
26514
- * document is a few kilobytes, while the full one for a popular package runs
26515
- * to megabytes. Only packages that already declare `os` or `cpu` ask for it,
26516
- * so an ordinary install of pure-JavaScript dependencies makes no extra
26517
- * requests at all — it is the prebuilt binaries, a handful per project, that
26518
- * need the answer.
26519
- *
26520
- * A failure here is not fatal. Being unable to read `libc` puts the check
26521
- * back where it was before this existed, which is worth strictly less than
26522
- * being right and strictly more than refusing to install.
26523
- */
26524
- async platformDetail(name, version) {
26525
- const key = `${name}@${version}`;
26526
- let request = this.details.get(key);
26527
- if (!request) {
26528
- request = (async () => {
26529
- try {
26530
- const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
26531
- const response = await this.fetcher(`${this.registry}/${encoded}/${version}`);
26532
- if (!response.ok) return {};
26533
- return await response.json();
26534
- } catch {
26535
- return {};
26536
- }
26537
- })();
26538
- this.details.set(key, request);
26539
- }
26540
- return request;
26541
- }
26542
- /** Overlap up to six sibling downloads; filesystem writes remain ordered. */
26543
- async prefetch(dependencies) {
26544
- const entries = Object.entries(dependencies);
26545
- let next = 0;
26546
- await Promise.all(Array.from({ length: Math.min(6, entries.length) }, async () => {
26547
- while (next < entries.length) {
26548
- const [name, range] = entries[next++];
26549
- try {
26550
- const metadata = await this.getMetadata(name);
26551
- const manifest = metadata.versions[resolveVersion(metadata, range)];
26552
- if (!manifest.os?.length && !manifest.cpu?.length && supportsPlatform(manifest)) {
26553
- await this.getTarball(manifest.dist.tarball);
26554
- }
26555
- } catch {
26556
- }
26557
- }
26558
- }));
26559
- }
26560
- async getMetadata(name) {
26561
- let request = this.metadata.get(name);
26562
- if (!request) {
26563
- request = (async () => {
26564
- const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
26565
- const response = await this.fetcher(`${this.registry}/${encoded}`, {
26566
- headers: { Accept: "application/vnd.npm.install-v1+json" }
26567
- });
26568
- if (!response.ok) throw new Error(`registry returned ${response.status} for ${name}`);
26569
- return await response.json();
26570
- })();
26571
- this.metadata.set(name, request);
26572
- void request.catch(() => {
26573
- this.metadata.delete(name);
26574
- });
26575
- }
26576
- return request;
26577
- }
26578
- async getTarball(url) {
26579
- let request = this.tarballs.get(url);
26580
- if (!request) {
26581
- request = (async () => {
26582
- const response = await this.fetcher(url);
26583
- if (!response.ok) throw new Error(`tarball returned ${response.status}: ${url}`);
26584
- return new Uint8Array(await response.arrayBuffer());
26585
- })();
26586
- this.tarballs.set(url, request);
26587
- void request.catch(() => {
26588
- this.tarballs.delete(url);
26589
- });
26590
- }
26591
- return request;
26592
- }
26593
- createBinLinks(manifest, target, modulesRoot) {
26594
- if (!manifest.bin) return;
26595
- const bins = typeof manifest.bin === "string" ? { [unscoped(manifest.name)]: manifest.bin } : manifest.bin;
26596
- const binDir = join(modulesRoot, ".bin");
26597
- mkdirp2(this.volume, binDir);
26598
- for (const [name, path] of Object.entries(bins)) {
26599
- const link = join(binDir, name);
26600
- this.removeIfPresent(link);
26601
- this.volume.symlinkSync(relative(binDir, join(target, path)), link);
26602
- }
26603
- }
26604
- persist(cwd, name, range, dev) {
26605
- const path = join(cwd, "package.json");
26606
- const manifest = this.tryReadJson(path) ?? {};
26607
- const key = dev ? "devDependencies" : "dependencies";
26608
- manifest[key] = { ...manifest[key] ?? {}, [name]: range === "latest" ? "*" : range };
26609
- this.volume.writeFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
26610
- }
26611
- removeIfPresent(path) {
26612
- let stat2;
26613
- try {
26614
- stat2 = this.volume.lstatSync(path);
26615
- } catch {
26616
- return;
26617
- }
26618
- if (!stat2.isDirectory()) return this.volume.unlinkSync(path);
26619
- for (const name of this.volume.readdirSync(path)) this.removeIfPresent(join(path, name));
26620
- this.volume.rmdirSync(path);
26621
- }
26622
- readJson(path) {
26623
- return JSON.parse(new TextDecoder().decode(this.volume.readFileSync(path)));
26624
- }
26625
- tryReadJson(path) {
26626
- try {
26627
- return this.readJson(path);
26628
- } catch {
26629
- return null;
26630
- }
26631
- }
26632
- };
26633
- var PLATFORM = { os: "linux", cpu: "x64", libc: "glibc" };
26634
- var IncompatiblePlatform = class extends Error {
26635
- constructor(identity, detail) {
26636
- super(`${identity} is not compatible with ${PLATFORM.os}/${PLATFORM.cpu}/${PLATFORM.libc}${detail}`);
26637
- this.name = "IncompatiblePlatform";
26638
- }
26639
- };
26640
- function supportsPlatform(manifest) {
26641
- return platformListAllows(manifest.os, PLATFORM.os) && platformListAllows(manifest.cpu, PLATFORM.cpu) && platformListAllows(manifest.libc, PLATFORM.libc);
26642
- }
26643
- function platformListAllows(values, current2) {
26644
- if (!values?.length) return true;
26645
- if (values.includes(`!${current2}`)) return false;
26646
- const positive = values.filter((value) => !value.startsWith("!"));
26647
- return positive.length === 0 || positive.includes(current2) || positive.includes("any");
26648
- }
26649
- function resolveVersion(metadata, range) {
26650
- const tag2 = metadata["dist-tags"]?.[range];
26651
- if (tag2) return tag2;
26652
- if (semver.valid(range) && metadata.versions[range]) return range;
26653
- const found2 = semver.maxSatisfying(Object.keys(metadata.versions), range === "latest" ? "*" : range, { includePrerelease: false });
26654
- if (!found2) throw new Error(`No matching version found for ${metadata.name}@${range}`);
26655
- return found2;
26656
- }
26657
- function verifyIntegrity(data, integrity, shasum, identity) {
26658
- if (integrity) {
26659
- const choices = integrity.trim().split(/\s+/);
26660
- for (const choice of choices) {
26661
- const dash = choice.indexOf("-");
26662
- const algorithm = choice.slice(0, dash);
26663
- const expected = choice.slice(dash + 1).replace(/\?.*$/, "");
26664
- const digest2 = algorithm === "sha512" ? sha512.sha512(data) : algorithm === "sha256" ? sha256.sha256(data) : null;
26665
- if (digest2 && Buffer2.from(digest2).toString("base64") === expected) return;
26666
- }
26667
- throw new Error(`Integrity check failed for ${identity}`);
26668
- }
26669
- if (shasum && Buffer2.from(sha1.sha1(data)).toString("hex") === shasum) return;
26670
- if (shasum) throw new Error(`Legacy checksum check failed for ${identity}`);
26671
- }
26672
- function extractNpmTarball(volume, compressed, destination) {
26673
- const tar2 = pako.ungzip(compressed);
26674
- let offset = 0;
26675
- let longPath = null;
26676
- let paxPath = null;
26677
- while (offset + 512 <= tar2.length) {
26678
- const header = tar2.subarray(offset, offset + 512);
26679
- if (header.every((byte) => byte === 0)) break;
26680
- const size = octal(header, 124, 12);
26681
- const type = String.fromCharCode(header[156] || 48);
26682
- const prefix = text(header, 345, 155);
26683
- let name = longPath ?? paxPath ?? [prefix, text(header, 0, 100)].filter(Boolean).join("/");
26684
- longPath = null;
26685
- paxPath = null;
26686
- const data = tar2.subarray(offset + 512, offset + 512 + size);
26687
- offset += 512 + Math.ceil(size / 512) * 512;
26688
- if (type === "L") {
26689
- longPath = new TextDecoder().decode(data).replace(/\0.*$/, "").trim();
26690
- continue;
26691
- }
26692
- if (type === "x" || type === "g") {
26693
- paxPath = parsePax(data).path ?? null;
26694
- continue;
26695
- }
26696
- name = stripPackageRoot(name);
26697
- if (!name) continue;
26698
- const target = safeTarget(destination, name);
26699
- const mode = octal(header, 100, 8) || 420;
26700
- if (type === "5") {
26701
- mkdirp2(volume, target, mode);
26702
- } else if (type === "2") {
26703
- mkdirp2(volume, dirname(target));
26704
- volume.symlinkSync(text(header, 157, 100), target);
26705
- } else if (type === "1") {
26706
- mkdirp2(volume, dirname(target));
26707
- volume.linkSync(safeTarget(destination, stripPackageRoot(text(header, 157, 100))), target);
26708
- } else if (type === "0" || type === "\0" || type === "7") {
26709
- mkdirp2(volume, dirname(target));
26710
- volume.writeFileSync(target, data.slice());
26711
- volume.chmodSync(target, mode);
26712
- }
26713
- }
26714
- }
26715
- function mkdirp2(volume, path, mode = 493) {
26716
- let current2 = "";
26717
- for (const part of segments(path)) {
26718
- current2 += `/${part}`;
26719
- try {
26720
- volume.mkdirSync(current2, { mode });
26721
- } catch (error) {
26722
- if (error.code !== "EEXIST") throw error;
26723
- if (!volume.lstatSync(current2).isDirectory()) throw error;
26724
- }
26725
- }
26726
- }
26727
- function safeTarget(destination, name) {
26728
- const clean2 = clean(`/${name}`).slice(1);
26729
- if (!clean2 || clean2 === ".." || clean2.startsWith("../") || name.startsWith("/")) throw new Error(`Unsafe path in package: ${name}`);
26730
- return join(destination, clean2);
26731
- }
26732
- function stripPackageRoot(name) {
26733
- const clean2 = name.replace(/^\.\//, "").replace(/\/$/, "");
26734
- const slash = clean2.indexOf("/");
26735
- return slash === -1 ? "" : clean2.slice(slash + 1);
26736
- }
26737
- function text(bytes2, start2, length) {
26738
- return new TextDecoder().decode(bytes2.subarray(start2, start2 + length)).replace(/\0.*$/, "").trim();
26739
- }
26740
- function octal(bytes2, start2, length) {
26741
- return parseInt(text(bytes2, start2, length).replace(/^0+/, "") || "0", 8);
26742
- }
26743
- function parsePax(data) {
26744
- const value = new TextDecoder().decode(data);
26745
- const result = {};
26746
- let offset = 0;
26747
- while (offset < value.length) {
26748
- const space = value.indexOf(" ", offset);
26749
- if (space < 0) break;
26750
- const length = Number(value.slice(offset, space));
26751
- if (!Number.isFinite(length) || length <= 0) break;
26752
- const record2 = value.slice(space + 1, offset + length - 1);
26753
- const equal2 = record2.indexOf("=");
26754
- if (equal2 > 0) result[record2.slice(0, equal2)] = record2.slice(equal2 + 1);
26755
- offset += length;
26756
- }
26757
- return result;
26758
- }
26759
- function unscoped(name) {
26760
- return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
26761
- }
26762
26936
  var DECLARES_EXPORTS = /(?:^|[\s;{)])(?:var|let|const|function|class)\s+exports\b/;
26763
26937
  var NAME = "exports";
26764
26938
  function renameShadowedExports(source) {
@@ -28471,8 +28645,8 @@ var VireoEngine = class _VireoEngine {
28471
28645
  const app = installedVireo(ctx);
28472
28646
  if (!app?.browserEngine) return null;
28473
28647
  const manifest = app.browserEngine;
28474
- const bytes2 = ctx.vfs.readFile(`${app.root}/${manifest.wasm}`, ctx.cred);
28475
- const loaded = await WebAssembly.instantiate(bytes2, {});
28648
+ const bytes3 = ctx.vfs.readFile(`${app.root}/${manifest.wasm}`, ctx.cred);
28649
+ const loaded = await WebAssembly.instantiate(bytes3, {});
28476
28650
  const instance = loaded instanceof WebAssembly.Instance ? loaded : loaded.instance;
28477
28651
  const wasm = instance.exports;
28478
28652
  for (const name of ["memory", "vireo_alloc", "vireo_load_html", "vireo_snapshot_pointer", "vireo_snapshot_length", "vireo_free_document"]) {
@@ -28496,11 +28670,11 @@ var VireoEngine = class _VireoEngine {
28496
28670
  this.wasm.vireo_free_document(handle);
28497
28671
  }
28498
28672
  }
28499
- copy(bytes2) {
28500
- if (!bytes2.length) return 0;
28501
- const pointer = this.wasm.vireo_alloc(bytes2.length);
28673
+ copy(bytes3) {
28674
+ if (!bytes3.length) return 0;
28675
+ const pointer = this.wasm.vireo_alloc(bytes3.length);
28502
28676
  if (!pointer) throw new Error("Vireo ran out of memory");
28503
- new Uint8Array(this.wasm.memory.buffer, pointer, bytes2.length).set(bytes2);
28677
+ new Uint8Array(this.wasm.memory.buffer, pointer, bytes3.length).set(bytes3);
28504
28678
  return pointer;
28505
28679
  }
28506
28680
  };
@@ -28686,8 +28860,8 @@ var SIGNATURE_PATH = "META/signature.json";
28686
28860
  var TRUSTED_KEYS_PATH = "/etc/pm/trusted-keys.json";
28687
28861
  var PackageError = class extends Error {
28688
28862
  };
28689
- async function openPackage(bytes2, trusted) {
28690
- const entries = readZip(bytes2);
28863
+ async function openPackage(bytes3, trusted) {
28864
+ const entries = readZip(bytes3);
28691
28865
  const byName = new Map(entries.map((entry) => [entry.name, entry]));
28692
28866
  const manifestEntry = byName.get(MANIFEST_PATH);
28693
28867
  if (!manifestEntry) {
@@ -28730,10 +28904,10 @@ async function openPackage(bytes2, trusted) {
28730
28904
  const trustedBy = trusted.find((key) => key.publicKey === signature.publicKey) ?? null;
28731
28905
  return { manifest, signature, entries, trustedBy };
28732
28906
  }
28733
- function parseManifest(bytes2) {
28907
+ function parseManifest(bytes3) {
28734
28908
  let parsed;
28735
28909
  try {
28736
- parsed = JSON.parse(new TextDecoder().decode(bytes2));
28910
+ parsed = JSON.parse(new TextDecoder().decode(bytes3));
28737
28911
  } catch (error) {
28738
28912
  throw new PackageError(`${MANIFEST_PATH} is not JSON: ${error.message}`);
28739
28913
  }
@@ -28749,10 +28923,10 @@ function parseManifest(bytes2) {
28749
28923
  }
28750
28924
  return manifest;
28751
28925
  }
28752
- function parseSignature(bytes2) {
28926
+ function parseSignature(bytes3) {
28753
28927
  let parsed;
28754
28928
  try {
28755
- parsed = JSON.parse(new TextDecoder().decode(bytes2));
28929
+ parsed = JSON.parse(new TextDecoder().decode(bytes3));
28756
28930
  } catch (error) {
28757
28931
  throw new PackageError(`${SIGNATURE_PATH} is not JSON: ${error.message}`);
28758
28932
  }
@@ -28800,16 +28974,16 @@ async function verifySignature(manifestBytes, signature) {
28800
28974
  intoBuffer(manifestBytes)
28801
28975
  );
28802
28976
  }
28803
- function intoBuffer(bytes2) {
28804
- return bytes2.slice().buffer;
28977
+ function intoBuffer(bytes3) {
28978
+ return bytes3.slice().buffer;
28805
28979
  }
28806
28980
  function base64ToBytes(text2) {
28807
28981
  const binary = atob(text2);
28808
- const bytes2 = new Uint8Array(binary.length);
28982
+ const bytes3 = new Uint8Array(binary.length);
28809
28983
  for (let index = 0; index < binary.length; index += 1) {
28810
- bytes2[index] = binary.charCodeAt(index);
28984
+ bytes3[index] = binary.charCodeAt(index);
28811
28985
  }
28812
- return bytes2;
28986
+ return bytes3;
28813
28987
  }
28814
28988
  async function fingerprint(publicKey) {
28815
28989
  const digest2 = await digestHex("sha256", base64ToBytes(publicKey));
@@ -29182,8 +29356,8 @@ function listInstalled2(ctx) {
29182
29356
  return 0;
29183
29357
  }
29184
29358
  for (const app of apps.slice().sort((a, b) => a.name.localeCompare(b.name))) {
29185
- const commands12 = app.installedBins.length > 0 ? ` (${app.installedBins.join(", ")})` : "";
29186
- ctx.line(`${app.name} ${app.version}${commands12}`);
29359
+ const commands13 = app.installedBins.length > 0 ? ` (${app.installedBins.join(", ")})` : "";
29360
+ ctx.line(`${app.name} ${app.version}${commands13}`);
29187
29361
  }
29188
29362
  return 0;
29189
29363
  }
@@ -29292,6 +29466,7 @@ function allCommands() {
29292
29466
  ...commands9,
29293
29467
  ...commands10,
29294
29468
  ...commands11,
29469
+ ...commands12,
29295
29470
  ...nodeCommands(),
29296
29471
  ...pythonCommands(),
29297
29472
  ...ffmpegCommands(),
@@ -29336,8 +29511,8 @@ var ContainerFs = class {
29336
29511
  return this.kernel.vfs;
29337
29512
  }
29338
29513
  async readFile(path, encoding) {
29339
- const bytes2 = this.vfs.readFile(clean(path));
29340
- return encoding ? new TextDecoder().decode(bytes2) : bytes2;
29514
+ const bytes3 = this.vfs.readFile(clean(path));
29515
+ return encoding ? new TextDecoder().decode(bytes3) : bytes3;
29341
29516
  }
29342
29517
  async writeFile(path, data, opts = {}) {
29343
29518
  const abs = clean(path);
@@ -29663,9 +29838,9 @@ var KernelChildProcess = class {
29663
29838
  this.exitCode = code;
29664
29839
  this.emit("exit", code);
29665
29840
  }
29666
- append(stream, text2) {
29841
+ append(stream, value, text2 = typeof value === "string" ? value : new TextDecoder().decode(value)) {
29667
29842
  this[stream] += text2;
29668
- this.emit(stream, text2);
29843
+ this.emit(stream, value);
29669
29844
  }
29670
29845
  };
29671
29846
  var ChildOutput = class {
@@ -29684,7 +29859,7 @@ var ChildOutput = class {
29684
29859
  write(data) {
29685
29860
  if (this.closedState) return;
29686
29861
  const text2 = typeof data === "string" ? data : this.decoder.decode(data, { stream: true });
29687
- if (text2) this.child.append(this.stream, text2);
29862
+ if (text2 || data instanceof Uint8Array) this.child.append(this.stream, data, text2);
29688
29863
  }
29689
29864
  end() {
29690
29865
  if (this.closedState) return;
@@ -31742,13 +31917,13 @@ var Z_NO_FLUSH = 0;
31742
31917
  var Z_SYNC_FLUSH = 2;
31743
31918
  var Z_FULL_FLUSH = 3;
31744
31919
  var Z_FINISH = 4;
31745
- var bytes = (data) => {
31920
+ var bytes2 = (data) => {
31746
31921
  if (typeof data === "string") return new Uint8Array(Buffer2.from(data, "utf8"));
31747
31922
  if (data instanceof ArrayBuffer) return new Uint8Array(data);
31748
31923
  return data;
31749
31924
  };
31750
31925
  function codec(run3) {
31751
- const sync2 = (data, options) => Buffer2.from(run3(bytes(data), options));
31926
+ const sync2 = (data, options) => Buffer2.from(run3(bytes2(data), options));
31752
31927
  const async_ = (data, options, callback) => {
31753
31928
  const done = typeof options === "function" ? options : callback;
31754
31929
  const settings = typeof options === "function" ? void 0 : options;
@@ -32098,6 +32273,8 @@ var VirtualServerResponse = class extends streamModule5__default.default.Writabl
32098
32273
  completed;
32099
32274
  constructor(request) {
32100
32275
  super();
32276
+ this.on("error", () => {
32277
+ });
32101
32278
  this.req = request;
32102
32279
  this.completed = new Promise((resolve3) => {
32103
32280
  this.resolve = resolve3;
@@ -32227,9 +32404,9 @@ var VirtualSocket = class extends streamModule5__default.default.Duplex {
32227
32404
  _read() {
32228
32405
  }
32229
32406
  _write(chunk, encoding, callback) {
32230
- const bytes2 = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk, encoding);
32407
+ const bytes3 = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk, encoding);
32231
32408
  try {
32232
- this.peer?.data(new Uint8Array(bytes2));
32409
+ this.peer?.data(new Uint8Array(bytes3));
32233
32410
  callback();
32234
32411
  } catch (error) {
32235
32412
  callback(error);
@@ -32253,9 +32430,9 @@ var VirtualSocket = class extends streamModule5__default.default.Duplex {
32253
32430
  this.peer = null;
32254
32431
  }
32255
32432
  /** Bytes arriving from the far end. */
32256
- deliver(bytes2) {
32433
+ deliver(bytes3) {
32257
32434
  if (this.destroyed || this.hungUp) return;
32258
- this.push(Buffer2.from(bytes2));
32435
+ this.push(Buffer2.from(bytes3));
32259
32436
  }
32260
32437
  /** The far end went away; let the server's stream end cleanly. */
32261
32438
  peerClosed() {
@@ -32410,7 +32587,7 @@ var VirtualHttpRouter = class {
32410
32587
  request.socket = socket;
32411
32588
  item.server.emit("upgrade", request, socket, Buffer2.alloc(0));
32412
32589
  return {
32413
- send: (bytes2) => socket.deliver(bytes2),
32590
+ send: (bytes3) => socket.deliver(bytes3),
32414
32591
  close: () => socket.peerClosed()
32415
32592
  };
32416
32593
  }
@@ -32636,9 +32813,9 @@ var VirtualClientRequest = class extends streamModule5__default.default.Writable
32636
32813
  }
32637
32814
  const result = remote ?? await this.router.request(this.target.port, init);
32638
32815
  const body_ = result.body;
32639
- const bytes2 = typeof body_ === "string" ? new TextEncoder().encode(body_) : body_ instanceof ArrayBuffer ? new Uint8Array(body_) : body_ ?? new Uint8Array();
32816
+ const bytes3 = typeof body_ === "string" ? new TextEncoder().encode(body_) : body_ instanceof ArrayBuffer ? new Uint8Array(body_) : body_ ?? new Uint8Array();
32640
32817
  const status = result.statusCode ?? 200;
32641
- return new VirtualClientResponse(status, result.statusMessage ?? STATUS_CODES[status] ?? "", lowercaseHeaders(result.headers), bytes2);
32818
+ return new VirtualClientResponse(status, result.statusMessage ?? STATUS_CODES[status] ?? "", lowercaseHeaders(result.headers), bytes3);
32642
32819
  }
32643
32820
  async viaFetch(body) {
32644
32821
  const fetchImpl = this.fetchImpl ?? globalThis.fetch;
@@ -32662,8 +32839,8 @@ var VirtualClientRequest = class extends streamModule5__default.default.Writable
32662
32839
  response.headers.forEach((value, key) => {
32663
32840
  received[key.toLowerCase()] = value;
32664
32841
  });
32665
- const bytes2 = new Uint8Array(await response.arrayBuffer());
32666
- return new VirtualClientResponse(response.status, response.statusText, received, bytes2);
32842
+ const bytes3 = new Uint8Array(await response.arrayBuffer());
32843
+ return new VirtualClientResponse(response.status, response.statusText, received, bytes3);
32667
32844
  }
32668
32845
  };
32669
32846
  function lowercaseHeaders(headers) {
@@ -32755,9 +32932,9 @@ function createVirtualFetch(router, options = {}) {
32755
32932
  for (const part of Array.isArray(value) ? value : [value]) responseHeaders.append(name, String(part));
32756
32933
  }
32757
32934
  const raw = result.body;
32758
- const bytes2 = typeof raw === "string" ? new TextEncoder().encode(raw) : raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw ?? new Uint8Array();
32935
+ const bytes3 = typeof raw === "string" ? new TextEncoder().encode(raw) : raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw ?? new Uint8Array();
32759
32936
  const nullBody = status === 204 || status === 205 || status === 304 || request.method === "HEAD";
32760
- return new Response(nullBody ? null : new Uint8Array(bytes2), {
32937
+ return new Response(nullBody ? null : new Uint8Array(bytes3), {
32761
32938
  status,
32762
32939
  statusText: result.statusMessage ?? STATUS_CODES[status] ?? "",
32763
32940
  headers: responseHeaders
@@ -33003,7 +33180,7 @@ function createTestModule(host2) {
33003
33180
  });
33004
33181
  };
33005
33182
  const hasOnly = (node2) => Boolean(node2.options.only) || node2.kind === "suite" && node2.children.some(hasOnly);
33006
- const report = (depth, outcome, name, started, detail) => {
33183
+ const report2 = (depth, outcome, name, started, detail) => {
33007
33184
  if (tap()) {
33008
33185
  tapIndex += 1;
33009
33186
  const ok2 = outcome === "fail" ? "not ok" : "ok";
@@ -33050,13 +33227,13 @@ ${indent(detail, 4)}
33050
33227
  if (runOnly && !options.only) return true;
33051
33228
  if (options.skip) {
33052
33229
  record2("skip", display);
33053
- report(depth, "skip", name, started);
33230
+ report2(depth, "skip", name, started);
33054
33231
  return true;
33055
33232
  }
33056
33233
  if (!fn) {
33057
33234
  const outcome = options.todo ? "todo" : "skip";
33058
33235
  record2(outcome, display);
33059
- report(depth, outcome, name, started);
33236
+ report2(depth, outcome, name, started);
33060
33237
  return true;
33061
33238
  }
33062
33239
  const controller = new AbortController();
@@ -33120,21 +33297,21 @@ ${indent(detail, 4)}
33120
33297
  }
33121
33298
  if (skipped) {
33122
33299
  record2("skip", display);
33123
- report(depth, "skip", name, started);
33300
+ report2(depth, "skip", name, started);
33124
33301
  return true;
33125
33302
  }
33126
33303
  if (error !== void 0) {
33127
33304
  if (todo) {
33128
33305
  record2("todo", display);
33129
- report(depth, "todo", name, started);
33306
+ report2(depth, "todo", name, started);
33130
33307
  return true;
33131
33308
  }
33132
33309
  record2("fail", display, error);
33133
- report(depth, "fail", name, started, errorText(error));
33310
+ report2(depth, "fail", name, started, errorText(error));
33134
33311
  return false;
33135
33312
  }
33136
33313
  record2(todo ? "todo" : "pass", display);
33137
- report(depth, todo ? "todo" : "pass", name, started);
33314
+ report2(depth, todo ? "todo" : "pass", name, started);
33138
33315
  return true;
33139
33316
  };
33140
33317
  const runSuite = async (suite, depth, runOnly) => {
@@ -33149,7 +33326,7 @@ ${indent(detail, 4)}
33149
33326
  `);
33150
33327
  if (suite.options.skip) {
33151
33328
  for (const child of suite.children) if (child.kind === "test") record2("skip", fullName(child));
33152
- report(depth, "skip", suite.name, started);
33329
+ report2(depth, "skip", suite.name, started);
33153
33330
  return true;
33154
33331
  }
33155
33332
  }
@@ -33161,10 +33338,10 @@ ${indent(detail, 4)}
33161
33338
  for (const child of suite.children) {
33162
33339
  if (child.kind === "test") {
33163
33340
  record2("cancelled", fullName(child), error);
33164
- report(depth + (isRoot ? 0 : 1), "cancelled", child.name, started, errorText(error));
33341
+ report2(depth + (isRoot ? 0 : 1), "cancelled", child.name, started, errorText(error));
33165
33342
  }
33166
33343
  }
33167
- if (!isRoot) report(depth, "fail", suite.name, started);
33344
+ if (!isRoot) report2(depth, "fail", suite.name, started);
33168
33345
  return false;
33169
33346
  }
33170
33347
  const only = runOnly || settings().only === true && suite.children.some(hasOnly);
@@ -33544,7 +33721,7 @@ var ChildProcess = class extends EventEmitter4__default.default {
33544
33721
  this.stdin = new streamModule5__default.default.Writable({
33545
33722
  write: (chunk, _encoding, done) => {
33546
33723
  try {
33547
- handle.sendStdin(typeof chunk === "string" ? chunk : Buffer2.from(chunk).toString("utf8"));
33724
+ handle.sendStdin(typeof chunk === "string" ? chunk : new Uint8Array(chunk));
33548
33725
  } catch {
33549
33726
  }
33550
33727
  done();
@@ -33563,8 +33740,8 @@ var ChildProcess = class extends EventEmitter4__default.default {
33563
33740
  const pipe = this.stdio[event.fd];
33564
33741
  pipe?.push(Buffer2.from(event.text));
33565
33742
  });
33566
- handle.on("stdout", (text2) => this.stdout.write(text2));
33567
- handle.on("stderr", (text2) => this.stderr.write(text2));
33743
+ handle.on("stdout", (value) => this.stdout.write(typeof value === "string" ? value : Buffer2.from(value)));
33744
+ handle.on("stderr", (value) => this.stderr.write(typeof value === "string" ? value : Buffer2.from(value)));
33568
33745
  handle.on("exit", (code) => this.finish(code));
33569
33746
  referenceChanged(1);
33570
33747
  try {
@@ -34551,7 +34728,7 @@ function createCoreModules(options) {
34551
34728
  });
34552
34729
  processObject.stdin = stdin;
34553
34730
  Reflect.deleteProperty(processObject, "browser");
34554
- const fs = createFsModule(volume, () => cwd, options.stdinPath, defer);
34731
+ const fs = createFsModule(volume, () => cwd, options.stdinPath, defer, stdin);
34555
34732
  processObject.loadEnvFile = (path2 = ".env") => {
34556
34733
  const parsed = parseEnv(fs.readFileSync(path2, "utf8"));
34557
34734
  for (const [key, value] of Object.entries(parsed)) {
@@ -34923,7 +35100,7 @@ function createPathModule(cwd) {
34923
35100
  path.default = path;
34924
35101
  return path;
34925
35102
  }
34926
- function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35103
+ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask, stdin) {
34927
35104
  const fds = /* @__PURE__ */ new Map();
34928
35105
  let nextFd = 3;
34929
35106
  if (stdinPath) fds.set(0, { path: stdinPath, position: 0, flags: "r" });
@@ -34934,7 +35111,7 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
34934
35111
  if (typeof value !== "string") throw new TypeError("path must be a string, Buffer, or URL");
34935
35112
  return value.startsWith("/") ? clean(value) : resolve(cwd(), value);
34936
35113
  };
34937
- const bytes2 = (data, encoding) => {
35114
+ const bytes3 = (data, encoding) => {
34938
35115
  if (typeof data === "string") return new Uint8Array(Buffer2.from(data, encoding));
34939
35116
  if (Buffer2.isBuffer(data) || data instanceof Uint8Array) return new Uint8Array(data);
34940
35117
  if (data instanceof ArrayBuffer) return new Uint8Array(data);
@@ -34996,12 +35173,12 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
34996
35173
  readFileSync: (path, options) => read(path, typeof options === "object" && options ? options.encoding : options),
34997
35174
  writeFileSync: (path, data, options) => {
34998
35175
  const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
34999
- volume.writeFileSync(abs(path), bytes2(data, encoding ?? void 0));
35176
+ volume.writeFileSync(abs(path), bytes3(data, encoding ?? void 0));
35000
35177
  if (typeof options === "object" && options?.mode !== void 0) volume.chmodSync(abs(path), options.mode);
35001
35178
  },
35002
35179
  appendFileSync: (path, data, options) => {
35003
35180
  const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
35004
- volume.appendFileSync(abs(path), bytes2(data, encoding ?? void 0));
35181
+ volume.appendFileSync(abs(path), bytes3(data, encoding ?? void 0));
35005
35182
  },
35006
35183
  existsSync: (path) => {
35007
35184
  try {
@@ -35092,7 +35269,7 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35092
35269
  offset = 0;
35093
35270
  length = data.length;
35094
35271
  }
35095
- const input = bytes2(data);
35272
+ const input = bytes3(data);
35096
35273
  const chunk = input.subarray(offset ?? 0, (offset ?? 0) + (length ?? input.length));
35097
35274
  const size = volume.lstatSync(file3.path).size;
35098
35275
  const append = file3.flags.startsWith("a") || (position ?? file3.position) >= size;
@@ -35217,9 +35394,9 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35217
35394
  const self = this;
35218
35395
  const append = () => {
35219
35396
  try {
35220
- const bytes3 = typeof chunk === "string" ? Buffer2.from(chunk, encoding) : chunk;
35221
- volume.appendFileSync(self.path, new Uint8Array(bytes3));
35222
- self.bytesWritten += bytes3.length;
35397
+ const bytes4 = typeof chunk === "string" ? Buffer2.from(chunk, encoding) : chunk;
35398
+ volume.appendFileSync(self.path, new Uint8Array(bytes4));
35399
+ self.bytesWritten += bytes4.length;
35223
35400
  done();
35224
35401
  } catch (error) {
35225
35402
  done(error);
@@ -35420,6 +35597,57 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35420
35597
  ({ offset, length, position } = options);
35421
35598
  }
35422
35599
  const start2 = offset ?? 0;
35600
+ if (fd === 0 && stdin) {
35601
+ const requested = length ?? buffer.byteLength - start2;
35602
+ const finish = (chunk) => {
35603
+ const source = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk);
35604
+ const count = Math.min(requested, source.byteLength);
35605
+ buffer.set(source.subarray(0, count), start2);
35606
+ if (count < source.byteLength && typeof stdin.unshift === "function") {
35607
+ stdin.unshift(source.subarray(count));
35608
+ }
35609
+ cb(null, count, buffer);
35610
+ };
35611
+ const available2 = stdin.read();
35612
+ if (available2 !== null) {
35613
+ defer(() => finish(available2));
35614
+ return;
35615
+ }
35616
+ if (stdin.readableEnded || stdin.destroyed) {
35617
+ defer(() => cb(null, 0, buffer));
35618
+ return;
35619
+ }
35620
+ let settled = false;
35621
+ const cleanup = () => {
35622
+ stdin.removeListener("readable", onReadable);
35623
+ stdin.removeListener("end", onEnd);
35624
+ stdin.removeListener("error", onError);
35625
+ };
35626
+ const onReadable = () => {
35627
+ if (settled) return;
35628
+ const chunk = stdin.read();
35629
+ if (chunk === null) return;
35630
+ settled = true;
35631
+ cleanup();
35632
+ finish(chunk);
35633
+ };
35634
+ const onEnd = () => {
35635
+ if (settled) return;
35636
+ settled = true;
35637
+ cleanup();
35638
+ cb(null, 0, buffer);
35639
+ };
35640
+ const onError = (error) => {
35641
+ if (settled) return;
35642
+ settled = true;
35643
+ cleanup();
35644
+ cb(error);
35645
+ };
35646
+ stdin.on("readable", onReadable);
35647
+ stdin.once("end", onEnd);
35648
+ stdin.once("error", onError);
35649
+ return;
35650
+ }
35423
35651
  runThenCall(() => [fs.readSync(fd, buffer, start2, length ?? buffer.byteLength - start2, position ?? null), buffer], cb);
35424
35652
  };
35425
35653
  fs.write = (fd, data, ...rest) => {
@@ -35511,8 +35739,8 @@ function createBufferBuiltin() {
35511
35739
  }
35512
35740
  },
35513
35741
  isAscii: (input) => {
35514
- const bytes2 = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
35515
- for (const byte of bytes2) if (byte > 127) return false;
35742
+ const bytes3 = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
35743
+ for (const byte of bytes3) if (byte > 127) return false;
35516
35744
  return true;
35517
35745
  }
35518
35746
  };
@@ -36151,37 +36379,37 @@ var MemoryVolume = class {
36151
36379
  writeFileSync(path, data) {
36152
36380
  const key = this.key(path);
36153
36381
  this.requireParent(key, "open");
36154
- const bytes2 = typeof data === "string" ? encoder7.encode(data) : data.slice();
36382
+ const bytes3 = typeof data === "string" ? encoder7.encode(data) : data.slice();
36155
36383
  const current2 = this.entries.get(key);
36156
36384
  if (current2?.kind === "directory") throw new VolumeError("EISDIR", "open", key);
36157
36385
  if (current2?.kind === "symlink") throw new VolumeError("EINVAL", "open", key);
36158
36386
  if (current2) {
36159
- current2.data = bytes2;
36387
+ current2.data = bytes3;
36160
36388
  this.touchChanged(current2, true);
36161
36389
  } else {
36162
- this.entries.set(key, this.inode("file", 438, bytes2));
36390
+ this.entries.set(key, this.inode("file", 438, bytes3));
36163
36391
  }
36164
36392
  }
36165
36393
  appendFileSync(path, data) {
36166
36394
  const key = this.key(path);
36167
- const bytes2 = typeof data === "string" ? encoder7.encode(data) : data;
36395
+ const bytes3 = typeof data === "string" ? encoder7.encode(data) : data;
36168
36396
  const current2 = this.entries.get(key);
36169
- if (!current2) return this.writeFileSync(key, bytes2);
36397
+ if (!current2) return this.writeFileSync(key, bytes3);
36170
36398
  if (current2.kind !== "file") throw new VolumeError(current2.kind === "directory" ? "EISDIR" : "EINVAL", "open", key);
36171
36399
  const length = current2.data.length;
36172
- const needed = length + bytes2.length;
36400
+ const needed = length + bytes3.length;
36173
36401
  const backing = current2.data.buffer;
36174
36402
  const ownsTail = current2.data.byteOffset === 0 && backing instanceof ArrayBuffer && backing.byteLength >= needed && appendCapacity.get(current2) === backing;
36175
36403
  if (ownsTail) {
36176
36404
  const grown = new Uint8Array(backing, 0, needed);
36177
- grown.set(bytes2, length);
36405
+ grown.set(bytes3, length);
36178
36406
  current2.data = grown;
36179
36407
  } else {
36180
36408
  const capacity = Math.max(needed, length * 2, 64 * 1024);
36181
36409
  const buffer = new ArrayBuffer(capacity);
36182
36410
  const grown = new Uint8Array(buffer, 0, needed);
36183
36411
  grown.set(current2.data);
36184
- grown.set(bytes2, length);
36412
+ grown.set(bytes3, length);
36185
36413
  current2.data = grown;
36186
36414
  appendCapacity.set(current2, buffer);
36187
36415
  }
@@ -36754,9 +36982,9 @@ var MirroringVolume = class {
36754
36982
  } catch {
36755
36983
  }
36756
36984
  try {
36757
- const bytes2 = mirror.readFileSync(source);
36985
+ const bytes3 = mirror.readFileSync(source);
36758
36986
  this.ensureDirectory(dirname(destination));
36759
- this.inner.writeFileSync(destination, bytes2);
36987
+ this.inner.writeFileSync(destination, bytes3);
36760
36988
  } catch {
36761
36989
  }
36762
36990
  };
@@ -37138,9 +37366,9 @@ var OutboundTcp = class {
37138
37366
  const bridge = new VirtualTcpConnection({ address, port }, { address: local.address, port: local.port });
37139
37367
  guest.pairWith(bridge);
37140
37368
  bridge.pairWith(guest);
37141
- host2.onData((bytes2) => {
37369
+ host2.onData((bytes3) => {
37142
37370
  try {
37143
- bridge.write(bytes2);
37371
+ bridge.write(bytes3);
37144
37372
  } catch {
37145
37373
  host2.close();
37146
37374
  }
@@ -37195,9 +37423,9 @@ function createNodeTcpDialer() {
37195
37423
  let onClose = null;
37196
37424
  let closed = false;
37197
37425
  socket.on("data", (chunk) => {
37198
- const bytes2 = new Uint8Array(chunk);
37199
- if (onData) onData(bytes2);
37200
- else pending.push(bytes2);
37426
+ const bytes3 = new Uint8Array(chunk);
37427
+ if (onData) onData(bytes3);
37428
+ else pending.push(bytes3);
37201
37429
  });
37202
37430
  const finish = () => {
37203
37431
  if (closed) return;
@@ -37216,8 +37444,8 @@ function createNodeTcpDialer() {
37216
37444
  socket.on("connect", () => {
37217
37445
  socket.setNoDelay(true);
37218
37446
  resolve3({
37219
- write(bytes2) {
37220
- socket.write(bytes2);
37447
+ write(bytes3) {
37448
+ socket.write(bytes3);
37221
37449
  },
37222
37450
  end() {
37223
37451
  socket.end();
@@ -37269,8 +37497,7 @@ function translate(error, host2, port) {
37269
37497
 
37270
37498
  // src/worker/local-runtime-pod.ts
37271
37499
  var WASM_ALIASES = {
37272
- esbuild: "esbuild-wasm",
37273
- rollup: "@rollup/wasm-node"
37500
+ ...RUNTIME_PACKAGE_FALLBACKS
37274
37501
  };
37275
37502
  var ProcessExit = class extends Error {
37276
37503
  constructor(code) {
@@ -37430,7 +37657,7 @@ var PodChildProcess = class {
37430
37657
  /* The child is launched asynchronously, but a parent may write and close
37431
37658
  * its input synchronously right after spawning. Holding both until the
37432
37659
  * child exists is what keeps `echo hi | child` from losing the `hi`. */
37433
- pendingInput = "";
37660
+ pendingInput = [];
37434
37661
  inputEnded = false;
37435
37662
  on(event, listener) {
37436
37663
  let set = this.listeners.get(event);
@@ -37454,15 +37681,13 @@ var PodChildProcess = class {
37454
37681
  (child) => {
37455
37682
  this.child = child;
37456
37683
  if (this.cancelled) child.kill();
37457
- if (this.pendingInput !== "") {
37458
- child.write(this.pendingInput);
37459
- this.pendingInput = "";
37460
- }
37684
+ for (const chunk of this.pendingInput.splice(0)) child.write(chunk);
37461
37685
  if (this.inputEnded) child.endInput?.();
37462
- child.on("output", (chunk) => {
37686
+ const outputEvent = child.rawOutput ? "raw-output" : "output";
37687
+ child.on(outputEvent, (chunk) => {
37463
37688
  const text2 = typeof chunk === "string" ? chunk : this.outText.decode(chunk, { stream: true });
37464
37689
  this.stdout += text2;
37465
- this.emit("stdout", text2);
37690
+ this.emit("stdout", chunk);
37466
37691
  });
37467
37692
  child.on("error", (chunk) => {
37468
37693
  const text2 = typeof chunk === "string" ? chunk : this.errText.decode(chunk, { stream: true });
@@ -37484,7 +37709,7 @@ var PodChildProcess = class {
37484
37709
  }
37485
37710
  sendStdin(data) {
37486
37711
  if (this.child) this.child.write(data);
37487
- else this.pendingInput += data;
37712
+ else this.pendingInput.push(data);
37488
37713
  }
37489
37714
  /** Signal EOF, so a child reading stdin to the end can finish. */
37490
37715
  endStdin() {
@@ -37844,14 +38069,14 @@ ${headers.join("\r\n")}\r
37844
38069
  `);
37845
38070
  connection.write(request);
37846
38071
  if (body.length) connection.write(body);
37847
- const bytes2 = [];
38072
+ const bytes3 = [];
37848
38073
  let combined = new Uint8Array();
37849
38074
  for (; ; ) {
37850
38075
  try {
37851
38076
  const chunk = connection.read(64 * 1024);
37852
38077
  if (chunk.length === 0) break;
37853
- bytes2.push(chunk);
37854
- combined = joinBytes(bytes2);
38078
+ bytes3.push(chunk);
38079
+ combined = joinBytes(bytes3);
37855
38080
  const headerEnd = findBytes(combined, new Uint8Array([13, 10, 13, 10]));
37856
38081
  if (headerEnd < 0) continue;
37857
38082
  const headerText = new TextDecoder().decode(combined.subarray(0, headerEnd));
@@ -37917,11 +38142,11 @@ function findBytes(haystack, needle) {
37917
38142
  }
37918
38143
  return -1;
37919
38144
  }
37920
- function parseHttpResponse(bytes2) {
38145
+ function parseHttpResponse(bytes3) {
37921
38146
  const marker = new Uint8Array([13, 10, 13, 10]);
37922
- const headerEnd = findBytes(bytes2, marker);
38147
+ const headerEnd = findBytes(bytes3, marker);
37923
38148
  if (headerEnd < 0) throw new Error("Python server returned an incomplete HTTP response");
37924
- const text2 = new TextDecoder().decode(bytes2.subarray(0, headerEnd));
38149
+ const text2 = new TextDecoder().decode(bytes3.subarray(0, headerEnd));
37925
38150
  const lines = text2.split("\r\n");
37926
38151
  const status = /HTTP\/\d\.\d\s+(\d+)(?:\s+(.*))?/.exec(lines.shift() ?? "");
37927
38152
  if (!status) throw new Error("Python server returned an invalid HTTP status line");
@@ -37930,7 +38155,7 @@ function parseHttpResponse(bytes2) {
37930
38155
  const separator = line.indexOf(":");
37931
38156
  if (separator > 0) headers[line.slice(0, separator).toLowerCase()] = line.slice(separator + 1).trim();
37932
38157
  }
37933
- let body = bytes2.slice(headerEnd + marker.length);
38158
+ let body = bytes3.slice(headerEnd + marker.length);
37934
38159
  if (CHUNKED.test(headers["transfer-encoding"] ?? "")) {
37935
38160
  body = decodeChunked(body).body;
37936
38161
  delete headers["transfer-encoding"];
@@ -37944,19 +38169,19 @@ function parseHttpResponse(bytes2) {
37944
38169
  };
37945
38170
  }
37946
38171
  var CHUNKED = /^(?:transfer-encoding:.*)?\bchunked\b/im;
37947
- function decodeChunked(bytes2) {
38172
+ function decodeChunked(bytes3) {
37948
38173
  const parts = [];
37949
38174
  const crlf = new Uint8Array([13, 10]);
37950
38175
  for (let at = 0; ; ) {
37951
- const lineEnd = findBytes(bytes2.subarray(at), crlf);
38176
+ const lineEnd = findBytes(bytes3.subarray(at), crlf);
37952
38177
  if (lineEnd < 0) return { body: joinBytes(parts), complete: false };
37953
- const header = new TextDecoder().decode(bytes2.subarray(at, at + lineEnd)).split(";")[0].trim();
38178
+ const header = new TextDecoder().decode(bytes3.subarray(at, at + lineEnd)).split(";")[0].trim();
37954
38179
  const size = /^[0-9a-f]+$/i.test(header) ? Number.parseInt(header, 16) : Number.NaN;
37955
38180
  if (!Number.isInteger(size)) throw new Error("Python server returned an invalid chunked response");
37956
38181
  at += lineEnd + crlf.length;
37957
38182
  if (size === 0) return { body: joinBytes(parts), complete: true };
37958
- if (at + size + crlf.length > bytes2.length) return { body: joinBytes(parts), complete: false };
37959
- parts.push(bytes2.subarray(at, at + size));
38183
+ if (at + size + crlf.length > bytes3.length) return { body: joinBytes(parts), complete: false };
38184
+ parts.push(bytes3.subarray(at, at + size));
37960
38185
  at += size + crlf.length;
37961
38186
  }
37962
38187
  }
@@ -38139,7 +38364,7 @@ var WorkerProcess = class extends EventEmitter4__default.default {
38139
38364
  */
38140
38365
  write(data) {
38141
38366
  if (this.inheritedInput) {
38142
- this.inheritedInput.sendStdin(typeof data === "string" ? data : new TextDecoder().decode(data));
38367
+ this.inheritedInput.sendStdin(data);
38143
38368
  return;
38144
38369
  }
38145
38370
  if (this.started) this.worker.postMessage({ type: "stdin", data });
@@ -38303,7 +38528,9 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38303
38528
  this.startChild(worker, children, message, ownedChildren);
38304
38529
  return;
38305
38530
  case "child-stdin":
38306
- children.get(message.id)?.sendStdin?.(String(message.data));
38531
+ children.get(message.id)?.sendStdin?.(
38532
+ message.data instanceof Uint8Array ? message.data : String(message.data)
38533
+ );
38307
38534
  return;
38308
38535
  case "child-stdin-end":
38309
38536
  children.get(message.id)?.endStdin?.();
@@ -38345,20 +38572,22 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38345
38572
  return;
38346
38573
  }
38347
38574
  });
38348
- worker.postMessage({
38349
- type: "start",
38350
- buffers,
38351
- script,
38352
- cwd,
38353
- env: env2,
38354
- argv: Array.isArray(options.argv) ? options.argv : ["/usr/bin/node", script, ...args.slice(1)],
38355
- aliases: this.aliases,
38356
- ...typeof options.stdinPath === "string" ? { stdinPath: options.stdinPath } : {},
38357
- ...options.interactiveStdin ? { interactiveStdin: true } : {},
38358
- ...options.tty ? { tty: true } : {},
38359
- ...this.networkPolicy ? { network: this.networkPolicy } : {}
38360
- });
38361
- process2.begin();
38575
+ setTimeout(() => {
38576
+ worker.postMessage({
38577
+ type: "start",
38578
+ buffers,
38579
+ script,
38580
+ cwd,
38581
+ env: env2,
38582
+ argv: Array.isArray(options.argv) ? options.argv : ["/usr/bin/node", script, ...args.slice(1)],
38583
+ aliases: this.aliases,
38584
+ ...typeof options.stdinPath === "string" ? { stdinPath: options.stdinPath } : {},
38585
+ ...options.interactiveStdin ? { interactiveStdin: true } : {},
38586
+ ...options.tty ? { tty: true } : {},
38587
+ ...this.networkPolicy ? { network: this.networkPolicy } : {}
38588
+ });
38589
+ process2.begin();
38590
+ }, 0);
38362
38591
  return process2;
38363
38592
  }
38364
38593
  /** Start an asynchronous child on the host's behalf and relay its events. */
@@ -38396,16 +38625,20 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38396
38625
  handle.on("exit", () => owned.delete(handle));
38397
38626
  let stdout = "";
38398
38627
  let stderr = "";
38628
+ const stdoutDecoder = new TextDecoder();
38629
+ const stderrDecoder = new TextDecoder();
38399
38630
  const live = request.inheritStdio ? streamTo : null;
38400
38631
  const restoreInput = live?.inheritInput(handle);
38401
38632
  if (restoreInput) handle.on("exit", restoreInput);
38402
- handle.on("stdout", (text2) => {
38633
+ handle.on("stdout", (value) => {
38634
+ const text2 = typeof value === "string" ? value : stdoutDecoder.decode(value, { stream: true });
38403
38635
  stdout += text2;
38404
- live?.output(text2);
38636
+ live?.output(value);
38405
38637
  });
38406
- handle.on("stderr", (text2) => {
38638
+ handle.on("stderr", (value) => {
38639
+ const text2 = typeof value === "string" ? value : stderrDecoder.decode(value, { stream: true });
38407
38640
  stderr += text2;
38408
- live?.error(text2);
38641
+ live?.error(value);
38409
38642
  });
38410
38643
  handle.on("exit", (code) => resolve3({ status: code, stdout, stderr, signal: null }));
38411
38644
  handle.exec();
@@ -38476,8 +38709,8 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38476
38709
  const id = this.nextRequestId++;
38477
38710
  this.upgraded.set(id, socket);
38478
38711
  socket.on("data", (chunk) => {
38479
- const bytes2 = new Uint8Array(chunk);
38480
- worker.postMessage({ type: "ws-data", id, data: bytes2 });
38712
+ const bytes3 = new Uint8Array(chunk);
38713
+ worker.postMessage({ type: "ws-data", id, data: bytes3 });
38481
38714
  });
38482
38715
  const drop = () => {
38483
38716
  if (!this.upgraded.delete(id)) return;
@@ -38617,7 +38850,8 @@ var Container = class _Container {
38617
38850
  const network = {
38618
38851
  allowOutbound: opts.network?.allowOutbound ?? false,
38619
38852
  allowedHosts: opts.network?.allowedHosts ?? null,
38620
- ...opts.network?.proxy ? { proxy: opts.network.proxy } : {}
38853
+ ...opts.network?.proxy ? { proxy: opts.network.proxy } : {},
38854
+ ...opts.network?.secrets ? { secrets: opts.network.secrets } : {}
38621
38855
  };
38622
38856
  const podOptions = {
38623
38857
  workdir: opts.cwd ?? "/",
@@ -38933,17 +39167,17 @@ var Container = class _Container {
38933
39167
  body: init.body ?? null
38934
39168
  });
38935
39169
  const bodyRaw = res.body;
38936
- const bytes2 = bodyRaw instanceof Uint8Array ? bodyRaw : (
39170
+ const bytes3 = bodyRaw instanceof Uint8Array ? bodyRaw : (
38937
39171
  // The binary dispatcher answers with an ArrayBuffer.
38938
39172
  bodyRaw instanceof ArrayBuffer ? new Uint8Array(bodyRaw) : typeof bodyRaw === "string" ? new TextEncoder().encode(bodyRaw) : new Uint8Array(0)
38939
39173
  );
38940
- const body = typeof bodyRaw === "string" ? bodyRaw : new TextDecoder().decode(bytes2);
39174
+ const body = typeof bodyRaw === "string" ? bodyRaw : new TextDecoder().decode(bytes3);
38941
39175
  return {
38942
39176
  status: res.statusCode ?? 200,
38943
39177
  statusText: res.statusMessage ?? "",
38944
39178
  headers: res.headers ?? {},
38945
39179
  body,
38946
- bytes: bytes2,
39180
+ bytes: bytes3,
38947
39181
  json() {
38948
39182
  return JSON.parse(body);
38949
39183
  }
@@ -39576,7 +39810,7 @@ function serveContainerOn(port, box) {
39576
39810
  headers: request.headers,
39577
39811
  ...request.body ? { body: new Uint8Array(request.body) } : {}
39578
39812
  });
39579
- const bytes2 = response.bytes.slice();
39813
+ const bytes3 = response.bytes.slice();
39580
39814
  port.postMessage(
39581
39815
  {
39582
39816
  id: request.id,
@@ -39584,10 +39818,10 @@ function serveContainerOn(port, box) {
39584
39818
  status: response.status,
39585
39819
  statusText: response.statusText,
39586
39820
  headers: response.headers,
39587
- body: bytes2.buffer
39821
+ body: bytes3.buffer
39588
39822
  }
39589
39823
  },
39590
- [bytes2.buffer]
39824
+ [bytes3.buffer]
39591
39825
  );
39592
39826
  } catch (error) {
39593
39827
  const message = new TextEncoder().encode(error instanceof Error ? error.message : String(error));
@@ -39673,8 +39907,8 @@ async function createPreview(box, options = {}) {
39673
39907
  Number(data.port),
39674
39908
  { method: "GET", path: data.path ?? "/", headers: data.headers ?? {} },
39675
39909
  {
39676
- data: (bytes2) => {
39677
- const carrier = bytes2.slice().buffer;
39910
+ data: (bytes3) => {
39911
+ const carrier = bytes3.slice().buffer;
39678
39912
  reply({ type: WS_DATA, id, data: carrier }, [carrier]);
39679
39913
  },
39680
39914
  close: () => {
@@ -39756,8 +39990,8 @@ function gitFilesystem(ctx) {
39756
39990
  const encoding = (opts) => typeof opts === "string" ? opts : opts?.encoding;
39757
39991
  return { promises: {
39758
39992
  async readFile(path, opts) {
39759
- const bytes2 = Buffer2.from(ctx.vfs.readFile(ctx.path(path), ctx.cred));
39760
- return encoding(opts) ? bytes2.toString(encoding(opts)) : bytes2;
39993
+ const bytes3 = Buffer2.from(ctx.vfs.readFile(ctx.path(path), ctx.cred));
39994
+ return encoding(opts) ? bytes3.toString(encoding(opts)) : bytes3;
39761
39995
  },
39762
39996
  async writeFile(path, data, opts) {
39763
39997
  ctx.vfs.writeFile(ctx.path(path), data, { cred: ctx.cred, mode: opts?.mode });
@@ -39949,8 +40183,8 @@ var signed = (value) => {
39949
40183
  }
39950
40184
  };
39951
40185
  var str = (s) => {
39952
- const bytes2 = [...new TextEncoder().encode(s)];
39953
- return [...leb(bytes2.length), ...bytes2];
40186
+ const bytes3 = [...new TextEncoder().encode(s)];
40187
+ return [...leb(bytes3.length), ...bytes3];
39954
40188
  };
39955
40189
  var section = (id, data) => [id, ...leb(data.length), ...data];
39956
40190
  function compileInstruction({ op, next }) {