main
   1"use strict";
   2const {
   3  __spreadValues,
   4  __spreadProps,
   5  __export,
   6  __toESM,
   7  __toCommonJS,
   8  __async,
   9  __await,
  10  __asyncGenerator,
  11  __yieldStar,
  12  __forAwait
  13} = require('./esblib.cjs');
  14
  15
  16// src/core.ts
  17var core_exports = {};
  18__export(core_exports, {
  19  $: () => $,
  20  Fail: () => Fail,
  21  ProcessOutput: () => ProcessOutput,
  22  ProcessPromise: () => ProcessPromise,
  23  bus: () => import_internals.bus,
  24  cd: () => cd,
  25  chalk: () => import_vendor_core3.chalk,
  26  defaults: () => defaults,
  27  kill: () => kill,
  28  log: () => log,
  29  os: () => os,
  30  path: () => import_node_path.default,
  31  ps: () => import_vendor_core3.ps,
  32  quote: () => import_util2.quote,
  33  quotePowerShell: () => import_util2.quotePowerShell,
  34  resolveDefaults: () => resolveDefaults,
  35  syncProcessCwd: () => syncProcessCwd,
  36  useBash: () => useBash,
  37  usePowerShell: () => usePowerShell,
  38  usePwsh: () => usePwsh,
  39  which: () => import_vendor_core3.which,
  40  within: () => within
  41});
  42module.exports = __toCommonJS(core_exports);
  43var import_node_async_hooks = require("async_hooks");
  44var import_node_buffer = require("buffer");
  45var import_node_child_process = __toESM(require("child_process"), 1);
  46var import_node_events = require("events");
  47var import_node_fs = __toESM(require("fs"), 1);
  48var import_node_os = require("os");
  49var import_node_process2 = __toESM(require("process"), 1);
  50var import_node_util2 = require("util");
  51
  52// src/error.ts
  53var EXIT_CODES = {
  54  2: "Misuse of shell builtins",
  55  126: "Invoked command cannot execute",
  56  127: "Command not found",
  57  128: "Invalid exit argument",
  58  129: "Hangup",
  59  130: "Interrupt",
  60  131: "Quit and dump core",
  61  132: "Illegal instruction",
  62  133: "Trace/breakpoint trap",
  63  134: "Process aborted",
  64  135: 'Bus error: "access to undefined portion of memory object"',
  65  136: 'Floating point exception: "erroneous arithmetic operation"',
  66  137: "Kill (terminate immediately)",
  67  138: "User-defined 1",
  68  139: "Segmentation violation",
  69  140: "User-defined 2",
  70  141: "Write to pipe with no one reading",
  71  142: "Signal raised by alarm",
  72  143: "Termination (request to terminate)",
  73  145: "Child process terminated, stopped (or continued*)",
  74  146: "Continue if stopped",
  75  147: "Stop executing temporarily",
  76  148: "Terminal stop signal",
  77  149: 'Background process attempting to read from tty ("in")',
  78  150: 'Background process attempting to write to tty ("out")',
  79  151: "Urgent data available on socket",
  80  152: "CPU time limit exceeded",
  81  153: "File size limit exceeded",
  82  154: 'Signal raised by timer counting virtual time: "virtual timer expired"',
  83  155: "Profiling timer expired",
  84  157: "Pollable event",
  85  159: "Bad syscall"
  86};
  87var ERRNO_CODES = {
  88  0: "Success",
  89  1: "Not super-user",
  90  2: "No such file or directory",
  91  3: "No such process",
  92  4: "Interrupted system call",
  93  5: "I/O error",
  94  6: "No such device or address",
  95  7: "Arg list too long",
  96  8: "Exec format error",
  97  9: "Bad file number",
  98  10: "No children",
  99  11: "No more processes",
 100  12: "Not enough core",
 101  13: "Permission denied",
 102  14: "Bad address",
 103  15: "Block device required",
 104  16: "Mount device busy",
 105  17: "File exists",
 106  18: "Cross-device link",
 107  19: "No such device",
 108  20: "Not a directory",
 109  21: "Is a directory",
 110  22: "Invalid argument",
 111  23: "Too many open files in system",
 112  24: "Too many open files",
 113  25: "Not a typewriter",
 114  26: "Text file busy",
 115  27: "File too large",
 116  28: "No space left on device",
 117  29: "Illegal seek",
 118  30: "Read only file system",
 119  31: "Too many links",
 120  32: "Broken pipe",
 121  33: "Math arg out of domain of func",
 122  34: "Math result not representable",
 123  35: "File locking deadlock error",
 124  36: "File or path name too long",
 125  37: "No record locks available",
 126  38: "Function not implemented",
 127  39: "Directory not empty",
 128  40: "Too many symbolic links",
 129  42: "No message of desired type",
 130  43: "Identifier removed",
 131  44: "Channel number out of range",
 132  45: "Level 2 not synchronized",
 133  46: "Level 3 halted",
 134  47: "Level 3 reset",
 135  48: "Link number out of range",
 136  49: "Protocol driver not attached",
 137  50: "No CSI structure available",
 138  51: "Level 2 halted",
 139  52: "Invalid exchange",
 140  53: "Invalid request descriptor",
 141  54: "Exchange full",
 142  55: "No anode",
 143  56: "Invalid request code",
 144  57: "Invalid slot",
 145  59: "Bad font file fmt",
 146  60: "Device not a stream",
 147  61: "No data (for no delay io)",
 148  62: "Timer expired",
 149  63: "Out of streams resources",
 150  64: "Machine is not on the network",
 151  65: "Package not installed",
 152  66: "The object is remote",
 153  67: "The link has been severed",
 154  68: "Advertise error",
 155  69: "Srmount error",
 156  70: "Communication error on send",
 157  71: "Protocol error",
 158  72: "Multihop attempted",
 159  73: "Cross mount point (not really error)",
 160  74: "Trying to read unreadable message",
 161  75: "Value too large for defined data type",
 162  76: "Given log. name not unique",
 163  77: "f.d. invalid for this operation",
 164  78: "Remote address changed",
 165  79: "Can   access a needed shared lib",
 166  80: "Accessing a corrupted shared lib",
 167  81: ".lib section in a.out corrupted",
 168  82: "Attempting to link in too many libs",
 169  83: "Attempting to exec a shared library",
 170  84: "Illegal byte sequence",
 171  86: "Streams pipe error",
 172  87: "Too many users",
 173  88: "Socket operation on non-socket",
 174  89: "Destination address required",
 175  90: "Message too long",
 176  91: "Protocol wrong type for socket",
 177  92: "Protocol not available",
 178  93: "Unknown protocol",
 179  94: "Socket type not supported",
 180  95: "Not supported",
 181  96: "Protocol family not supported",
 182  97: "Address family not supported by protocol family",
 183  98: "Address already in use",
 184  99: "Address not available",
 185  100: "Network interface is not configured",
 186  101: "Network is unreachable",
 187  102: "Connection reset by network",
 188  103: "Connection aborted",
 189  104: "Connection reset by peer",
 190  105: "No buffer space available",
 191  106: "Socket is already connected",
 192  107: "Socket is not connected",
 193  108: "Can't send after socket shutdown",
 194  109: "Too many references",
 195  110: "Connection timed out",
 196  111: "Connection refused",
 197  112: "Host is down",
 198  113: "Host is unreachable",
 199  114: "Socket already connected",
 200  115: "Connection already in progress",
 201  116: "Stale file handle",
 202  122: "Quota exceeded",
 203  123: "No medium (in tape drive)",
 204  125: "Operation canceled",
 205  130: "Previous owner died",
 206  131: "State not recoverable"
 207};
 208var DOCS_URL = "https://google.github.io/zx";
 209var _Fail = class _Fail extends Error {
 210  static formatExitMessage(code, signal, stderr, from, details = "") {
 211    if (code == 0 && signal == null) return `exit code: ${code}`;
 212    const codeInfo = _Fail.getExitCodeInfo(code);
 213    let message = `${stderr}
 214    at ${from}
 215    exit code: ${code}${codeInfo ? " (" + codeInfo + ")" : ""}`;
 216    if (signal != null) message += `
 217    signal: ${signal}`;
 218    if (details) message += `
 219    details: 
 220${details}`;
 221    return message;
 222  }
 223  static formatErrorMessage(err, from) {
 224    return `${err.message}
 225    errno: ${err.errno} (${_Fail.getErrnoMessage(err.errno)})
 226    code: ${err.code}
 227    at ${from}`;
 228  }
 229  static formatErrorDetails(lines = [], lim = 20) {
 230    if (lines.length < lim) return lines.join("\n");
 231    let errors = lines.filter((l) => /(fail|error|not ok|exception)/i.test(l));
 232    if (errors.length === 0) errors = lines;
 233    return errors.slice(0, lim).join("\n") + (errors.length > lim ? "\n..." : "");
 234  }
 235  static getExitCodeInfo(exitCode) {
 236    return EXIT_CODES[exitCode];
 237  }
 238  static getCallerLocationFromString(stackString = "unknown") {
 239    const lines = stackString.split(/^\s*(at\s)?/m).filter((s) => s == null ? void 0 : s.includes(":"));
 240    const i = lines.findIndex((l) => l.includes("Proxy.set"));
 241    const offset = i < 0 ? i : i + 2;
 242    return (lines.find((l) => l.includes("file://")) || lines[offset] || stackString).trim();
 243  }
 244  static getCallerLocation(err = new Error("zx error")) {
 245    return _Fail.getCallerLocationFromString(err.stack);
 246  }
 247  static getErrnoMessage(errno) {
 248    return ERRNO_CODES[-errno] || "Unknown error";
 249  }
 250};
 251_Fail.DOCS_URL = DOCS_URL;
 252_Fail.EXIT_CODES = EXIT_CODES;
 253_Fail.ERRNO_CODES = ERRNO_CODES;
 254var Fail = _Fail;
 255
 256// src/log.ts
 257var import_vendor_core = require("./vendor-core.cjs");
 258var import_node_util = require("util");
 259var import_node_process = __toESM(require("process"), 1);
 260var formatters = {
 261  cmd({ cmd }) {
 262    return formatCmd(cmd);
 263  },
 264  stdout({ data }) {
 265    return data;
 266  },
 267  stderr({ data }) {
 268    return data;
 269  },
 270  custom({ data }) {
 271    return data;
 272  },
 273  fetch(entry) {
 274    const init = entry.init ? " " + (0, import_node_util.inspect)(entry.init) : "";
 275    return `$ ${import_vendor_core.chalk.greenBright("fetch")} ${entry.url}${init}
 276`;
 277  },
 278  cd(entry) {
 279    return `$ ${import_vendor_core.chalk.greenBright("cd")} ${entry.dir}
 280`;
 281  },
 282  retry(entry) {
 283    const attempt = `Attempt: ${entry.attempt}${entry.total == Infinity ? "" : `/${entry.total}`}`;
 284    const delay = entry.delay > 0 ? `; next in ${entry.delay}ms` : "";
 285    return `${import_vendor_core.chalk.bgRed.white(" FAIL ")} ${attempt}${delay}
 286`;
 287  },
 288  end() {
 289    return "";
 290  },
 291  kill() {
 292    return "";
 293  }
 294};
 295var log = function(entry) {
 296  var _a;
 297  if (!entry.verbose) return;
 298  const stream = log.output || import_node_process.default.stderr;
 299  const format = ((_a = log.formatters) == null ? void 0 : _a[entry.kind]) || formatters[entry.kind];
 300  if (!format) return;
 301  stream.write(format(entry));
 302};
 303var SPACE_RE = /\s/;
 304var SYNTAX = "()[]{}<>;:+|&=";
 305var CMD_BREAK = "|&;><";
 306var RESERVED_WORDS = /* @__PURE__ */ new Set([
 307  "if",
 308  "then",
 309  "else",
 310  "elif",
 311  "fi",
 312  "case",
 313  "esac",
 314  "for",
 315  "select",
 316  "while",
 317  "until",
 318  "do",
 319  "done",
 320  "in",
 321  "EOF"
 322]);
 323function formatCmd(cmd) {
 324  if (cmd == void 0) return import_vendor_core.chalk.grey("undefined");
 325  let q = "";
 326  let out = "$ ";
 327  let buf = "";
 328  let mode = "";
 329  let pos = 0;
 330  const cap = () => {
 331    const word = buf.trim();
 332    if (word) {
 333      pos++;
 334      if (mode === "syntax") {
 335        if (CMD_BREAK.includes(word)) {
 336          pos = 0;
 337        }
 338        out += import_vendor_core.chalk.red(buf);
 339      } else if (mode === "quote" || mode === "dollar") {
 340        out += import_vendor_core.chalk.yellowBright(buf);
 341      } else if (RESERVED_WORDS.has(word)) {
 342        out += import_vendor_core.chalk.cyanBright(buf);
 343      } else if (pos === 1) {
 344        out += import_vendor_core.chalk.greenBright(buf);
 345        pos = Infinity;
 346      } else {
 347        out += buf;
 348      }
 349    } else {
 350      out += buf;
 351    }
 352    mode = "";
 353    buf = "";
 354  };
 355  for (const c of [...cmd]) {
 356    if (!q) {
 357      if (c === "$") {
 358        cap();
 359        mode = "dollar";
 360        buf += c;
 361        cap();
 362      } else if (c === "'" || c === '"') {
 363        cap();
 364        mode = "quote";
 365        q = c;
 366        buf += c;
 367      } else if (SPACE_RE.test(c)) {
 368        cap();
 369        buf += c;
 370      } else if (SYNTAX.includes(c)) {
 371        const isEnv = c === "=" && pos === 0;
 372        isEnv && (pos = 1);
 373        cap();
 374        mode = "syntax";
 375        buf += c;
 376        cap();
 377        isEnv && (pos = -1);
 378      } else {
 379        buf += c;
 380      }
 381    } else {
 382      buf += c;
 383      if (c === q) {
 384        cap();
 385        q = "";
 386      }
 387    }
 388  }
 389  cap();
 390  return out.replaceAll("\n", import_vendor_core.chalk.reset("\n> ")) + "\n";
 391}
 392
 393// src/core.ts
 394var import_vendor_core2 = require("./vendor-core.cjs");
 395var import_util = require("./util.cjs");
 396var import_internals = require("./internals.cjs");
 397var import_node_path = __toESM(require("path"), 1);
 398var os = __toESM(require("os"), 1);
 399var import_vendor_core3 = require("./vendor-core.cjs");
 400var import_util2 = require("./util.cjs");
 401var CWD = Symbol("processCwd");
 402var SYNC = Symbol("syncExec");
 403var EPF = Symbol("end-piped-from");
 404var SHOT = Symbol("snapshot");
 405var EOL = import_node_buffer.Buffer.from(import_node_os.EOL);
 406var BR_CC = "\n".charCodeAt(0);
 407var DLMTR = /\r?\n/;
 408var SIGTERM = "SIGTERM";
 409var ENV_PREFIX = "ZX_";
 410var ENV_OPTS = /* @__PURE__ */ new Set([
 411  "cwd",
 412  "preferLocal",
 413  "detached",
 414  "verbose",
 415  "quiet",
 416  "timeout",
 417  "timeoutSignal",
 418  "killSignal",
 419  "prefix",
 420  "postfix",
 421  "shell"
 422]);
 423var defaults = resolveDefaults({
 424  [CWD]: import_node_process2.default.cwd(),
 425  [SYNC]: false,
 426  verbose: false,
 427  env: import_node_process2.default.env,
 428  sync: false,
 429  shell: true,
 430  stdio: "pipe",
 431  nothrow: false,
 432  quiet: false,
 433  detached: false,
 434  preferLocal: false,
 435  spawn: import_node_child_process.default.spawn,
 436  spawnSync: import_node_child_process.default.spawnSync,
 437  log,
 438  kill,
 439  killSignal: SIGTERM,
 440  timeoutSignal: SIGTERM
 441});
 442var storage = new import_node_async_hooks.AsyncLocalStorage();
 443var getStore = () => storage.getStore() || defaults;
 444var getSnapshot = (opts, from, pieces, args) => __spreadProps(__spreadValues({}, opts), {
 445  ac: opts.ac || new AbortController(),
 446  ee: new import_node_events.EventEmitter(),
 447  from,
 448  pieces,
 449  args,
 450  cmd: ""
 451});
 452function within(callback) {
 453  return storage.run(__spreadValues({}, getStore()), callback);
 454}
 455var $ = new Proxy(
 456  // prettier-ignore
 457  function(pieces, ...args) {
 458    const opts = getStore();
 459    if (!Array.isArray(pieces)) {
 460      return function(...args2) {
 461        return within(() => Object.assign($, opts, pieces).apply(this, args2));
 462      };
 463    }
 464    const from = Fail.getCallerLocation();
 465    const cb = () => cb[SHOT] = getSnapshot(opts, from, pieces, args);
 466    const pp = new ProcessPromise(cb);
 467    if (!pp.isHalted()) pp.run();
 468    return pp.sync ? pp.output : pp;
 469  },
 470  {
 471    set(t, key, value) {
 472      return Reflect.set(
 473        key in Function.prototype ? t : getStore(),
 474        key === "sync" ? SYNC : key,
 475        value
 476      );
 477    },
 478    get(t, key) {
 479      return key === "sync" ? $({ sync: true }) : Reflect.get(key in Function.prototype ? t : getStore(), key);
 480    }
 481  }
 482);
 483var _ProcessPromise = class _ProcessPromise extends Promise {
 484  constructor(executor) {
 485    let resolve;
 486    let reject;
 487    super((...args) => {
 488      ;
 489      [resolve = import_util.noop, reject = import_util.noop] = args;
 490      executor(...args);
 491    });
 492    this._stage = "initial";
 493    this._id = (0, import_util.randomId)();
 494    this._piped = false;
 495    this._stdin = new import_vendor_core2.VoidStream();
 496    this._zurk = null;
 497    this._output = null;
 498    // Stream-like API
 499    this.writable = true;
 500    const snapshot = executor[SHOT];
 501    if (snapshot) {
 502      this._snapshot = snapshot;
 503      this._resolve = resolve;
 504      this._reject = reject;
 505      if (snapshot.halt) this._stage = "halted";
 506      try {
 507        this.build();
 508      } catch (err) {
 509        this.finalize(ProcessOutput.fromError(err), true);
 510      }
 511    } else _ProcessPromise.disarm(this);
 512  }
 513  // prettier-ignore
 514  build() {
 515    const $2 = this._snapshot;
 516    if (!$2.shell)
 517      throw new Fail(`No shell is available: ${Fail.DOCS_URL}/shell`);
 518    if (!$2.quote)
 519      throw new Fail(`No quote function is defined: ${Fail.DOCS_URL}/quotes`);
 520    if ($2.pieces.some((p) => p == null))
 521      throw new Fail(`Malformed command at ${$2.from}`);
 522    $2.cmd = (0, import_vendor_core2.buildCmd)(
 523      $2.quote,
 524      $2.pieces,
 525      $2.args
 526    );
 527  }
 528  run() {
 529    var _a, _b;
 530    _ProcessPromise.bus.runBack(this);
 531    if (this.isRunning() || this.isSettled()) return this;
 532    this._stage = "running";
 533    const self = this;
 534    const $2 = self._snapshot;
 535    const id = self.id;
 536    const cwd = $2.cwd || $2[CWD];
 537    if ($2.preferLocal) {
 538      const dirs = $2.preferLocal === true ? [$2.cwd, $2[CWD]] : [$2.preferLocal].flat();
 539      $2.env = (0, import_util.preferLocalBin)($2.env, ...dirs);
 540    }
 541    this._zurk = (0, import_vendor_core2.exec)({
 542      cmd: self.fullCmd,
 543      cwd,
 544      input: (_b = (_a = $2.input) == null ? void 0 : _a.stdout) != null ? _b : $2.input,
 545      stdin: self._stdin,
 546      sync: self.sync,
 547      signal: self.signal,
 548      shell: (0, import_util.isString)($2.shell) ? $2.shell : true,
 549      id,
 550      env: $2.env,
 551      spawn: $2.spawn,
 552      spawnSync: $2.spawnSync,
 553      store: $2.store,
 554      stdio: $2.stdio,
 555      detached: $2.detached,
 556      ee: $2.ee,
 557      run(cb, ctx) {
 558        var _a2, _b2;
 559        ((_b2 = (_a2 = self.cmd).then) == null ? void 0 : _b2.call(
 560          _a2,
 561          (cmd) => {
 562            $2.cmd = cmd;
 563            ctx.cmd = self.fullCmd;
 564            cb();
 565          },
 566          (error) => self.finalize(ProcessOutput.fromError(error))
 567        )) || cb();
 568      },
 569      on: {
 570        start: () => {
 571          $2.log({ kind: "cmd", cmd: $2.cmd, cwd, verbose: self.isVerbose(), id });
 572          self.timeout($2.timeout, $2.timeoutSignal);
 573        },
 574        stdout: (data) => {
 575          $2.log({ kind: "stdout", data, verbose: !self._piped && self.isVerbose(), id });
 576        },
 577        stderr: (data) => {
 578          $2.log({ kind: "stderr", data, verbose: !self.isQuiet(), id });
 579        },
 580        end: (data, c) => {
 581          const { error: _error, status, signal: __signal, duration, ctx: { store } } = data;
 582          const { stdout, stderr } = store;
 583          const { cause, exitCode, signal: _signal } = self._breakerData || {};
 584          const signal = _signal != null ? _signal : __signal;
 585          const code = exitCode != null ? exitCode : status;
 586          const error = cause != null ? cause : _error;
 587          const output = new ProcessOutput({
 588            code,
 589            signal,
 590            error,
 591            duration,
 592            store,
 593            from: $2.from
 594          });
 595          $2.log({ kind: "end", signal, exitCode: code, duration, error, verbose: self.isVerbose(), id });
 596          if (stdout.length && (0, import_util.getLast)((0, import_util.getLast)(stdout)) !== BR_CC) c.on.stdout(EOL, c);
 597          if (stderr.length && (0, import_util.getLast)((0, import_util.getLast)(stderr)) !== BR_CC) c.on.stderr(EOL, c);
 598          self.finalize(output);
 599        }
 600      }
 601    });
 602    return this;
 603  }
 604  break(exitCode, signal, cause) {
 605    if (!this.isRunning()) return;
 606    this._breakerData = { exitCode, signal, cause };
 607    this.kill(signal);
 608  }
 609  finalize(output, legacy = false) {
 610    if (this.isSettled()) return;
 611    this._output = output;
 612    _ProcessPromise.bus.unpipeBack(this);
 613    if (output.ok || this.isNothrow()) {
 614      this._stage = "fulfilled";
 615      this._resolve(output);
 616    } else {
 617      this._stage = "rejected";
 618      if (legacy) {
 619        this._resolve(output);
 620        throw output.cause || output;
 621      }
 622      this._reject(output);
 623      if (this.sync) throw output;
 624    }
 625  }
 626  abort(reason) {
 627    if (this.isSettled()) throw new Fail("Too late to abort the process.");
 628    if (this.signal !== this.ac.signal)
 629      throw new Fail("The signal is controlled by another process.");
 630    if (!this.child)
 631      throw new Fail("Trying to abort a process without creating one.");
 632    this.ac.abort(reason);
 633  }
 634  kill(signal) {
 635    if (this.isSettled()) throw new Fail("Too late to kill the process.");
 636    if (!this.child)
 637      throw new Fail("Trying to kill a process without creating one.");
 638    if (!this.pid) throw new Fail("The process pid is undefined.");
 639    return $.kill(this.pid, signal || this._snapshot.killSignal || $.killSignal);
 640  }
 641  // Configurators
 642  stdio(stdin, stdout = "pipe", stderr = "pipe") {
 643    this._snapshot.stdio = Array.isArray(stdin) ? stdin : [stdin, stdout, stderr];
 644    return this;
 645  }
 646  nothrow(v = true) {
 647    this._snapshot.nothrow = v;
 648    return this;
 649  }
 650  quiet(v = true) {
 651    this._snapshot.quiet = v;
 652    return this;
 653  }
 654  verbose(v = true) {
 655    this._snapshot.verbose = v;
 656    return this;
 657  }
 658  timeout(d = 0, signal = $.timeoutSignal) {
 659    if (this.isSettled()) return this;
 660    const $2 = this._snapshot;
 661    $2.timeout = (0, import_util.parseDuration)(d);
 662    $2.timeoutSignal = signal;
 663    if (this._timeoutId) clearTimeout(this._timeoutId);
 664    if ($2.timeout && this.isRunning()) {
 665      this._timeoutId = setTimeout(() => this.kill($2.timeoutSignal), $2.timeout);
 666      this.finally(() => clearTimeout(this._timeoutId)).catch(import_util.noop);
 667    }
 668    return this;
 669  }
 670  /**
 671   *  @deprecated Use $({halt: true})`cmd` instead.
 672   */
 673  halt() {
 674    return this;
 675  }
 676  // Getters
 677  get id() {
 678    return this._id;
 679  }
 680  get pid() {
 681    var _a;
 682    return (_a = this.child) == null ? void 0 : _a.pid;
 683  }
 684  get cmd() {
 685    return this._snapshot.cmd;
 686  }
 687  get fullCmd() {
 688    const { prefix = "", postfix = "", cmd } = this._snapshot;
 689    return prefix + cmd + postfix;
 690  }
 691  get child() {
 692    var _a;
 693    return (_a = this._zurk) == null ? void 0 : _a.child;
 694  }
 695  get stdin() {
 696    var _a;
 697    return (_a = this.child) == null ? void 0 : _a.stdin;
 698  }
 699  get stdout() {
 700    var _a;
 701    return (_a = this.child) == null ? void 0 : _a.stdout;
 702  }
 703  get stderr() {
 704    var _a;
 705    return (_a = this.child) == null ? void 0 : _a.stderr;
 706  }
 707  get exitCode() {
 708    return this.then(
 709      (o) => o.exitCode,
 710      (o) => o.exitCode
 711    );
 712  }
 713  get signal() {
 714    return this._snapshot.signal || this.ac.signal;
 715  }
 716  get ac() {
 717    return this._snapshot.ac;
 718  }
 719  get output() {
 720    return this._output;
 721  }
 722  get stage() {
 723    return this._stage;
 724  }
 725  get sync() {
 726    return this._snapshot[SYNC];
 727  }
 728  get [Symbol.toStringTag]() {
 729    return "ProcessPromise";
 730  }
 731  [Symbol.toPrimitive]() {
 732    return this.toString();
 733  }
 734  // Output formatters
 735  json() {
 736    return this.then((o) => o.json());
 737  }
 738  text(encoding) {
 739    return this.then((o) => o.text(encoding));
 740  }
 741  lines(delimiter) {
 742    return this.then((o) => o.lines(delimiter));
 743  }
 744  buffer() {
 745    return this.then((o) => o.buffer());
 746  }
 747  blob(type) {
 748    return this.then((o) => o.blob(type));
 749  }
 750  // Status checkers
 751  isQuiet() {
 752    return this._snapshot.quiet;
 753  }
 754  isVerbose() {
 755    return this._snapshot.verbose && !this.isQuiet();
 756  }
 757  isNothrow() {
 758    return this._snapshot.nothrow;
 759  }
 760  isHalted() {
 761    return this.stage === "halted" && !this.sync;
 762  }
 763  isSettled() {
 764    return !!this.output;
 765  }
 766  isRunning() {
 767    return this.stage === "running";
 768  }
 769  // Piping
 770  // prettier-ignore
 771  get pipe() {
 772    const getPipeMethod = (kind) => this._pipe.bind(this, kind);
 773    const stdout = getPipeMethod("stdout");
 774    const stderr = getPipeMethod("stderr");
 775    const stdall = getPipeMethod("stdall");
 776    return Object.assign(stdout, { stdout, stderr, stdall });
 777  }
 778  unpipe(to) {
 779    _ProcessPromise.bus.unpipe(this, to);
 780    return this;
 781  }
 782  // prettier-ignore
 783  _pipe(source, dest, ...args) {
 784    if ((0, import_util.isString)(dest))
 785      return this._pipe(source, import_node_fs.default.createWriteStream(dest));
 786    if ((0, import_util.isStringLiteral)(dest, ...args))
 787      return this._pipe(
 788        source,
 789        $({
 790          halt: true,
 791          signal: this.signal
 792        })(dest, ...args)
 793      );
 794    const isP = dest instanceof _ProcessPromise;
 795    if (isP && dest.isSettled()) throw new Fail("Cannot pipe to a settled process.");
 796    if (!isP && dest.writableEnded) throw new Fail("Cannot pipe to a closed stream.");
 797    this._piped = true;
 798    _ProcessPromise.bus.pipe(this, dest);
 799    const { ee } = this._snapshot;
 800    const output = this.output;
 801    const from = new import_vendor_core2.VoidStream();
 802    const check = () => {
 803      var _a;
 804      return !!((_a = _ProcessPromise.bus.refs.get(this)) == null ? void 0 : _a.has(dest));
 805    };
 806    const end = () => {
 807      if (!check()) return;
 808      setImmediate(() => {
 809        _ProcessPromise.bus.unpipe(this, dest);
 810        _ProcessPromise.bus.sources(dest).length === 0 && from.end();
 811      });
 812    };
 813    const fill = () => {
 814      for (const chunk of this._zurk.store[source]) from.write(chunk);
 815    };
 816    const fillSettled = () => {
 817      if (!output) return;
 818      if (isP && !output.ok) dest.break(output.exitCode, output.signal, output.cause);
 819      fill();
 820      end();
 821    };
 822    if (!output) {
 823      const onData = (chunk) => check() && from.write(chunk);
 824      ee.once(source, () => {
 825        fill();
 826        ee.on(source, onData);
 827      }).once("end", () => {
 828        ee.removeListener(source, onData);
 829        end();
 830      });
 831    }
 832    if (isP) {
 833      from.pipe(dest._stdin);
 834      if (this.isHalted()) ee.once("start", () => dest.run());
 835      else {
 836        dest.run();
 837        this.catch((e) => dest.break(e.exitCode, e.signal, e.cause));
 838      }
 839      fillSettled();
 840      return dest;
 841    }
 842    from.once("end", () => dest.emit(EPF)).pipe(dest);
 843    fillSettled();
 844    return _ProcessPromise.promisifyStream(dest, this);
 845  }
 846  // Promise API
 847  then(onfulfilled, onrejected) {
 848    return super.then(onfulfilled, onrejected);
 849  }
 850  catch(onrejected) {
 851    return super.catch(onrejected);
 852  }
 853  // Async iterator API
 854  [Symbol.asyncIterator]() {
 855    return __asyncGenerator(this, null, function* () {
 856      const memo = [];
 857      const dlmtr = this._snapshot.delimiter || $.delimiter || DLMTR;
 858      for (const chunk of this._zurk.store.stdout) {
 859        yield* __yieldStar((0, import_util.getLines)(chunk, memo, dlmtr));
 860      }
 861      try {
 862        for (var iter = __forAwait(this.stdout || []), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
 863          const chunk = temp.value;
 864          yield* __yieldStar((0, import_util.getLines)(chunk, memo, dlmtr));
 865        }
 866      } catch (temp) {
 867        error = [temp];
 868      } finally {
 869        try {
 870          more && (temp = iter.return) && (yield new __await(temp.call(iter)));
 871        } finally {
 872          if (error)
 873            throw error[0];
 874        }
 875      }
 876      if (memo[0]) yield memo[0];
 877      yield new __await(this);
 878    });
 879  }
 880  emit(event, ...args) {
 881    return this;
 882  }
 883  on(event, cb) {
 884    this._stdin.on(event, cb);
 885    return this;
 886  }
 887  once(event, cb) {
 888    this._stdin.once(event, cb);
 889    return this;
 890  }
 891  write(data, encoding, cb) {
 892    this._stdin.write(data, encoding, cb);
 893    return this;
 894  }
 895  end(chunk, cb) {
 896    this._stdin.end(chunk, cb);
 897    return this;
 898  }
 899  removeListener(event, cb) {
 900    this._stdin.removeListener(event, cb);
 901    return this;
 902  }
 903  // prettier-ignore
 904  static disarm(p, toggle = true) {
 905    Object.getOwnPropertyNames(_ProcessPromise.prototype).forEach((k) => {
 906      if (k in Promise.prototype) return;
 907      if (!toggle) {
 908        Reflect.deleteProperty(p, k);
 909        return;
 910      }
 911      Object.defineProperty(p, k, { configurable: true, get() {
 912        throw new Fail("Inappropriate usage. Apply $ instead of direct instantiation.");
 913      } });
 914    });
 915  }
 916};
 917// prettier-ignore
 918_ProcessPromise.bus = {
 919  refs: /* @__PURE__ */ new Map(),
 920  streams: /* @__PURE__ */ new WeakMap(),
 921  pipe(from, to) {
 922    const set = this.refs.get(from) || this.refs.set(from, /* @__PURE__ */ new Set()).get(from);
 923    set.add(to);
 924  },
 925  unpipe(from, to) {
 926    const set = this.refs.get(from);
 927    if (!set) return;
 928    if (to) set.delete(to);
 929    if (set.size) return;
 930    this.refs.delete(from);
 931    from._piped = false;
 932  },
 933  unpipeBack(to, from) {
 934    if (from) return this.unpipe(from, to);
 935    for (const _from of this.refs.keys()) {
 936      this.unpipe(_from, to);
 937    }
 938  },
 939  runBack(p) {
 940    var _a;
 941    for (const from of this.sources(p)) {
 942      if (from instanceof _ProcessPromise) from.run();
 943      else (_a = this.streams.get(from)) == null ? void 0 : _a.run();
 944    }
 945  },
 946  sources(p) {
 947    const refs = [];
 948    for (const [from, set] of this.refs.entries()) {
 949      set.has(p) && refs.push(from);
 950    }
 951    return refs;
 952  }
 953};
 954_ProcessPromise.promisifyStream = (stream, from) => {
 955  const proxy = _ProcessPromise.bus.streams.get(stream) || (0, import_util.proxyOverride)(stream, {
 956    then(res = import_util.noop, rej = import_util.noop) {
 957      return new Promise((_res, _rej) => {
 958        const end = () => _res(res((0, import_util.proxyOverride)(stream, from.output)));
 959        stream.once("error", (e) => _rej(rej(e))).once("finish", end).once(EPF, end);
 960      });
 961    },
 962    run() {
 963      from.run();
 964    },
 965    pipe(...args) {
 966      const dest = stream.pipe.apply(stream, args);
 967      return dest instanceof _ProcessPromise ? dest : _ProcessPromise.promisifyStream(dest, from);
 968    }
 969  });
 970  _ProcessPromise.bus.streams.set(stream, proxy);
 971  return proxy;
 972};
 973var ProcessPromise = _ProcessPromise;
 974var _ProcessOutput = class _ProcessOutput extends Error {
 975  // prettier-ignore
 976  constructor(code = null, signal = null, stdout = "", stderr = "", stdall = "", message = "", duration = 0, error = null, from = "", store = { stdout: [stdout], stderr: [stderr], stdall: [stdall] }) {
 977    super(message);
 978    const dto = code !== null && typeof code === "object" ? code : { code, signal, duration, error, from, store };
 979    Object.defineProperties(this, {
 980      _dto: { value: dto, enumerable: false },
 981      cause: { get() {
 982        return dto.error;
 983      }, enumerable: false },
 984      stdout: { get: (0, import_util.once)(() => (0, import_util.bufArrJoin)(dto.store.stdout)) },
 985      stderr: { get: (0, import_util.once)(() => (0, import_util.bufArrJoin)(dto.store.stderr)) },
 986      stdall: { get: (0, import_util.once)(() => (0, import_util.bufArrJoin)(dto.store.stdall)) },
 987      message: { get: (0, import_util.once)(
 988        () => dto.error || message ? _ProcessOutput.getErrorMessage(dto.error || new Error(message), dto.from) : _ProcessOutput.getExitMessage(
 989          dto.code,
 990          dto.signal,
 991          this.stderr,
 992          dto.from,
 993          this.stderr.trim() ? "" : _ProcessOutput.getErrorDetails(this.lines())
 994        )
 995      ) }
 996    });
 997  }
 998  get exitCode() {
 999    return this._dto.code;
1000  }
1001  get signal() {
1002    return this._dto.signal;
1003  }
1004  get duration() {
1005    return this._dto.duration;
1006  }
1007  get [Symbol.toStringTag]() {
1008    return "ProcessOutput";
1009  }
1010  get ok() {
1011    return !this._dto.error && this.exitCode === 0;
1012  }
1013  json() {
1014    return JSON.parse(this.stdall);
1015  }
1016  buffer() {
1017    return import_node_buffer.Buffer.from(this.stdall);
1018  }
1019  blob(type = "text/plain") {
1020    if (!globalThis.Blob)
1021      throw new Fail(
1022        "Blob is not supported in this environment. Provide a polyfill"
1023      );
1024    return new Blob([this.buffer()], { type });
1025  }
1026  text(encoding = "utf8") {
1027    return encoding === "utf8" ? this.toString() : this.buffer().toString(encoding);
1028  }
1029  lines(delimiter) {
1030    return (0, import_util.iteratorToArray)(this[Symbol.iterator](delimiter));
1031  }
1032  toString() {
1033    return this.stdall;
1034  }
1035  valueOf() {
1036    return this.stdall.trim();
1037  }
1038  [Symbol.toPrimitive]() {
1039    return this.valueOf();
1040  }
1041  // prettier-ignore
1042  *[Symbol.iterator](dlmtr = this._dto.delimiter || $.delimiter || DLMTR) {
1043    const memo = [];
1044    for (const chunk of this._dto.store.stdall) {
1045      yield* __yieldStar((0, import_util.getLines)(chunk, memo, dlmtr));
1046    }
1047    if (memo[0]) yield memo[0];
1048  }
1049  [import_node_util2.inspect.custom]() {
1050    const codeInfo = _ProcessOutput.getExitCodeInfo(this.exitCode);
1051    return `ProcessOutput {
1052  stdout: ${import_vendor_core2.chalk.green((0, import_node_util2.inspect)(this.stdout))},
1053  stderr: ${import_vendor_core2.chalk.red((0, import_node_util2.inspect)(this.stderr))},
1054  signal: ${(0, import_node_util2.inspect)(this.signal)},
1055  exitCode: ${(this.ok ? import_vendor_core2.chalk.green : import_vendor_core2.chalk.red)(this.exitCode)}${codeInfo ? import_vendor_core2.chalk.grey(" (" + codeInfo + ")") : ""},
1056  duration: ${this.duration}
1057}`;
1058  }
1059  static fromError(error) {
1060    const output = new _ProcessOutput();
1061    output._dto.error = error;
1062    return output;
1063  }
1064};
1065_ProcessOutput.getExitMessage = Fail.formatExitMessage;
1066_ProcessOutput.getErrorMessage = Fail.formatErrorMessage;
1067_ProcessOutput.getErrorDetails = Fail.formatErrorDetails;
1068_ProcessOutput.getExitCodeInfo = Fail.getExitCodeInfo;
1069var ProcessOutput = _ProcessOutput;
1070var useBash = () => setShell("bash", false);
1071var usePwsh = () => setShell("pwsh");
1072var usePowerShell = () => setShell("powershell.exe");
1073function setShell(n, ps3 = true) {
1074  $.shell = import_vendor_core2.which.sync(n);
1075  $.prefix = ps3 ? "" : "set -euo pipefail;";
1076  $.postfix = ps3 ? "; exit $LastExitCode" : "";
1077  $.quote = ps3 ? import_util.quotePowerShell : import_util.quote;
1078}
1079try {
1080  const { shell, prefix, postfix } = $;
1081  useBash();
1082  if ((0, import_util.isString)(shell)) $.shell = shell;
1083  if ((0, import_util.isString)(prefix)) $.prefix = prefix;
1084  if ((0, import_util.isString)(postfix)) $.postfix = postfix;
1085} catch (err) {
1086}
1087var cwdSyncHook;
1088function syncProcessCwd(flag = true) {
1089  cwdSyncHook = cwdSyncHook || (0, import_node_async_hooks.createHook)({
1090    init: syncCwd,
1091    before: syncCwd,
1092    promiseResolve: syncCwd,
1093    after: syncCwd,
1094    destroy: syncCwd
1095  });
1096  if (flag) cwdSyncHook.enable();
1097  else cwdSyncHook.disable();
1098}
1099function syncCwd() {
1100  if ($[CWD] != import_node_process2.default.cwd()) import_node_process2.default.chdir($[CWD]);
1101}
1102function cd(dir) {
1103  if (dir instanceof ProcessOutput) {
1104    dir = dir.toString().trim();
1105  }
1106  $.log({ kind: "cd", dir, verbose: !$.quiet && $.verbose });
1107  import_node_process2.default.chdir(dir);
1108  $[CWD] = import_node_process2.default.cwd();
1109}
1110function kill(_0) {
1111  return __async(this, arguments, function* (pid, signal = $.killSignal || SIGTERM) {
1112    if (typeof pid !== "number" && typeof pid !== "string" || !/^\d+$/.test(pid))
1113      throw new Fail(`Invalid pid: ${pid}`);
1114    $.log({ kind: "kill", pid, signal, verbose: !$.quiet && $.verbose });
1115    if (import_node_process2.default.platform === "win32" && (yield new Promise((resolve) => {
1116      import_node_child_process.default.exec(`taskkill /pid ${pid} /t /f`, (err) => resolve(!err));
1117    })))
1118      return;
1119    for (const p of yield import_vendor_core2.ps.tree({ pid, recursive: true })) {
1120      try {
1121        import_node_process2.default.kill(+p.pid, signal);
1122      } catch (e) {
1123      }
1124    }
1125    try {
1126      import_node_process2.default.kill(-pid, signal);
1127    } catch (e) {
1128      try {
1129        import_node_process2.default.kill(+pid, signal);
1130      } catch (e2) {
1131      }
1132    }
1133  });
1134}
1135function resolveDefaults(defs = defaults, prefix = ENV_PREFIX, env = import_node_process2.default.env, allowed = ENV_OPTS) {
1136  return Object.entries(env).reduce((m, [k, v]) => {
1137    if (v && k.startsWith(prefix)) {
1138      const _k = (0, import_util.toCamelCase)(k.slice(prefix.length));
1139      const _v = (0, import_util.parseBool)(v);
1140      if (allowed.has(_k)) m[_k] = _v;
1141    }
1142    return m;
1143  }, defs);
1144}
1145/* c8 ignore next 100 */
1146// Annotate the CommonJS export names for ESM import in node:
11470 && (module.exports = {
1148  $,
1149  Fail,
1150  ProcessOutput,
1151  ProcessPromise,
1152  bus,
1153  cd,
1154  chalk,
1155  defaults,
1156  kill,
1157  log,
1158  os,
1159  path,
1160  ps,
1161  quote,
1162  quotePowerShell,
1163  resolveDefaults,
1164  syncProcessCwd,
1165  useBash,
1166  usePowerShell,
1167  usePwsh,
1168  which,
1169  within
1170});