sandboxedjs 0.1.81 → 0.1.83

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
@@ -20238,7 +20238,7 @@ var wheels_default = {
20238
20238
 
20239
20239
  // package.json
20240
20240
  var package_default = {
20241
- version: "0.1.81"};
20241
+ version: "0.1.83"};
20242
20242
 
20243
20243
  // src/python/config.ts
20244
20244
  function runtimeModuleUrl() {
@@ -25216,7 +25216,21 @@ function makeNpmAlias(name, path) {
25216
25216
  exec: ["exec", ...rest],
25217
25217
  list: ["ls", ...rest],
25218
25218
  why: ["ls", ...rest],
25219
- dlx: ["exec", ...rest]
25219
+ dlx: ["exec", ...rest],
25220
+ /* Verbs of the package manager itself, never script names. Tools ask
25221
+ * them in passing — Next resolves its download registry with
25222
+ * `yarn config get registry` whenever yarn is on PATH — and running
25223
+ * them as scripts failed with "could not read package.json". */
25224
+ config: ["config", ...rest],
25225
+ cache: ["cache", ...rest],
25226
+ root: ["root", ...rest],
25227
+ prefix: ["prefix", ...rest],
25228
+ ping: ["ping", ...rest],
25229
+ whoami: ["whoami", ...rest],
25230
+ init: ["init", ...rest],
25231
+ create: ["create", ...rest],
25232
+ uninstall: ["uninstall", ...rest],
25233
+ rm: ["uninstall", ...rest]
25220
25234
  };
25221
25235
  if (subcommand === void 0) return npm.run({ ...ctx, args: ["install"], argv: [name, "install"] });
25222
25236
  if (subcommand === "-v" || subcommand === "--version") {
@@ -25828,6 +25842,49 @@ var CommonJsEngine = class {
25828
25842
  this.globals = { ...options.globals };
25829
25843
  this.aliases = { ...options.aliases };
25830
25844
  this.overrides = { ...options.overrides };
25845
+ const engine = this;
25846
+ this.moduleApi = function Module(id = "", parent = null) {
25847
+ Object.assign(this, { id, filename: id, exports: {}, loaded: false, parent, children: [] });
25848
+ };
25849
+ Object.assign(this.moduleApi, this.builtins.module);
25850
+ this.moduleApi.Module = this.moduleApi;
25851
+ this.moduleApi._extensions = {
25852
+ ".js": (module, filename) => this.evaluate(module, this.readText(filename)),
25853
+ ".json": (module, filename) => {
25854
+ module.exports = JSON.parse(this.readText(filename));
25855
+ },
25856
+ ".node": (_module, filename) => {
25857
+ throw dlopenFailed(filename);
25858
+ }
25859
+ };
25860
+ this.moduleApi._cache = new Proxy(/* @__PURE__ */ Object.create(null), {
25861
+ get: (_target, key) => typeof key === "string" ? this.cache.get(key) : void 0,
25862
+ set: (_target, key, value) => {
25863
+ this.cache.set(String(key), value);
25864
+ return true;
25865
+ },
25866
+ deleteProperty: (_target, key) => this.cache.delete(String(key)),
25867
+ ownKeys: () => [...this.cache.keys()],
25868
+ getOwnPropertyDescriptor: (_target, key) => this.cache.has(String(key)) ? { enumerable: true, configurable: true, writable: true, value: this.cache.get(String(key)) } : void 0
25869
+ });
25870
+ this.moduleApi._resolveFilename = (request, parent) => this.resolve(request, parent?.filename || join(this.cwd, "__entry__.js"));
25871
+ this.moduleApi.prototype.require = function(request) {
25872
+ const filename = engine.moduleApi._resolveFilename(request, this);
25873
+ const builtin = engine.builtin(filename, this);
25874
+ if (builtin.found) return builtin.value;
25875
+ const target = engine.load(filename, this, false);
25876
+ if (target.pending) throw requireOfAsyncModule(request);
25877
+ return target.exports;
25878
+ };
25879
+ this.moduleApi.prototype._compile = function(source, filename) {
25880
+ this.filename = filename;
25881
+ engine.evaluate(this, source);
25882
+ };
25883
+ this.moduleApi.createRequire = (filename) => {
25884
+ const path = String(filename).startsWith("file:") ? pathFromFileUrl(String(filename)) : String(filename);
25885
+ if (!path.startsWith("/")) throw new TypeError("createRequire requires an absolute path or file URL");
25886
+ return this.makeRequire(Object.assign(new this.moduleApi(path), { filename: path }));
25887
+ };
25831
25888
  }
25832
25889
  volume;
25833
25890
  cache = /* @__PURE__ */ new Map();
@@ -25840,6 +25897,7 @@ var CommonJsEngine = class {
25840
25897
  /** `package.json` per directory; resolution reads them constantly. */
25841
25898
  manifests = /* @__PURE__ */ new Map();
25842
25899
  evaluationDepth = 0;
25900
+ moduleApi;
25843
25901
  /**
25844
25902
  * Is a module body running synchronously right now?
25845
25903
  *
@@ -25876,7 +25934,7 @@ var CommonJsEngine = class {
25876
25934
  specifier = pathFromFileUrl(specifier);
25877
25935
  }
25878
25936
  const builtin = this.builtin(specifier);
25879
- if (builtin.found) return specifier.replace(/^node:/, "");
25937
+ if (builtin.found) return specifier;
25880
25938
  if (specifier.startsWith("#")) {
25881
25939
  const found = this.resolveImports(specifier, importer, kind);
25882
25940
  if (found) return found;
@@ -25909,17 +25967,14 @@ var CommonJsEngine = class {
25909
25967
  parent,
25910
25968
  children: []
25911
25969
  };
25970
+ Object.setPrototypeOf(module, this.moduleApi.prototype);
25912
25971
  this.cache.set(filename, module);
25913
25972
  parent?.children.push(module);
25914
25973
  if (isMain) this.main = module;
25915
25974
  try {
25916
- if (filename.endsWith(".node")) {
25917
- throw dlopenFailed(filename);
25918
- } else if (filename.endsWith(".json")) {
25919
- module.exports = JSON.parse(this.readText(filename));
25920
- } else {
25921
- this.evaluate(module, this.readText(filename));
25922
- }
25975
+ const extension = extname(filename);
25976
+ const loader = this.moduleApi._extensions[extension] ?? this.moduleApi._extensions[".js"];
25977
+ loader(module, filename);
25923
25978
  module.loaded = true;
25924
25979
  return module;
25925
25980
  } catch (error) {
@@ -25972,15 +26027,12 @@ ${code}
25972
26027
  /** The `require` a module sees, complete with `resolve`, `cache` and `main`. */
25973
26028
  makeRequire(module) {
25974
26029
  const localRequire = ((specifier) => {
25975
- const builtin = this.builtin(specifier, module);
25976
- if (builtin.found) return builtin.value;
25977
- const target = this.load(this.resolve(specifier, module.filename, "require"), module, false);
25978
- if (target.pending) throw requireOfAsyncModule(specifier);
25979
- return target.exports;
26030
+ return this.moduleApi.prototype.require.call(module, specifier);
25980
26031
  });
25981
- localRequire.resolve = (specifier) => this.resolve(specifier, module.filename, "require");
26032
+ localRequire.resolve = (specifier) => this.moduleApi._resolveFilename(specifier, module);
25982
26033
  Object.defineProperty(localRequire, "main", { get: () => this.main });
25983
- localRequire.cache = Object.fromEntries(this.cache);
26034
+ localRequire.cache = this.moduleApi._cache;
26035
+ localRequire.extensions = this.moduleApi._extensions;
25984
26036
  return localRequire;
25985
26037
  }
25986
26038
  /**
@@ -26155,12 +26207,7 @@ ${code}
26155
26207
  if (prefixOnly || !Object.prototype.hasOwnProperty.call(this.builtins, name)) {
26156
26208
  return Object.prototype.hasOwnProperty.call(this.overrides, specifier) ? { found: true, value: this.overrides[specifier] } : { found: false, value: void 0 };
26157
26209
  }
26158
- if (name === "module" && importer) {
26159
- return {
26160
- found: true,
26161
- value: { ...this.builtins.module, createRequire: () => this.makeRequire(importer) }
26162
- };
26163
- }
26210
+ if (name === "module") return { found: true, value: this.moduleApi };
26164
26211
  return { found: true, value: this.builtins[name] };
26165
26212
  }
26166
26213
  exists(path) {
@@ -26268,6 +26315,108 @@ function splitSpecifier(specifier) {
26268
26315
  return { name: parts.slice(0, size).join("/"), subpath: parts.slice(size).join("/") };
26269
26316
  }
26270
26317
 
26318
+ // src/node/diagnostics-channel.ts
26319
+ function createDiagnosticsChannel() {
26320
+ const channels2 = /* @__PURE__ */ new Map();
26321
+ class Channel {
26322
+ constructor(name) {
26323
+ this.name = name;
26324
+ }
26325
+ name;
26326
+ listeners = /* @__PURE__ */ new Set();
26327
+ get hasSubscribers() {
26328
+ return this.listeners.size > 0;
26329
+ }
26330
+ subscribe(fn) {
26331
+ if (typeof fn !== "function") throw new TypeError("subscriber must be a function");
26332
+ this.listeners.add(fn);
26333
+ }
26334
+ unsubscribe(fn) {
26335
+ return this.listeners.delete(fn);
26336
+ }
26337
+ publish(message) {
26338
+ for (const fn of [...this.listeners]) {
26339
+ try {
26340
+ fn(message, this.name);
26341
+ } catch (error) {
26342
+ queueMicrotask(() => {
26343
+ throw error;
26344
+ });
26345
+ }
26346
+ }
26347
+ }
26348
+ }
26349
+ const channel = (name) => {
26350
+ if (typeof name !== "string" && typeof name !== "symbol") throw new TypeError("channel name must be a string or symbol");
26351
+ let result = channels2.get(name);
26352
+ if (!result) {
26353
+ result = new Channel(name);
26354
+ channels2.set(name, result);
26355
+ }
26356
+ return result;
26357
+ };
26358
+ return {
26359
+ Channel,
26360
+ channel,
26361
+ hasSubscribers: (name) => channels2.get(name)?.hasSubscribers ?? false,
26362
+ subscribe: (name, fn) => channel(name).subscribe(fn),
26363
+ unsubscribe: (name, fn) => channels2.get(name)?.unsubscribe(fn) ?? false
26364
+ };
26365
+ }
26366
+
26367
+ // src/node/ipc-channel.ts
26368
+ var IPC_CHANNEL_ENV = "SANDBOXEDJS_IPC_CHANNEL";
26369
+ var channels = /* @__PURE__ */ new Map();
26370
+ var closedChannels = /* @__PURE__ */ new Set();
26371
+ function newIpcChannelId() {
26372
+ const random = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : Math.random().toString(36).slice(2);
26373
+ return `ipc-${random}`;
26374
+ }
26375
+ var hostIpcTransport = {
26376
+ attach(id, side, onMessage, onDisconnect) {
26377
+ let channel = channels.get(id);
26378
+ if (!channel && !closedChannels.has(id)) {
26379
+ channel = { parent: { backlog: [] }, child: { backlog: [] }, closed: false };
26380
+ channels.set(id, channel);
26381
+ }
26382
+ if (!channel || channel.closed) {
26383
+ queueMicrotask(onDisconnect);
26384
+ return { send: () => {
26385
+ }, disconnect: () => {
26386
+ } };
26387
+ }
26388
+ const own = channel[side];
26389
+ const other = channel[side === "parent" ? "child" : "parent"];
26390
+ own.deliver = onMessage;
26391
+ own.disconnected = onDisconnect;
26392
+ for (const message of own.backlog.splice(0)) queueMicrotask(() => onMessage(message));
26393
+ return {
26394
+ send(message) {
26395
+ if (channel.closed) return;
26396
+ const copy = message === void 0 ? void 0 : JSON.parse(JSON.stringify(message));
26397
+ if (other.deliver) {
26398
+ const deliver = other.deliver;
26399
+ setTimeout(() => {
26400
+ if (!channel.closed) deliver(copy);
26401
+ }, 0);
26402
+ } else {
26403
+ other.backlog.push(copy);
26404
+ }
26405
+ },
26406
+ disconnect() {
26407
+ if (channel.closed) return;
26408
+ channel.closed = true;
26409
+ channels.delete(id);
26410
+ closedChannels.add(id);
26411
+ for (const end of [channel.parent, channel.child]) {
26412
+ const notify = end.disconnected;
26413
+ if (notify) setTimeout(notify, 0);
26414
+ }
26415
+ }
26416
+ };
26417
+ }
26418
+ };
26419
+
26271
26420
  // src/node/readable-from.ts
26272
26421
  function createReadableFrom(Readable) {
26273
26422
  return function from(source, options = {}) {
@@ -26317,6 +26466,132 @@ function installReadableFrom(streamModule5) {
26317
26466
  streamModule5.Readable.from = createReadableFrom(streamModule5.Readable);
26318
26467
  }
26319
26468
 
26469
+ // src/node/parse-args.ts
26470
+ function argError(code, message) {
26471
+ return Object.assign(new TypeError(message), { code });
26472
+ }
26473
+ function parseArgs2(config2 = {}) {
26474
+ const args = config2.args ?? globalThis.process?.argv?.slice(2) ?? [];
26475
+ const options = config2.options ?? {};
26476
+ const strict = config2.strict ?? true;
26477
+ const allowPositionals = config2.allowPositionals ?? !strict;
26478
+ const allowNegative = config2.allowNegative ?? false;
26479
+ const byShort = /* @__PURE__ */ new Map();
26480
+ for (const [name, option] of Object.entries(options)) {
26481
+ if (option.type !== "string" && option.type !== "boolean") {
26482
+ throw argError("ERR_INVALID_ARG_VALUE", `The property 'options.${name}.type' must be one of: 'string', 'boolean'`);
26483
+ }
26484
+ if (option.short !== void 0) {
26485
+ if (option.short.length !== 1) {
26486
+ throw argError("ERR_INVALID_ARG_VALUE", `The property 'options.${name}.short' must be a single character`);
26487
+ }
26488
+ byShort.set(option.short, name);
26489
+ }
26490
+ }
26491
+ const tokens = [];
26492
+ const takesValue = (name) => options[name]?.type === "string";
26493
+ for (let index = 0; index < args.length; index++) {
26494
+ const arg = args[index];
26495
+ if (arg === "--") {
26496
+ tokens.push({ kind: "option-terminator", index });
26497
+ for (let rest = index + 1; rest < args.length; rest++) tokens.push({ kind: "positional", index: rest, value: args[rest] });
26498
+ break;
26499
+ }
26500
+ if (arg.startsWith("--") && arg.length > 2) {
26501
+ const equals = arg.indexOf("=");
26502
+ if (equals !== -1) {
26503
+ tokens.push({ kind: "option", name: arg.slice(2, equals), rawName: arg.slice(0, equals), index, value: arg.slice(equals + 1), inlineValue: true });
26504
+ continue;
26505
+ }
26506
+ const name = arg.slice(2);
26507
+ if (takesValue(name) && index + 1 < args.length) {
26508
+ tokens.push({ kind: "option", name, rawName: arg, index, value: args[index + 1], inlineValue: false });
26509
+ index++;
26510
+ } else {
26511
+ tokens.push({ kind: "option", name, rawName: arg, index, value: void 0, inlineValue: void 0 });
26512
+ }
26513
+ continue;
26514
+ }
26515
+ if (arg.startsWith("-") && arg.length > 1) {
26516
+ for (let at = 1; at < arg.length; at++) {
26517
+ const short = arg[at];
26518
+ const name = byShort.get(short) ?? short;
26519
+ if (takesValue(name)) {
26520
+ if (at + 1 < arg.length) {
26521
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: arg.slice(at + 1), inlineValue: true });
26522
+ } else if (index + 1 < args.length) {
26523
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: args[index + 1], inlineValue: false });
26524
+ index++;
26525
+ } else {
26526
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: void 0, inlineValue: void 0 });
26527
+ }
26528
+ break;
26529
+ }
26530
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: void 0, inlineValue: void 0 });
26531
+ }
26532
+ continue;
26533
+ }
26534
+ tokens.push({ kind: "positional", index, value: arg });
26535
+ }
26536
+ const values = /* @__PURE__ */ Object.create(null);
26537
+ const positionals = [];
26538
+ const store = (name, value) => {
26539
+ if (options[name]?.multiple) {
26540
+ const list = values[name] ?? [];
26541
+ list.push(value);
26542
+ values[name] = list;
26543
+ } else {
26544
+ values[name] = value;
26545
+ }
26546
+ };
26547
+ for (const token of tokens) {
26548
+ if (token.kind === "option-terminator") continue;
26549
+ if (token.kind === "positional") {
26550
+ if (!allowPositionals) {
26551
+ throw argError("ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL", `Unexpected argument '${token.value}'. This command does not take positional arguments`);
26552
+ }
26553
+ positionals.push(token.value);
26554
+ continue;
26555
+ }
26556
+ let name = token.name;
26557
+ let negated = false;
26558
+ if (allowNegative && name.startsWith("no-") && token.rawName.startsWith("--") && options[name.slice(3)]?.type === "boolean") {
26559
+ name = name.slice(3);
26560
+ negated = true;
26561
+ }
26562
+ const option = options[name];
26563
+ if (!option) {
26564
+ if (strict) {
26565
+ throw argError(
26566
+ "ERR_PARSE_ARGS_UNKNOWN_OPTION",
26567
+ `Unknown option '${token.rawName}'${allowPositionals ? `. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- ${JSON.stringify(token.rawName)}'` : ""}`
26568
+ );
26569
+ }
26570
+ store(name, token.value ?? true);
26571
+ continue;
26572
+ }
26573
+ if (option.type === "string") {
26574
+ if (token.value === void 0) {
26575
+ if (strict) throw argError("ERR_PARSE_ARGS_INVALID_OPTION_VALUE", `Option '${token.rawName} <value>' argument missing`);
26576
+ store(name, true);
26577
+ continue;
26578
+ }
26579
+ store(name, token.value);
26580
+ } else {
26581
+ if (token.inlineValue && strict) {
26582
+ throw argError("ERR_PARSE_ARGS_INVALID_OPTION_VALUE", `Option '${token.rawName}' does not take an argument`);
26583
+ }
26584
+ store(name, !negated);
26585
+ }
26586
+ }
26587
+ for (const [name, option] of Object.entries(options)) {
26588
+ if (option.default !== void 0 && values[name] === void 0) {
26589
+ values[name] = Array.isArray(option.default) ? option.default.slice() : option.default;
26590
+ }
26591
+ }
26592
+ return config2.tokens ? { values, positionals, tokens } : { values, positionals };
26593
+ }
26594
+
26320
26595
  // src/node/util-module.ts
26321
26596
  var customInspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
26322
26597
  var promisifyCustom = /* @__PURE__ */ Symbol.for("nodejs.util.promisify.custom");
@@ -26345,8 +26620,9 @@ function render(value, depth, seen, options) {
26345
26620
  if (value === null) return "null";
26346
26621
  const object = value;
26347
26622
  const custom = object[customInspect];
26348
- if (typeof custom === "function") {
26349
- return String(custom.call(object, depth, options));
26623
+ if (options.customInspect !== false && typeof custom === "function") {
26624
+ const result = custom.call(object, depth, options, inspect);
26625
+ if (result !== object) return typeof result === "string" ? result : render(result, depth, seen, options);
26350
26626
  }
26351
26627
  if (seen.has(object)) return "[Circular *1]";
26352
26628
  if (depth < 0) return Array.isArray(object) ? "[Array]" : "[Object]";
@@ -26681,6 +26957,7 @@ var legacy = {
26681
26957
  inspect.custom = customInspect;
26682
26958
  var utilModule = {
26683
26959
  parseEnv,
26960
+ parseArgs: parseArgs2,
26684
26961
  format,
26685
26962
  formatWithOptions,
26686
26963
  inspect,
@@ -28447,20 +28724,10 @@ function concat6(parts) {
28447
28724
  return joined;
28448
28725
  }
28449
28726
  var ChildProcess = class extends EventEmitter4__default.default {
28450
- stdout = new streamModule4__default.default.PassThrough();
28451
- stderr = new streamModule4__default.default.PassThrough();
28452
- stdin;
28453
- stdio;
28454
- pid;
28455
- exitCode = null;
28456
- signalCode = null;
28457
- killed = false;
28458
- spawnfile;
28459
- spawnargs;
28460
- handle;
28461
- settled = false;
28462
- constructor(handle, file3, args) {
28727
+ constructor(handle, file3, args, referenceChanged = () => {
28728
+ }) {
28463
28729
  super();
28730
+ this.referenceChanged = referenceChanged;
28464
28731
  this.handle = handle;
28465
28732
  this.pid = handle.pid;
28466
28733
  this.spawnfile = file3;
@@ -28485,31 +28752,90 @@ var ChildProcess = class extends EventEmitter4__default.default {
28485
28752
  handle.on("stdout", (text2) => this.stdout.write(text2));
28486
28753
  handle.on("stderr", (text2) => this.stderr.write(text2));
28487
28754
  handle.on("exit", (code) => this.finish(code));
28488
- handle.exec();
28755
+ referenceChanged(1);
28756
+ try {
28757
+ handle.exec();
28758
+ } catch (error) {
28759
+ this.unref();
28760
+ throw error;
28761
+ }
28489
28762
  }
28763
+ referenceChanged;
28764
+ stdout = new streamModule4__default.default.PassThrough();
28765
+ stderr = new streamModule4__default.default.PassThrough();
28766
+ stdin;
28767
+ stdio;
28768
+ pid;
28769
+ exitCode = null;
28770
+ signalCode = null;
28771
+ killed = false;
28772
+ spawnfile;
28773
+ spawnargs;
28774
+ handle;
28775
+ settled = false;
28776
+ referenced = true;
28490
28777
  kill(signal = "SIGTERM") {
28491
28778
  this.killed = true;
28492
28779
  this.handle.kill(typeof signal === "number" ? "SIGTERM" : signal);
28493
28780
  return true;
28494
28781
  }
28495
28782
  ref() {
28783
+ if (!this.settled && !this.referenced) {
28784
+ this.referenced = true;
28785
+ this.referenceChanged(1);
28786
+ }
28496
28787
  return this;
28497
28788
  }
28498
28789
  unref() {
28790
+ if (this.referenced) {
28791
+ this.referenced = false;
28792
+ this.referenceChanged(-1);
28793
+ }
28499
28794
  return this;
28500
28795
  }
28501
- disconnect() {
28502
- this.emit("disconnect");
28503
- }
28504
- /** No IPC channel exists, and reporting that honestly beats a silent drop. */
28505
- send() {
28506
- return false;
28796
+ channel;
28797
+ channelOpen = false;
28798
+ /** Open the parent's end of a `fork` channel. */
28799
+ attachChannel(transport, id) {
28800
+ this.channelOpen = true;
28801
+ this.channel = transport.attach(
28802
+ id,
28803
+ "parent",
28804
+ (message) => this.emit("message", message, void 0),
28805
+ () => this.channelClosed()
28806
+ );
28507
28807
  }
28508
28808
  get connected() {
28509
- return false;
28809
+ return this.channelOpen;
28810
+ }
28811
+ /** `send(message[, sendHandle][, options][, callback])`, as Node spells it. */
28812
+ send(message, ...rest) {
28813
+ const callback = rest.find((value) => typeof value === "function");
28814
+ if (!this.channel || !this.channelOpen) {
28815
+ const error = Object.assign(new Error("Channel closed"), { code: "ERR_IPC_CHANNEL_CLOSED" });
28816
+ if (callback) queueMicrotask(() => callback(error));
28817
+ else queueMicrotask(() => this.emit("error", error));
28818
+ return false;
28819
+ }
28820
+ this.channel.send(message);
28821
+ if (callback) queueMicrotask(() => callback(null));
28822
+ return true;
28823
+ }
28824
+ disconnect() {
28825
+ if (!this.channelOpen) return;
28826
+ this.channel?.disconnect();
28827
+ this.channelClosed();
28828
+ }
28829
+ channelClosed() {
28830
+ if (!this.channelOpen) return;
28831
+ this.channelOpen = false;
28832
+ this.emit("disconnect");
28510
28833
  }
28511
28834
  finish(code) {
28512
28835
  if (this.settled) return;
28836
+ this.channel?.disconnect();
28837
+ this.channelClosed();
28838
+ this.unref();
28513
28839
  this.settled = true;
28514
28840
  this.exitCode = code;
28515
28841
  this.stdout.end();
@@ -28518,7 +28844,7 @@ var ChildProcess = class extends EventEmitter4__default.default {
28518
28844
  queueMicrotask(() => this.emit("close", code, null));
28519
28845
  }
28520
28846
  };
28521
- function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv = () => ({})) {
28847
+ function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv = () => ({}), lifecycle = {}) {
28522
28848
  const environmentFor = (options) => options.env ? { ...options.env } : defaultEnv();
28523
28849
  const throughShell = (command, options) => {
28524
28850
  const shell = typeof options.shell === "string" ? options.shell : "/bin/sh";
@@ -28529,16 +28855,24 @@ function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv
28529
28855
  if (stdio === "ignore") return true;
28530
28856
  return Array.isArray(stdio) && stdio[0] === "ignore";
28531
28857
  };
28858
+ const wantsChannel = (options) => Array.isArray(options.stdio) && options.stdio.includes("ipc");
28532
28859
  const start2 = (file3, args, options) => {
28533
28860
  const resolved = options.shell ? throughShell([file3, ...args].join(" "), options) : { file: file3, args };
28861
+ const channelId = wantsChannel(options) && lifecycle.ipc ? newIpcChannelId() : void 0;
28534
28862
  const handle = spawnChild({
28535
28863
  command: resolved.file,
28536
28864
  args: resolved.args,
28537
28865
  cwd: options.cwd ?? defaultCwd(),
28538
- env: environmentFor(options),
28866
+ env: channelId ? { ...environmentFor(options), [IPC_CHANNEL_ENV]: channelId } : environmentFor(options),
28867
+ ...options.stdio === "inherit" || Array.isArray(options.stdio) && options.stdio[0] === "inherit" ? { inheritStdio: true } : {},
28539
28868
  ...stdinIgnored(options) ? { stdinIgnored: true } : {}
28540
28869
  });
28541
- return new ChildProcess(handle, resolved.file, resolved.args);
28870
+ const child = new ChildProcess(handle, resolved.file, resolved.args, lifecycle.referenceChanged);
28871
+ if (channelId && lifecycle.ipc) child.attachChannel(lifecycle.ipc, channelId);
28872
+ const inherited = (index) => options.stdio === "inherit" || Array.isArray(options.stdio) && options.stdio[index] === "inherit";
28873
+ if (inherited(1)) child.stdout.on("data", (chunk) => lifecycle.stdout?.(chunk.toString()));
28874
+ if (inherited(2)) child.stderr.on("data", (chunk) => lifecycle.stderr?.(chunk.toString()));
28875
+ return child;
28542
28876
  };
28543
28877
  const spawn = (file3, args = [], options = {}) => {
28544
28878
  if (!Array.isArray(args)) return start2(file3, [], args);
@@ -28581,7 +28915,13 @@ ${err.join("")}`),
28581
28915
  spawn,
28582
28916
  exec,
28583
28917
  execFile,
28584
- fork: (modulePath, args = [], options = {}) => spawn("node", [modulePath, ...args], options),
28918
+ fork: (modulePath, args = [], options = {}) => {
28919
+ const [list, opts] = Array.isArray(args) ? [args, options] : [[], args ?? {}];
28920
+ const stdio = Array.isArray(opts.stdio) ? opts.stdio : typeof opts.stdio === "string" ? [opts.stdio, opts.stdio, opts.stdio] : opts.silent ? ["pipe", "pipe", "pipe"] : ["inherit", "inherit", "inherit"];
28921
+ const withChannel = stdio.includes("ipc") ? stdio : [...stdio, "ipc"];
28922
+ const execArgv = (opts.execArgv ?? []).filter((flag) => !/^--(inspect|debug)/.test(flag));
28923
+ return start2("node", [...execArgv, modulePath, ...list], { ...opts, shell: false, stdio: withChannel });
28924
+ },
28585
28925
  ...buildSyncFamily(syncSpawn, throughShell, defaultCwd, environmentFor),
28586
28926
  ChildProcess
28587
28927
  };
@@ -29212,6 +29552,9 @@ function createCoreModules(options) {
29212
29552
  argv: options.argv?.slice() ?? ["/usr/bin/node"],
29213
29553
  argv0: "node",
29214
29554
  execPath: "/usr/bin/node",
29555
+ /* `process/browser.js` has no `execArgv`; Node always has an array, and
29556
+ * CLIs that fork copy it (`[...process.execArgv]`). */
29557
+ execArgv: [],
29215
29558
  env: env2,
29216
29559
  platform: "linux",
29217
29560
  arch: "x64",
@@ -29265,6 +29608,25 @@ function createCoreModules(options) {
29265
29608
  const implementation = EventEmitter4__default.default.prototype[method];
29266
29609
  if (typeof implementation === "function") processObject[method] = implementation;
29267
29610
  }
29611
+ const hrtime = (previous) => {
29612
+ const now = performance.timeOrigin + performance.now();
29613
+ let seconds = Math.floor(now / 1e3);
29614
+ let nanoseconds = Math.floor(now % 1e3 * 1e6);
29615
+ if (previous) {
29616
+ seconds -= previous[0];
29617
+ nanoseconds -= previous[1];
29618
+ if (nanoseconds < 0) {
29619
+ seconds -= 1;
29620
+ nanoseconds += 1e9;
29621
+ }
29622
+ }
29623
+ return [seconds, nanoseconds];
29624
+ };
29625
+ hrtime.bigint = () => {
29626
+ const [seconds, nanoseconds] = hrtime();
29627
+ return BigInt(seconds) * 1000000000n + BigInt(nanoseconds);
29628
+ };
29629
+ processObject.hrtime = hrtime;
29268
29630
  const tty = options.tty === true;
29269
29631
  processObject.stdout = makeOutputStream(stdoutWrite, 1, tty);
29270
29632
  processObject.stderr = makeOutputStream(stderrWrite, 2, tty);
@@ -29349,6 +29711,7 @@ function createCoreModules(options) {
29349
29711
  const moduleBuiltin = {
29350
29712
  builtinModules: builtinNames2.flatMap((name) => [name, `node:${name}`]),
29351
29713
  isBuiltin: (name) => builtinNames2.includes(name.replace(/^node:/, "")),
29714
+ findSourceMap: () => void 0,
29352
29715
  createRequire: () => {
29353
29716
  throw new Error("createRequire is only available inside a loaded module");
29354
29717
  }
@@ -29371,7 +29734,86 @@ function createCoreModules(options) {
29371
29734
  };
29372
29735
  const http = options.http ? createHttpModule(options.http.router, options.http.owner, httpOptions, "http:") : createUnsupportedModule("http");
29373
29736
  const https = options.http ? createHttpModule(options.http.router, options.http.owner, httpOptions, "https:") : createUnsupportedModule("https");
29374
- const childProcess = options.spawnChild ? createChildProcessModule(options.spawnChild, () => cwd, options.syncSpawn, () => ({ ...processObject.env })) : createUnsupportedModule("child_process");
29737
+ let referencedChildren = 0;
29738
+ const childProcess = options.spawnChild ? createChildProcessModule(options.spawnChild, () => cwd, options.syncSpawn, () => ({ ...processObject.env }), {
29739
+ referenceChanged: (delta) => {
29740
+ referencedChildren += delta;
29741
+ },
29742
+ stdout: options.stdout,
29743
+ stderr: options.stderr,
29744
+ ...options.ipc ? { ipc: options.ipc } : {}
29745
+ }) : createUnsupportedModule("child_process");
29746
+ let channelReferenced = 0;
29747
+ const channelId = env2[IPC_CHANNEL_ENV];
29748
+ if (channelId && options.ipc) {
29749
+ delete env2[IPC_CHANNEL_ENV];
29750
+ let open = true;
29751
+ let referenced = true;
29752
+ channelReferenced = 1;
29753
+ const close = () => {
29754
+ if (!open) return;
29755
+ open = false;
29756
+ if (referenced) channelReferenced = 0;
29757
+ processObject.connected = false;
29758
+ delete processObject.send;
29759
+ try {
29760
+ processObject.emit("disconnect");
29761
+ } catch (error) {
29762
+ reportUncaught(error);
29763
+ }
29764
+ runTicks();
29765
+ };
29766
+ const endpoint = options.ipc.attach(
29767
+ channelId,
29768
+ "child",
29769
+ (message) => {
29770
+ try {
29771
+ processObject.emit("message", message, void 0);
29772
+ } catch (error) {
29773
+ reportUncaught(error);
29774
+ }
29775
+ runTicks();
29776
+ },
29777
+ close
29778
+ );
29779
+ processObject.connected = true;
29780
+ processObject.send = (message, ...rest) => {
29781
+ const callback = rest.find((value) => typeof value === "function");
29782
+ if (!open) {
29783
+ const error = Object.assign(new Error("Channel closed"), { code: "ERR_IPC_CHANNEL_CLOSED" });
29784
+ if (callback) defer(() => callback(error));
29785
+ else defer(() => {
29786
+ processObject.emit("error", error);
29787
+ });
29788
+ return false;
29789
+ }
29790
+ endpoint.send(message);
29791
+ if (callback) defer(() => callback(null));
29792
+ return true;
29793
+ };
29794
+ processObject.disconnect = () => {
29795
+ if (open) {
29796
+ endpoint.disconnect();
29797
+ close();
29798
+ }
29799
+ };
29800
+ processObject.channel = {
29801
+ ref() {
29802
+ if (open && !referenced) {
29803
+ referenced = true;
29804
+ channelReferenced = 1;
29805
+ }
29806
+ return this;
29807
+ },
29808
+ unref() {
29809
+ if (referenced) {
29810
+ referenced = false;
29811
+ channelReferenced = 0;
29812
+ }
29813
+ return this;
29814
+ }
29815
+ };
29816
+ }
29375
29817
  const readline = createReadlineModule(() => processObject.stdin, () => processObject.stdout);
29376
29818
  const dns = createDnsModule(defer);
29377
29819
  const builtins = {
@@ -29383,6 +29825,7 @@ function createCoreModules(options) {
29383
29825
  console: consoleObject,
29384
29826
  constants: fs.constants,
29385
29827
  crypto: createCryptoModule(),
29828
+ diagnostics_channel: createDiagnosticsChannel(),
29386
29829
  dns,
29387
29830
  "dns/promises": dns.promises,
29388
29831
  events: EventEmitter4__default.default,
@@ -29401,6 +29844,25 @@ function createCoreModules(options) {
29401
29844
  readline,
29402
29845
  "readline/promises": readline.promises,
29403
29846
  stream: streamModule4__default.default,
29847
+ "stream/web": Object.fromEntries([
29848
+ "ReadableStream",
29849
+ "ReadableStreamDefaultReader",
29850
+ "ReadableStreamBYOBReader",
29851
+ "ReadableStreamDefaultController",
29852
+ "ReadableByteStreamController",
29853
+ "ReadableStreamBYOBRequest",
29854
+ "WritableStream",
29855
+ "WritableStreamDefaultWriter",
29856
+ "WritableStreamDefaultController",
29857
+ "TransformStream",
29858
+ "TransformStreamDefaultController",
29859
+ "ByteLengthQueuingStrategy",
29860
+ "CountQueuingStrategy",
29861
+ "TextEncoderStream",
29862
+ "TextDecoderStream",
29863
+ "CompressionStream",
29864
+ "DecompressionStream"
29865
+ ].filter((name) => name in globalThis).map((name) => [name, globalThis[name]])),
29404
29866
  "stream/promises": createStreamPromises(),
29405
29867
  string_decoder: stringDecoderModule__default.default,
29406
29868
  timers: { ...timersModule__default.default, ...timers.api },
@@ -29432,7 +29894,57 @@ function createCoreModules(options) {
29432
29894
  })
29433
29895
  };
29434
29896
  for (const name of stubNames) builtins[name] = createUnsupportedModule(name);
29897
+ builtins.worker_threads = {
29898
+ MessagePort: globalThis.MessagePort ?? class MessagePort {
29899
+ },
29900
+ markAsUncloneable: () => {
29901
+ },
29902
+ isMarkedAsUncloneable: () => false,
29903
+ markAsUntransferable: () => {
29904
+ },
29905
+ isMarkedAsUntransferable: () => false
29906
+ };
29435
29907
  builtins.net = createNetModule();
29908
+ builtins.inspector = createUnsupportedModule("inspector", {
29909
+ url: () => void 0,
29910
+ close: () => {
29911
+ },
29912
+ waitForDebugger: () => {
29913
+ throw Object.assign(new Error("Inspector is not active"), { code: "ERR_INSPECTOR_NOT_ACTIVE" });
29914
+ },
29915
+ console: consoleObject
29916
+ });
29917
+ builtins.v8 = createUnsupportedModule("v8", {
29918
+ getHeapStatistics: () => {
29919
+ const memory = performance.memory;
29920
+ const limit = memory?.jsHeapSizeLimit ?? 4 * 1024 ** 3;
29921
+ return {
29922
+ total_heap_size: memory?.totalJSHeapSize ?? 0,
29923
+ total_heap_size_executable: 0,
29924
+ total_physical_size: memory?.totalJSHeapSize ?? 0,
29925
+ total_available_size: limit - (memory?.usedJSHeapSize ?? 0),
29926
+ used_heap_size: memory?.usedJSHeapSize ?? 0,
29927
+ heap_size_limit: limit,
29928
+ malloced_memory: 0,
29929
+ peak_malloced_memory: 0,
29930
+ does_zap_garbage: 0,
29931
+ number_of_native_contexts: 1,
29932
+ number_of_detached_contexts: 0,
29933
+ total_global_handles_size: 0,
29934
+ used_global_handles_size: 0,
29935
+ external_memory: 0
29936
+ };
29937
+ },
29938
+ getHeapSpaceStatistics: () => [],
29939
+ getHeapCodeStatistics: () => ({ code_and_metadata_size: 0, bytecode_and_metadata_size: 0, external_script_source_size: 0, cpu_profiler_metadata_size: 0 }),
29940
+ cachedDataVersionTag: () => 0,
29941
+ setFlagsFromString: () => {
29942
+ },
29943
+ setHeapSnapshotNearHeapLimit: () => {
29944
+ },
29945
+ serialize: (value) => Buffer2.from(JSON.stringify(value) ?? "null"),
29946
+ deserialize: (buffer) => JSON.parse(Buffer2.from(buffer).toString("utf8"))
29947
+ });
29436
29948
  const globals = {
29437
29949
  Buffer: Buffer2,
29438
29950
  console: consoleObject,
@@ -29467,7 +29979,7 @@ function createCoreModules(options) {
29467
29979
  builtins,
29468
29980
  globals,
29469
29981
  process: processObject,
29470
- pendingHandles: timers.pending,
29982
+ pendingHandles: () => timers.pending() + referencedChildren + channelReferenced,
29471
29983
  pendingUnrefed: timers.pendingUnrefed,
29472
29984
  /** Client requests sent but not yet read to completion. */
29473
29985
  pendingRequests: () => inFlightRequests,
@@ -29533,7 +30045,9 @@ var ASYNC_FS_METHODS = [
29533
30045
  "close",
29534
30046
  "read",
29535
30047
  "write",
29536
- "exists"
30048
+ "exists",
30049
+ "fsync",
30050
+ "fdatasync"
29537
30051
  ];
29538
30052
  function createPathModule(cwd) {
29539
30053
  const resolve3 = (...segments2) => pathModule__default.default.resolve(cwd(), ...segments2);
@@ -29756,6 +30270,12 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
29756
30270
  unwatchFile: () => {
29757
30271
  }
29758
30272
  };
30273
+ fs.fsyncSync = (fd) => {
30274
+ requiredFd(fds, fd);
30275
+ };
30276
+ fs.fdatasyncSync = (fd) => {
30277
+ requiredFd(fds, fd);
30278
+ };
29759
30279
  fs.ftruncateSync = (fd, length) => fs.truncateSync(requiredFd(fds, fd).path, length);
29760
30280
  fs.fchmodSync = (fd, mode) => fs.chmodSync(requiredFd(fds, fd).path, mode);
29761
30281
  fs.fchownSync = (fd, uid, gid) => fs.chownSync(requiredFd(fds, fd).path, uid, gid);
@@ -29816,6 +30336,8 @@ function makeFileHandle(fs, fd) {
29816
30336
  return {
29817
30337
  fd,
29818
30338
  close: async () => fs.closeSync(fd),
30339
+ sync: async () => fs.fsyncSync(fd),
30340
+ datasync: async () => fs.fdatasyncSync(fd),
29819
30341
  stat: async () => fs.fstatSync(fd),
29820
30342
  truncate: async (length) => fs.ftruncateSync(fd, length),
29821
30343
  chmod: async (mode) => fs.fchmodSync(fd, mode),
@@ -30409,7 +30931,7 @@ function formatUncaught(error) {
30409
30931
  Node.js v22.12.0
30410
30932
  `;
30411
30933
  }
30412
- var stubNames = ["cluster", "dgram", "diagnostics_channel", "domain", "http2", "inspector", "net", "tls", "v8", "vm", "worker_threads"];
30934
+ var stubNames = ["cluster", "dgram", "domain", "http2", "inspector", "net", "tls", "v8", "vm", "worker_threads"];
30413
30935
  var builtinNames2 = [
30414
30936
  "assert",
30415
30937
  "assert/strict",
@@ -30422,6 +30944,7 @@ var builtinNames2 = [
30422
30944
  "events",
30423
30945
  "fs",
30424
30946
  "fs/promises",
30947
+ "diagnostics_channel",
30425
30948
  "dns",
30426
30949
  "dns/promises",
30427
30950
  "http",
@@ -30437,6 +30960,7 @@ var builtinNames2 = [
30437
30960
  "readline",
30438
30961
  "readline/promises",
30439
30962
  "stream",
30963
+ "stream/web",
30440
30964
  "stream/promises",
30441
30965
  "string_decoder",
30442
30966
  "timers",
@@ -31825,6 +32349,7 @@ var LocalRuntimePod = class _LocalRuntimePod {
31825
32349
  ...this.networkPolicy ? { policy: this.networkPolicy } : {}
31826
32350
  },
31827
32351
  spawnChild: (config2) => this.processManager.spawn(config2),
32352
+ ipc: hostIpcTransport,
31828
32353
  ...typeof options.stdinPath === "string" ? { stdinPath: options.stdinPath } : {},
31829
32354
  ...options.interactiveStdin ? { interactiveStdin: true } : {},
31830
32355
  ...options.tty ? { tty: true } : {},
@@ -32318,9 +32843,12 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
32318
32843
  const entry = { worker, server };
32319
32844
  this.live.add(entry);
32320
32845
  const ownedChildren = /* @__PURE__ */ new Set();
32846
+ const channelEnds = /* @__PURE__ */ new Map();
32321
32847
  const process2 = new WorkerProcess(worker, () => {
32322
32848
  for (const child of ownedChildren) child.kill("SIGTERM");
32323
32849
  ownedChildren.clear();
32850
+ for (const end of channelEnds.values()) end.disconnect();
32851
+ channelEnds.clear();
32324
32852
  this.live.delete(entry);
32325
32853
  server.close();
32326
32854
  this.closeProxies(owner);
@@ -32385,6 +32913,30 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
32385
32913
  case "child-kill":
32386
32914
  children.get(message.id)?.kill(String(message.signal));
32387
32915
  return;
32916
+ case "ipc-attach": {
32917
+ const key = `${message.side}:${message.id}`;
32918
+ if (channelEnds.has(key)) return;
32919
+ channelEnds.set(key, hostIpcTransport.attach(
32920
+ String(message.id),
32921
+ message.side === "child" ? "child" : "parent",
32922
+ (value) => worker.postMessage({ type: "ipc-message", id: message.id, side: message.side, value }),
32923
+ () => {
32924
+ channelEnds.delete(key);
32925
+ worker.postMessage({ type: "ipc-disconnect", id: message.id, side: message.side });
32926
+ }
32927
+ ));
32928
+ return;
32929
+ }
32930
+ case "ipc-send":
32931
+ channelEnds.get(`${message.side}:${message.id}`)?.send(message.value);
32932
+ return;
32933
+ case "ipc-close": {
32934
+ const key = `${message.side}:${message.id}`;
32935
+ const end = channelEnds.get(key);
32936
+ channelEnds.delete(key);
32937
+ end?.disconnect();
32938
+ return;
32939
+ }
32388
32940
  default:
32389
32941
  return;
32390
32942
  }