UNPKG

@botpress/adk-cli

Version:

Command-line interface for the Botpress Agent Development Kit (ADK)

3,520 lines 125 kB
// @bun
import {
  promptYesNo
} from "./chunk-62hm2spv.js";
import {
  require_adm_zip
} from "./chunk-8n02v208.js";
import {
  createCliLogger
} from "./chunk-gzwt1qdr.js";
import"./chunk-nxy2ya5r.js";
import"./chunk-wzj4dc7n.js";
import {
  AdkError,
  isAdkError
} from "./chunk-p0hjqn4r.js";
import"./chunk-np5wcwfv.js";
import"./chunk-dq2xpa24.js";
import"./chunk-6w0knnta.js";
import"./chunk-40x04ckt.js";
import"./chunk-t76d8fxx.js";
import"./chunk-nh2akp42.js";
import"./chunk-0fdvzjbh.js";
import"./chunk-2a5b6azq.js";
import"./chunk-vay209b5.js";
import"./chunk-3xrpxgq4.js";
import"./chunk-rfm3jr1m.js";
import"./chunk-w346ejn9.js";
import"./chunk-knvm2anf.js";
import"./chunk-65h5trb5.js";
import"./chunk-s2akeqpw.js";
import"./chunk-6771vrjp.js";
import"./chunk-g8mm42v1.js";
import"./chunk-50hzjdck.js";
import"./chunk-nn2jb0x0.js";
import"./chunk-v8xvth6j.js";
import"./chunk-kkk13rcb.js";
import"./chunk-ytpp1kam.js";
import"./chunk-na956zz3.js";
import"./chunk-f4bw8q7c.js";
import"./chunk-0v8vgrns.js";
import"./chunk-54qt5g7m.js";
import {
  __toESM
} from "./chunk-dhs2bg35.js";

// src/commands/upgrade.ts
import {
  existsSync,
  writeFileSync,
  chmodSync,
  renameSync,
  unlinkSync,
  readFileSync,
  mkdirSync,
  rmdirSync,
  accessSync,
  constants
} from "fs";
import { join, dirname, basename } from "path";
import { tmpdir } from "os";
import { execSync, spawnSync } from "child_process";

// ../../node_modules/.bun/tar@7.5.13/node_modules/tar/dist/esm/index.min.js
import Kr from "events";
import I from "fs";
import { EventEmitter as Ti } from "events";
import Ns from "stream";
import { StringDecoder as Mr } from "string_decoder";
import nr from "path";
import Vt from "fs";
import { dirname as xn, parse as Ln } from "path";
import { EventEmitter as _n } from "events";
import Mi from "assert";
import { Buffer as gt } from "buffer";
import * as ks from "zlib";
import qr from "zlib";
import { posix as Zt } from "path";
import { basename as wn } from "path";
import fi from "fs";
import $ from "fs";
import $s from "path";
import { win32 as In } from "path";
import sr from "path";
import Cr from "fs";
import so from "assert";
import { randomBytes as Ir } from "crypto";
import u from "fs";
import R from "path";
import cr from "fs";
import mi from "fs";
import Ee from "path";
import k from "fs";
import jn from "fs/promises";
import pi from "path";
import { join as br } from "path";
import v from "fs";
import Fr from "path";
var kr = Object.defineProperty;
var vr = (s, t) => {
  for (var e in t)
    kr(s, e, { get: t[e], enumerable: true });
};
var Os = typeof process == "object" && process ? process : { stdout: null, stderr: null };
var Br = (s) => !!s && typeof s == "object" && (s instanceof D || s instanceof Ns || Pr(s) || zr(s));
var Pr = (s) => !!s && typeof s == "object" && s instanceof Ti && typeof s.pipe == "function" && s.pipe !== Ns.Writable.prototype.pipe;
var zr = (s) => !!s && typeof s == "object" && s instanceof Ti && typeof s.write == "function" && typeof s.end == "function";
var q = Symbol("EOF");
var j = Symbol("maybeEmitEnd");
var rt = Symbol("emittedEnd");
var Le = Symbol("emittingEnd");
var jt = Symbol("emittedError");
var Ne = Symbol("closed");
var Ts = Symbol("read");
var Ae = Symbol("flush");
var xs = Symbol("flushChunk");
var z = Symbol("encoding");
var Mt = Symbol("decoder");
var b = Symbol("flowing");
var Qt = Symbol("paused");
var Bt = Symbol("resume");
var _ = Symbol("buffer");
var A = Symbol("pipes");
var g = Symbol("bufferLength");
var yi = Symbol("bufferPush");
var De = Symbol("bufferShift");
var L = Symbol("objectMode");
var w = Symbol("destroyed");
var Ri = Symbol("error");
var bi = Symbol("emitData");
var Ls = Symbol("emitEnd");
var _i = Symbol("emitEnd2");
var Z = Symbol("async");
var gi = Symbol("abort");
var Ie = Symbol("aborted");
var Jt = Symbol("signal");
var yt = Symbol("dataListeners");
var C = Symbol("discarded");
var te = (s) => Promise.resolve().then(s);
var Ur = (s) => s();
var Hr = (s) => s === "end" || s === "finish" || s === "prefinish";
var Wr = (s) => s instanceof ArrayBuffer || !!s && typeof s == "object" && s.constructor && s.constructor.name === "ArrayBuffer" && s.byteLength >= 0;
var Gr = (s) => !Buffer.isBuffer(s) && ArrayBuffer.isView(s);
var Ce = class {
  src;
  dest;
  opts;
  ondrain;
  constructor(t, e, i) {
    this.src = t, this.dest = e, this.opts = i, this.ondrain = () => t[Bt](), this.dest.on("drain", this.ondrain);
  }
  unpipe() {
    this.dest.removeListener("drain", this.ondrain);
  }
  proxyErrors(t) {}
  end() {
    this.unpipe(), this.opts.end && this.dest.end();
  }
};
var Oi = class extends Ce {
  unpipe() {
    this.src.removeListener("error", this.proxyErrors), super.unpipe();
  }
  constructor(t, e, i) {
    super(t, e, i), this.proxyErrors = (r) => this.dest.emit("error", r), t.on("error", this.proxyErrors);
  }
};
var Zr = (s) => !!s.objectMode;
var Yr = (s) => !s.objectMode && !!s.encoding && s.encoding !== "buffer";
var D = class extends Ti {
  [b] = false;
  [Qt] = false;
  [A] = [];
  [_] = [];
  [L];
  [z];
  [Z];
  [Mt];
  [q] = false;
  [rt] = false;
  [Le] = false;
  [Ne] = false;
  [jt] = null;
  [g] = 0;
  [w] = false;
  [Jt];
  [Ie] = false;
  [yt] = 0;
  [C] = false;
  writable = true;
  readable = true;
  constructor(...t) {
    let e = t[0] || {};
    if (super(), e.objectMode && typeof e.encoding == "string")
      throw new TypeError("Encoding and objectMode may not be used together");
    Zr(e) ? (this[L] = true, this[z] = null) : Yr(e) ? (this[z] = e.encoding, this[L] = false) : (this[L] = false, this[z] = null), this[Z] = !!e.async, this[Mt] = this[z] ? new Mr(this[z]) : null, e && e.debugExposeBuffer === true && Object.defineProperty(this, "buffer", { get: () => this[_] }), e && e.debugExposePipes === true && Object.defineProperty(this, "pipes", { get: () => this[A] });
    let { signal: i } = e;
    i && (this[Jt] = i, i.aborted ? this[gi]() : i.addEventListener("abort", () => this[gi]()));
  }
  get bufferLength() {
    return this[g];
  }
  get encoding() {
    return this[z];
  }
  set encoding(t) {
    throw new Error("Encoding must be set at instantiation time");
  }
  setEncoding(t) {
    throw new Error("Encoding must be set at instantiation time");
  }
  get objectMode() {
    return this[L];
  }
  set objectMode(t) {
    throw new Error("objectMode must be set at instantiation time");
  }
  get async() {
    return this[Z];
  }
  set async(t) {
    this[Z] = this[Z] || !!t;
  }
  [gi]() {
    this[Ie] = true, this.emit("abort", this[Jt]?.reason), this.destroy(this[Jt]?.reason);
  }
  get aborted() {
    return this[Ie];
  }
  set aborted(t) {}
  write(t, e, i) {
    if (this[Ie])
      return false;
    if (this[q])
      throw new Error("write after end");
    if (this[w])
      return this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" })), true;
    typeof e == "function" && (i = e, e = "utf8"), e || (e = "utf8");
    let r = this[Z] ? te : Ur;
    if (!this[L] && !Buffer.isBuffer(t)) {
      if (Gr(t))
        t = Buffer.from(t.buffer, t.byteOffset, t.byteLength);
      else if (Wr(t))
        t = Buffer.from(t);
      else if (typeof t != "string")
        throw new Error("Non-contiguous data written to non-objectMode stream");
    }
    return this[L] ? (this[b] && this[g] !== 0 && this[Ae](true), this[b] ? this.emit("data", t) : this[yi](t), this[g] !== 0 && this.emit("readable"), i && r(i), this[b]) : t.length ? (typeof t == "string" && !(e === this[z] && !this[Mt]?.lastNeed) && (t = Buffer.from(t, e)), Buffer.isBuffer(t) && this[z] && (t = this[Mt].write(t)), this[b] && this[g] !== 0 && this[Ae](true), this[b] ? this.emit("data", t) : this[yi](t), this[g] !== 0 && this.emit("readable"), i && r(i), this[b]) : (this[g] !== 0 && this.emit("readable"), i && r(i), this[b]);
  }
  read(t) {
    if (this[w])
      return null;
    if (this[C] = false, this[g] === 0 || t === 0 || t && t > this[g])
      return this[j](), null;
    this[L] && (t = null), this[_].length > 1 && !this[L] && (this[_] = [this[z] ? this[_].join("") : Buffer.concat(this[_], this[g])]);
    let e = this[Ts](t || null, this[_][0]);
    return this[j](), e;
  }
  [Ts](t, e) {
    if (this[L])
      this[De]();
    else {
      let i = e;
      t === i.length || t === null ? this[De]() : typeof i == "string" ? (this[_][0] = i.slice(t), e = i.slice(0, t), this[g] -= t) : (this[_][0] = i.subarray(t), e = i.subarray(0, t), this[g] -= t);
    }
    return this.emit("data", e), !this[_].length && !this[q] && this.emit("drain"), e;
  }
  end(t, e, i) {
    return typeof t == "function" && (i = t, t = undefined), typeof e == "function" && (i = e, e = "utf8"), t !== undefined && this.write(t, e), i && this.once("end", i), this[q] = true, this.writable = false, (this[b] || !this[Qt]) && this[j](), this;
  }
  [Bt]() {
    this[w] || (!this[yt] && !this[A].length && (this[C] = true), this[Qt] = false, this[b] = true, this.emit("resume"), this[_].length ? this[Ae]() : this[q] ? this[j]() : this.emit("drain"));
  }
  resume() {
    return this[Bt]();
  }
  pause() {
    this[b] = false, this[Qt] = true, this[C] = false;
  }
  get destroyed() {
    return this[w];
  }
  get flowing() {
    return this[b];
  }
  get paused() {
    return this[Qt];
  }
  [yi](t) {
    this[L] ? this[g] += 1 : this[g] += t.length, this[_].push(t);
  }
  [De]() {
    return this[L] ? this[g] -= 1 : this[g] -= this[_][0].length, this[_].shift();
  }
  [Ae](t = false) {
    do
      ;
    while (this[xs](this[De]()) && this[_].length);
    !t && !this[_].length && !this[q] && this.emit("drain");
  }
  [xs](t) {
    return this.emit("data", t), this[b];
  }
  pipe(t, e) {
    if (this[w])
      return t;
    this[C] = false;
    let i = this[rt];
    return e = e || {}, t === Os.stdout || t === Os.stderr ? e.end = false : e.end = e.end !== false, e.proxyErrors = !!e.proxyErrors, i ? e.end && t.end() : (this[A].push(e.proxyErrors ? new Oi(this, t, e) : new Ce(this, t, e)), this[Z] ? te(() => this[Bt]()) : this[Bt]()), t;
  }
  unpipe(t) {
    let e = this[A].find((i) => i.dest === t);
    e && (this[A].length === 1 ? (this[b] && this[yt] === 0 && (this[b] = false), this[A] = []) : this[A].splice(this[A].indexOf(e), 1), e.unpipe());
  }
  addListener(t, e) {
    return this.on(t, e);
  }
  on(t, e) {
    let i = super.on(t, e);
    if (t === "data")
      this[C] = false, this[yt]++, !this[A].length && !this[b] && this[Bt]();
    else if (t === "readable" && this[g] !== 0)
      super.emit("readable");
    else if (Hr(t) && this[rt])
      super.emit(t), this.removeAllListeners(t);
    else if (t === "error" && this[jt]) {
      let r = e;
      this[Z] ? te(() => r.call(this, this[jt])) : r.call(this, this[jt]);
    }
    return i;
  }
  removeListener(t, e) {
    return this.off(t, e);
  }
  off(t, e) {
    let i = super.off(t, e);
    return t === "data" && (this[yt] = this.listeners("data").length, this[yt] === 0 && !this[C] && !this[A].length && (this[b] = false)), i;
  }
  removeAllListeners(t) {
    let e = super.removeAllListeners(t);
    return (t === "data" || t === undefined) && (this[yt] = 0, !this[C] && !this[A].length && (this[b] = false)), e;
  }
  get emittedEnd() {
    return this[rt];
  }
  [j]() {
    !this[Le] && !this[rt] && !this[w] && this[_].length === 0 && this[q] && (this[Le] = true, this.emit("end"), this.emit("prefinish"), this.emit("finish"), this[Ne] && this.emit("close"), this[Le] = false);
  }
  emit(t, ...e) {
    let i = e[0];
    if (t !== "error" && t !== "close" && t !== w && this[w])
      return false;
    if (t === "data")
      return !this[L] && !i ? false : this[Z] ? (te(() => this[bi](i)), true) : this[bi](i);
    if (t === "end")
      return this[Ls]();
    if (t === "close") {
      if (this[Ne] = true, !this[rt] && !this[w])
        return false;
      let n = super.emit("close");
      return this.removeAllListeners("close"), n;
    } else if (t === "error") {
      this[jt] = i, super.emit(Ri, i);
      let n = !this[Jt] || this.listeners("error").length ? super.emit("error", i) : false;
      return this[j](), n;
    } else if (t === "resume") {
      let n = super.emit("resume");
      return this[j](), n;
    } else if (t === "finish" || t === "prefinish") {
      let n = super.emit(t);
      return this.removeAllListeners(t), n;
    }
    let r = super.emit(t, ...e);
    return this[j](), r;
  }
  [bi](t) {
    for (let i of this[A])
      i.dest.write(t) === false && this.pause();
    let e = this[C] ? false : super.emit("data", t);
    return this[j](), e;
  }
  [Ls]() {
    return this[rt] ? false : (this[rt] = true, this.readable = false, this[Z] ? (te(() => this[_i]()), true) : this[_i]());
  }
  [_i]() {
    if (this[Mt]) {
      let e = this[Mt].end();
      if (e) {
        for (let i of this[A])
          i.dest.write(e);
        this[C] || super.emit("data", e);
      }
    }
    for (let e of this[A])
      e.end();
    let t = super.emit("end");
    return this.removeAllListeners("end"), t;
  }
  async collect() {
    let t = Object.assign([], { dataLength: 0 });
    this[L] || (t.dataLength = 0);
    let e = this.promise();
    return this.on("data", (i) => {
      t.push(i), this[L] || (t.dataLength += i.length);
    }), await e, t;
  }
  async concat() {
    if (this[L])
      throw new Error("cannot concat in objectMode");
    let t = await this.collect();
    return this[z] ? t.join("") : Buffer.concat(t, t.dataLength);
  }
  async promise() {
    return new Promise((t, e) => {
      this.on(w, () => e(new Error("stream destroyed"))), this.on("error", (i) => e(i)), this.on("end", () => t());
    });
  }
  [Symbol.asyncIterator]() {
    this[C] = false;
    let t = false, e = async () => (this.pause(), t = true, { value: undefined, done: true });
    return { next: () => {
      if (t)
        return e();
      let r = this.read();
      if (r !== null)
        return Promise.resolve({ done: false, value: r });
      if (this[q])
        return e();
      let n, o, h = (d) => {
        this.off("data", a), this.off("end", l), this.off(w, c), e(), o(d);
      }, a = (d) => {
        this.off("error", h), this.off("end", l), this.off(w, c), this.pause(), n({ value: d, done: !!this[q] });
      }, l = () => {
        this.off("error", h), this.off("data", a), this.off(w, c), e(), n({ done: true, value: undefined });
      }, c = () => h(new Error("stream destroyed"));
      return new Promise((d, S) => {
        o = S, n = d, this.once(w, c), this.once("error", h), this.once("end", l), this.once("data", a);
      });
    }, throw: e, return: e, [Symbol.asyncIterator]() {
      return this;
    }, [Symbol.asyncDispose]: async () => {} };
  }
  [Symbol.iterator]() {
    this[C] = false;
    let t = false, e = () => (this.pause(), this.off(Ri, e), this.off(w, e), this.off("end", e), t = true, { done: true, value: undefined }), i = () => {
      if (t)
        return e();
      let r = this.read();
      return r === null ? e() : { done: false, value: r };
    };
    return this.once("end", e), this.once(Ri, e), this.once(w, e), { next: i, throw: e, return: e, [Symbol.iterator]() {
      return this;
    }, [Symbol.dispose]: () => {} };
  }
  destroy(t) {
    if (this[w])
      return t ? this.emit("error", t) : this.emit(w), this;
    this[w] = true, this[C] = true, this[_].length = 0, this[g] = 0;
    let e = this;
    return typeof e.close == "function" && !this[Ne] && e.close(), t ? this.emit("error", t) : this.emit(w), this;
  }
  static get isStream() {
    return Br;
  }
};
var Vr = I.writev;
var ot = Symbol("_autoClose");
var H = Symbol("_close");
var ee = Symbol("_ended");
var m = Symbol("_fd");
var xi = Symbol("_finished");
var J = Symbol("_flags");
var Li = Symbol("_flush");
var Ii = Symbol("_handleChunk");
var Ci = Symbol("_makeBuf");
var se = Symbol("_mode");
var Fe = Symbol("_needDrain");
var Ut = Symbol("_onerror");
var Ht = Symbol("_onopen");
var Ni = Symbol("_onread");
var Pt = Symbol("_onwrite");
var ht = Symbol("_open");
var U = Symbol("_path");
var nt = Symbol("_pos");
var Y = Symbol("_queue");
var zt = Symbol("_read");
var Ai = Symbol("_readSize");
var Q = Symbol("_reading");
var ie = Symbol("_remain");
var Di = Symbol("_size");
var ke = Symbol("_write");
var Rt = Symbol("_writing");
var ve = Symbol("_defaultFlag");
var bt = Symbol("_errored");
var _t = class extends D {
  [bt] = false;
  [m];
  [U];
  [Ai];
  [Q] = false;
  [Di];
  [ie];
  [ot];
  constructor(t, e) {
    if (e = e || {}, super(e), this.readable = true, this.writable = false, typeof t != "string")
      throw new TypeError("path must be a string");
    this[bt] = false, this[m] = typeof e.fd == "number" ? e.fd : undefined, this[U] = t, this[Ai] = e.readSize || 16 * 1024 * 1024, this[Q] = false, this[Di] = typeof e.size == "number" ? e.size : 1 / 0, this[ie] = this[Di], this[ot] = typeof e.autoClose == "boolean" ? e.autoClose : true, typeof this[m] == "number" ? this[zt]() : this[ht]();
  }
  get fd() {
    return this[m];
  }
  get path() {
    return this[U];
  }
  write() {
    throw new TypeError("this is a readable stream");
  }
  end() {
    throw new TypeError("this is a readable stream");
  }
  [ht]() {
    I.open(this[U], "r", (t, e) => this[Ht](t, e));
  }
  [Ht](t, e) {
    t ? this[Ut](t) : (this[m] = e, this.emit("open", e), this[zt]());
  }
  [Ci]() {
    return Buffer.allocUnsafe(Math.min(this[Ai], this[ie]));
  }
  [zt]() {
    if (!this[Q]) {
      this[Q] = true;
      let t = this[Ci]();
      if (t.length === 0)
        return process.nextTick(() => this[Ni](null, 0, t));
      I.read(this[m], t, 0, t.length, null, (e, i, r) => this[Ni](e, i, r));
    }
  }
  [Ni](t, e, i) {
    this[Q] = false, t ? this[Ut](t) : this[Ii](e, i) && this[zt]();
  }
  [H]() {
    if (this[ot] && typeof this[m] == "number") {
      let t = this[m];
      this[m] = undefined, I.close(t, (e) => e ? this.emit("error", e) : this.emit("close"));
    }
  }
  [Ut](t) {
    this[Q] = true, this[H](), this.emit("error", t);
  }
  [Ii](t, e) {
    let i = false;
    return this[ie] -= t, t > 0 && (i = super.write(t < e.length ? e.subarray(0, t) : e)), (t === 0 || this[ie] <= 0) && (i = false, this[H](), super.end()), i;
  }
  emit(t, ...e) {
    switch (t) {
      case "prefinish":
      case "finish":
        return false;
      case "drain":
        return typeof this[m] == "number" && this[zt](), false;
      case "error":
        return this[bt] ? false : (this[bt] = true, super.emit(t, ...e));
      default:
        return super.emit(t, ...e);
    }
  }
};
var Me = class extends _t {
  [ht]() {
    let t = true;
    try {
      this[Ht](null, I.openSync(this[U], "r")), t = false;
    } finally {
      t && this[H]();
    }
  }
  [zt]() {
    let t = true;
    try {
      if (!this[Q]) {
        this[Q] = true;
        do {
          let e = this[Ci](), i = e.length === 0 ? 0 : I.readSync(this[m], e, 0, e.length, null);
          if (!this[Ii](i, e))
            break;
        } while (true);
        this[Q] = false;
      }
      t = false;
    } finally {
      t && this[H]();
    }
  }
  [H]() {
    if (this[ot] && typeof this[m] == "number") {
      let t = this[m];
      this[m] = undefined, I.closeSync(t), this.emit("close");
    }
  }
};
var tt = class extends Kr {
  readable = false;
  writable = true;
  [bt] = false;
  [Rt] = false;
  [ee] = false;
  [Y] = [];
  [Fe] = false;
  [U];
  [se];
  [ot];
  [m];
  [ve];
  [J];
  [xi] = false;
  [nt];
  constructor(t, e) {
    e = e || {}, super(e), this[U] = t, this[m] = typeof e.fd == "number" ? e.fd : undefined, this[se] = e.mode === undefined ? 438 : e.mode, this[nt] = typeof e.start == "number" ? e.start : undefined, this[ot] = typeof e.autoClose == "boolean" ? e.autoClose : true;
    let i = this[nt] !== undefined ? "r+" : "w";
    this[ve] = e.flags === undefined, this[J] = e.flags === undefined ? i : e.flags, this[m] === undefined && this[ht]();
  }
  emit(t, ...e) {
    if (t === "error") {
      if (this[bt])
        return false;
      this[bt] = true;
    }
    return super.emit(t, ...e);
  }
  get fd() {
    return this[m];
  }
  get path() {
    return this[U];
  }
  [Ut](t) {
    this[H](), this[Rt] = true, this.emit("error", t);
  }
  [ht]() {
    I.open(this[U], this[J], this[se], (t, e) => this[Ht](t, e));
  }
  [Ht](t, e) {
    this[ve] && this[J] === "r+" && t && t.code === "ENOENT" ? (this[J] = "w", this[ht]()) : t ? this[Ut](t) : (this[m] = e, this.emit("open", e), this[Rt] || this[Li]());
  }
  end(t, e) {
    return t && this.write(t, e), this[ee] = true, !this[Rt] && !this[Y].length && typeof this[m] == "number" && this[Pt](null, 0), this;
  }
  write(t, e) {
    return typeof t == "string" && (t = Buffer.from(t, e)), this[ee] ? (this.emit("error", new Error("write() after end()")), false) : this[m] === undefined || this[Rt] || this[Y].length ? (this[Y].push(t), this[Fe] = true, false) : (this[Rt] = true, this[ke](t), true);
  }
  [ke](t) {
    I.write(this[m], t, 0, t.length, this[nt], (e, i) => this[Pt](e, i));
  }
  [Pt](t, e) {
    t ? this[Ut](t) : (this[nt] !== undefined && typeof e == "number" && (this[nt] += e), this[Y].length ? this[Li]() : (this[Rt] = false, this[ee] && !this[xi] ? (this[xi] = true, this[H](), this.emit("finish")) : this[Fe] && (this[Fe] = false, this.emit("drain"))));
  }
  [Li]() {
    if (this[Y].length === 0)
      this[ee] && this[Pt](null, 0);
    else if (this[Y].length === 1)
      this[ke](this[Y].pop());
    else {
      let t = this[Y];
      this[Y] = [], Vr(this[m], t, this[nt], (e, i) => this[Pt](e, i));
    }
  }
  [H]() {
    if (this[ot] && typeof this[m] == "number") {
      let t = this[m];
      this[m] = undefined, I.close(t, (e) => e ? this.emit("error", e) : this.emit("close"));
    }
  }
};
var Wt = class extends tt {
  [ht]() {
    let t;
    if (this[ve] && this[J] === "r+")
      try {
        t = I.openSync(this[U], this[J], this[se]);
      } catch (e) {
        if (e?.code === "ENOENT")
          return this[J] = "w", this[ht]();
        throw e;
      }
    else
      t = I.openSync(this[U], this[J], this[se]);
    this[Ht](null, t);
  }
  [H]() {
    if (this[ot] && typeof this[m] == "number") {
      let t = this[m];
      this[m] = undefined, I.closeSync(t), this.emit("close");
    }
  }
  [ke](t) {
    let e = true;
    try {
      this[Pt](null, I.writeSync(this[m], t, 0, t.length, this[nt])), e = false;
    } finally {
      if (e)
        try {
          this[H]();
        } catch {}
    }
  }
};
var $r = new Map([["C", "cwd"], ["f", "file"], ["z", "gzip"], ["P", "preservePaths"], ["U", "unlink"], ["strip-components", "strip"], ["stripComponents", "strip"], ["keep-newer", "newer"], ["keepNewer", "newer"], ["keep-newer-files", "newer"], ["keepNewerFiles", "newer"], ["k", "keep"], ["keep-existing", "keep"], ["keepExisting", "keep"], ["m", "noMtime"], ["no-mtime", "noMtime"], ["p", "preserveOwner"], ["L", "follow"], ["h", "follow"], ["onentry", "onReadEntry"]]);
var As = (s) => !!s.sync && !!s.file;
var Ds = (s) => !s.sync && !!s.file;
var Is = (s) => !!s.sync && !s.file;
var Cs = (s) => !s.sync && !s.file;
var Fs = (s) => !!s.file;
var Xr = (s) => {
  let t = $r.get(s);
  return t || s;
};
var re = (s = {}) => {
  if (!s)
    return {};
  let t = {};
  for (let [e, i] of Object.entries(s)) {
    let r = Xr(e);
    t[r] = i;
  }
  return t.chmod === undefined && t.noChmod === false && (t.chmod = true), delete t.noChmod, t;
};
var K = (s, t, e, i, r) => Object.assign((n = [], o, h) => {
  Array.isArray(n) && (o = n, n = {}), typeof o == "function" && (h = o, o = undefined), o = o ? Array.from(o) : [];
  let a = re(n);
  if (r?.(a, o), As(a)) {
    if (typeof h == "function")
      throw new TypeError("callback not supported for sync tar functions");
    return s(a, o);
  } else if (Ds(a)) {
    let l = t(a, o);
    return h ? l.then(() => h(), h) : l;
  } else if (Is(a)) {
    if (typeof h == "function")
      throw new TypeError("callback not supported for sync tar functions");
    return e(a, o);
  } else if (Cs(a)) {
    if (typeof h == "function")
      throw new TypeError("callback only supported with file option");
    return i(a, o);
  }
  throw new Error("impossible options??");
}, { syncFile: s, asyncFile: t, syncNoFile: e, asyncNoFile: i, validate: r });
var jr = qr.constants || { ZLIB_VERNUM: 4736 };
var M = Object.freeze(Object.assign(Object.create(null), { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8, BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: 1 / 0, Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1, BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1, BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3, BROTLI_MODE_GENERIC: 0, BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0, BROTLI_MIN_QUALITY: 0, BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11, BROTLI_MIN_WINDOW_BITS: 10, BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30, BROTLI_DEFAULT_WINDOW: 22, BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24, BROTLI_PARAM_MODE: 0, BROTLI_PARAM_QUALITY: 1, BROTLI_PARAM_LGWIN: 2, BROTLI_PARAM_LGBLOCK: 3, BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6, BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8, BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1, BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1, BROTLI_DECODER_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, BROTLI_DECODER_ERROR_UNREACHABLE: -31 }, jr));
var Qr = gt.concat;
var vs = Object.getOwnPropertyDescriptor(gt, "concat");
var Jr = (s) => s;
var ki = vs?.writable === true || vs?.set !== undefined ? (s) => {
  gt.concat = s ? Jr : Qr;
} : (s) => {};
var Ot = Symbol("_superWrite");
var Gt = class extends Error {
  code;
  errno;
  constructor(t, e) {
    super("zlib: " + t.message, { cause: t }), this.code = t.code, this.errno = t.errno, this.code || (this.code = "ZLIB_ERROR"), this.message = "zlib: " + t.message, Error.captureStackTrace(this, e ?? this.constructor);
  }
  get name() {
    return "ZlibError";
  }
};
var vi = Symbol("flushFlag");
var ne = class extends D {
  #t = false;
  #i = false;
  #s;
  #n;
  #r;
  #e;
  #o;
  get sawError() {
    return this.#t;
  }
  get handle() {
    return this.#e;
  }
  get flushFlag() {
    return this.#s;
  }
  constructor(t, e) {
    if (!t || typeof t != "object")
      throw new TypeError("invalid options for ZlibBase constructor");
    if (super(t), this.#s = t.flush ?? 0, this.#n = t.finishFlush ?? 0, this.#r = t.fullFlushFlag ?? 0, typeof ks[e] != "function")
      throw new TypeError("Compression method not supported: " + e);
    try {
      this.#e = new ks[e](t);
    } catch (i) {
      throw new Gt(i, this.constructor);
    }
    this.#o = (i) => {
      this.#t || (this.#t = true, this.close(), this.emit("error", i));
    }, this.#e?.on("error", (i) => this.#o(new Gt(i))), this.once("end", () => this.close);
  }
  close() {
    this.#e && (this.#e.close(), this.#e = undefined, this.emit("close"));
  }
  reset() {
    if (!this.#t)
      return Mi(this.#e, "zlib binding closed"), this.#e.reset?.();
  }
  flush(t) {
    this.ended || (typeof t != "number" && (t = this.#r), this.write(Object.assign(gt.alloc(0), { [vi]: t })));
  }
  end(t, e, i) {
    return typeof t == "function" && (i = t, e = undefined, t = undefined), typeof e == "function" && (i = e, e = undefined), t && (e ? this.write(t, e) : this.write(t)), this.flush(this.#n), this.#i = true, super.end(i);
  }
  get ended() {
    return this.#i;
  }
  [Ot](t) {
    return super.write(t);
  }
  write(t, e, i) {
    if (typeof e == "function" && (i = e, e = "utf8"), typeof t == "string" && (t = gt.from(t, e)), this.#t)
      return;
    Mi(this.#e, "zlib binding closed");
    let r = this.#e._handle, n = r.close;
    r.close = () => {};
    let o = this.#e.close;
    this.#e.close = () => {}, ki(true);
    let h;
    try {
      let l = typeof t[vi] == "number" ? t[vi] : this.#s;
      h = this.#e._processChunk(t, l), ki(false);
    } catch (l) {
      ki(false), this.#o(new Gt(l, this.write));
    } finally {
      this.#e && (this.#e._handle = r, r.close = n, this.#e.close = o, this.#e.removeAllListeners("error"));
    }
    this.#e && this.#e.on("error", (l) => this.#o(new Gt(l, this.write)));
    let a;
    if (h)
      if (Array.isArray(h) && h.length > 0) {
        let l = h[0];
        a = this[Ot](gt.from(l));
        for (let c = 1;c < h.length; c++)
          a = this[Ot](h[c]);
      } else
        a = this[Ot](gt.from(h));
    return i && i(), a;
  }
};
var Be = class extends ne {
  #t;
  #i;
  constructor(t, e) {
    t = t || {}, t.flush = t.flush || M.Z_NO_FLUSH, t.finishFlush = t.finishFlush || M.Z_FINISH, t.fullFlushFlag = M.Z_FULL_FLUSH, super(t, e), this.#t = t.level, this.#i = t.strategy;
  }
  params(t, e) {
    if (!this.sawError) {
      if (!this.handle)
        throw new Error("cannot switch params when binding is closed");
      if (!this.handle.params)
        throw new Error("not supported in this implementation");
      if (this.#t !== t || this.#i !== e) {
        this.flush(M.Z_SYNC_FLUSH), Mi(this.handle, "zlib binding closed");
        let i = this.handle.flush;
        this.handle.flush = (r, n) => {
          typeof r == "function" && (n = r, r = this.flushFlag), this.flush(r), n?.();
        };
        try {
          this.handle.params(t, e);
        } finally {
          this.handle.flush = i;
        }
        this.handle && (this.#t = t, this.#i = e);
      }
    }
  }
};
var Pe = class extends Be {
  #t;
  constructor(t) {
    super(t, "Gzip"), this.#t = t && !!t.portable;
  }
  [Ot](t) {
    return this.#t ? (this.#t = false, t[9] = 255, super[Ot](t)) : super[Ot](t);
  }
};
var ze = class extends Be {
  constructor(t) {
    super(t, "Unzip");
  }
};
var Ue = class extends ne {
  constructor(t, e) {
    t = t || {}, t.flush = t.flush || M.BROTLI_OPERATION_PROCESS, t.finishFlush = t.finishFlush || M.BROTLI_OPERATION_FINISH, t.fullFlushFlag = M.BROTLI_OPERATION_FLUSH, super(t, e);
  }
};
var He = class extends Ue {
  constructor(t) {
    super(t, "BrotliCompress");
  }
};
var We = class extends Ue {
  constructor(t) {
    super(t, "BrotliDecompress");
  }
};
var Ge = class extends ne {
  constructor(t, e) {
    t = t || {}, t.flush = t.flush || M.ZSTD_e_continue, t.finishFlush = t.finishFlush || M.ZSTD_e_end, t.fullFlushFlag = M.ZSTD_e_flush, super(t, e);
  }
};
var Ze = class extends Ge {
  constructor(t) {
    super(t, "ZstdCompress");
  }
};
var Ye = class extends Ge {
  constructor(t) {
    super(t, "ZstdDecompress");
  }
};
var Ms = (s, t) => {
  if (Number.isSafeInteger(s))
    s < 0 ? sn(s, t) : en(s, t);
  else
    throw Error("cannot encode number outside of javascript safe integer range");
  return t;
};
var en = (s, t) => {
  t[0] = 128;
  for (var e = t.length;e > 1; e--)
    t[e - 1] = s & 255, s = Math.floor(s / 256);
};
var sn = (s, t) => {
  t[0] = 255;
  var e = false;
  s = s * -1;
  for (var i = t.length;i > 1; i--) {
    var r = s & 255;
    s = Math.floor(s / 256), e ? t[i - 1] = Ps(r) : r === 0 ? t[i - 1] = 0 : (e = true, t[i - 1] = zs(r));
  }
};
var Bs = (s) => {
  let t = s[0], e = t === 128 ? nn(s.subarray(1, s.length)) : t === 255 ? rn(s) : null;
  if (e === null)
    throw Error("invalid base256 encoding");
  if (!Number.isSafeInteger(e))
    throw Error("parsed number outside of javascript safe integer range");
  return e;
};
var rn = (s) => {
  for (var t = s.length, e = 0, i = false, r = t - 1;r > -1; r--) {
    var n = Number(s[r]), o;
    i ? o = Ps(n) : n === 0 ? o = n : (i = true, o = zs(n)), o !== 0 && (e -= o * Math.pow(256, t - r - 1));
  }
  return e;
};
var nn = (s) => {
  for (var t = s.length, e = 0, i = t - 1;i > -1; i--) {
    var r = Number(s[i]);
    r !== 0 && (e += r * Math.pow(256, t - i - 1));
  }
  return e;
};
var Ps = (s) => (255 ^ s) & 255;
var zs = (s) => (255 ^ s) + 1 & 255;
var Bi = {};
vr(Bi, { code: () => Ke, isCode: () => oe, isName: () => hn, name: () => he });
var oe = (s) => he.has(s);
var hn = (s) => Ke.has(s);
var he = new Map([["0", "File"], ["", "OldFile"], ["1", "Link"], ["2", "SymbolicLink"], ["3", "CharacterDevice"], ["4", "BlockDevice"], ["5", "Directory"], ["6", "FIFO"], ["7", "ContiguousFile"], ["g", "GlobalExtendedHeader"], ["x", "ExtendedHeader"], ["A", "SolarisACL"], ["D", "GNUDumpDir"], ["I", "Inode"], ["K", "NextFileHasLongLinkpath"], ["L", "NextFileHasLongPath"], ["M", "ContinuationFile"], ["N", "OldGnuLongPath"], ["S", "SparseFile"], ["V", "TapeVolumeHeader"], ["X", "OldExtendedHeader"]]);
var Ke = new Map(Array.from(he).map((s) => [s[1], s[0]]));
var F = class {
  cksumValid = false;
  needPax = false;
  nullBlock = false;
  block;
  path;
  mode;
  uid;
  gid;
  size;
  cksum;
  #t = "Unsupported";
  linkpath;
  uname;
  gname;
  devmaj = 0;
  devmin = 0;
  atime;
  ctime;
  mtime;
  charset;
  comment;
  constructor(t, e = 0, i, r) {
    Buffer.isBuffer(t) ? this.decode(t, e || 0, i, r) : t && this.#i(t);
  }
  decode(t, e, i, r) {
    if (e || (e = 0), !t || !(t.length >= e + 512))
      throw new Error("need 512 bytes for header");
    this.path = i?.path ?? Tt(t, e, 100), this.mode = i?.mode ?? r?.mode ?? at(t, e + 100, 8), this.uid = i?.uid ?? r?.uid ?? at(t, e + 108, 8), this.gid = i?.gid ?? r?.gid ?? at(t, e + 116, 8), this.size = i?.size ?? r?.size ?? at(t, e + 124, 12), this.mtime = i?.mtime ?? r?.mtime ?? Pi(t, e + 136, 12), this.cksum = at(t, e + 148, 12), r && this.#i(r, true), i && this.#i(i);
    let n = Tt(t, e + 156, 1);
    if (oe(n) && (this.#t = n || "0"), this.#t === "0" && this.path.slice(-1) === "/" && (this.#t = "5"), this.#t === "5" && (this.size = 0), this.linkpath = Tt(t, e + 157, 100), t.subarray(e + 257, e + 265).toString() === "ustar\x0000")
      if (this.uname = i?.uname ?? r?.uname ?? Tt(t, e + 265, 32), this.gname = i?.gname ?? r?.gname ?? Tt(t, e + 297, 32), this.devmaj = i?.devmaj ?? r?.devmaj ?? at(t, e + 329, 8) ?? 0, this.devmin = i?.devmin ?? r?.devmin ?? at(t, e + 337, 8) ?? 0, t[e + 475] !== 0) {
        let h = Tt(t, e + 345, 155);
        this.path = h + "/" + this.path;
      } else {
        let h = Tt(t, e + 345, 130);
        h && (this.path = h + "/" + this.path), this.atime = i?.atime ?? r?.atime ?? Pi(t, e + 476, 12), this.ctime = i?.ctime ?? r?.ctime ?? Pi(t, e + 488, 12);
      }
    let o = 256;
    for (let h = e;h < e + 148; h++)
      o += t[h];
    for (let h = e + 156;h < e + 512; h++)
      o += t[h];
    this.cksumValid = o === this.cksum, this.cksum === undefined && o === 256 && (this.nullBlock = true);
  }
  #i(t, e = false) {
    Object.assign(this, Object.fromEntries(Object.entries(t).filter(([i, r]) => !(r == null || i === "path" && e || i === "linkpath" && e || i === "global"))));
  }
  encode(t, e = 0) {
    if (t || (t = this.block = Buffer.alloc(512)), this.#t === "Unsupported" && (this.#t = "0"), !(t.length >= e + 512))
      throw new Error("need 512 bytes for header");
    let i = this.ctime || this.atime ? 130 : 155, r = an(this.path || "", i), n = r[0], o = r[1];
    this.needPax = !!r[2], this.needPax = xt(t, e, 100, n) || this.needPax, this.needPax = lt(t, e + 100, 8, this.mode) || this.needPax, this.needPax = lt(t, e + 108, 8, this.uid) || this.needPax, this.needPax = lt(t, e + 116, 8, this.gid) || this.needPax, this.needPax = lt(t, e + 124, 12, this.size) || this.needPax, this.needPax = zi(t, e + 136, 12, this.mtime) || this.needPax, t[e + 156] = Number(this.#t.codePointAt(0)), this.needPax = xt(t, e + 157, 100, this.linkpath) || this.needPax, t.write("ustar\x0000", e + 257, 8), this.needPax = xt(t, e + 265, 32, this.uname) || this.needPax, this.needPax = xt(t, e + 297, 32, this.gname) || this.needPax, this.needPax = lt(t, e + 329, 8, this.devmaj) || this.needPax, this.needPax = lt(t, e + 337, 8, this.devmin) || this.needPax, this.needPax = xt(t, e + 345, i, o) || this.needPax, t[e + 475] !== 0 ? this.needPax = xt(t, e + 345, 155, o) || this.needPax : (this.needPax = xt(t, e + 345, 130, o) || this.needPax, this.needPax = zi(t, e + 476, 12, this.atime) || this.needPax, this.needPax = zi(t, e + 488, 12, this.ctime) || this.needPax);
    let h = 256;
    for (let a = e;a < e + 148; a++)
      h += t[a];
    for (let a = e + 156;a < e + 512; a++)
      h += t[a];
    return this.cksum = h, lt(t, e + 148, 8, this.cksum), this.cksumValid = true, this.needPax;
  }
  get type() {
    return this.#t === "Unsupported" ? this.#t : he.get(this.#t);
  }
  get typeKey() {
    return this.#t;
  }
  set type(t) {
    let e = String(Ke.get(t));
    if (oe(e) || e === "Unsupported")
      this.#t = e;
    else if (oe(t))
      this.#t = t;
    else
      throw new TypeError("invalid entry type: " + t);
  }
};
var an = (s, t) => {
  let i = s, r = "", n, o = Zt.parse(s).root || ".";
  if (Buffer.byteLength(i) < 100)
    n = [i, r, false];
  else {
    r = Zt.dirname(i), i = Zt.basename(i);
    do
      Buffer.byteLength(i) <= 100 && Buffer.byteLength(r) <= t ? n = [i, r, false] : Buffer.byteLength(i) > 100 && Buffer.byteLength(r) <= t ? n = [i.slice(0, 99), r, true] : (i = Zt.join(Zt.basename(r), i), r = Zt.dirname(r));
    while (r !== o && n === undefined);
    n || (n = [s.slice(0, 99), "", true]);
  }
  return n;
};
var Tt = (s, t, e) => s.subarray(t, t + e).toString("utf8").replace(/\0.*/, "");
var Pi = (s, t, e) => ln(at(s, t, e));
var ln = (s) => s === undefined ? undefined : new Date(s * 1000);
var at = (s, t, e) => Number(s[t]) & 128 ? Bs(s.subarray(t, t + e)) : fn(s, t, e);
var cn = (s) => isNaN(s) ? undefined : s;
var fn = (s, t, e) => cn(parseInt(s.subarray(t, t + e).toString("utf8").replace(/\0.*$/, "").trim(), 8));
var dn = { 12: 8589934591, 8: 2097151 };
var lt = (s, t, e, i) => i === undefined ? false : i > dn[e] || i < 0 ? (Ms(i, s.subarray(t, t + e)), true) : (un(s, t, e, i), false);
var un = (s, t, e, i) => s.write(mn(i, e), t, e, "ascii");
var mn = (s, t) => pn(Math.floor(s).toString(8), t);
var pn = (s, t) => (s.length === t - 1 ? s : new Array(t - s.length - 1).join("0") + s + " ") + "\x00";
var zi = (s, t, e, i) => i === undefined ? false : lt(s, t, e, i.getTime() / 1000);
var En = new Array(156).join("\x00");
var xt = (s, t, e, i) => i === undefined ? false : (s.write(i + En, t, e, "utf8"), i.length !== Buffer.byteLength(i) || i.length > e);
var ct = class s {
  atime;
  mtime;
  ctime;
  charset;
  comment;
  gid;
  uid;
  gname;
  uname;
  linkpath;
  dev;
  ino;
  nlink;
  path;
  size;
  mode;
  global;
  constructor(t, e = false) {
    this.atime = t.atime, this.charset = t.charset, this.comment = t.comment, this.ctime = t.ctime, this.dev = t.dev, this.gid = t.gid, this.global = e, this.gname = t.gname, this.ino = t.ino, this.linkpath = t.linkpath, this.mtime = t.mtime, this.nlink = t.nlink, this.path = t.path, this.size = t.size, this.uid = t.uid, this.uname = t.uname;
  }
  encode() {
    let t = this.encodeBody();
    if (t === "")
      return Buffer.allocUnsafe(0);
    let e = Buffer.byteLength(t), i = 512 * Math.ceil(1 + e / 512), r = Buffer.allocUnsafe(i);
    for (let n = 0;n < 512; n++)
      r[n] = 0;
    new F({ path: ("PaxHeader/" + wn(this.path ?? "")).slice(0, 99), mode: this.mode || 420, uid: this.uid, gid: this.gid, size: e, mtime: this.mtime, type: this.global ? "GlobalExtendedHeader" : "ExtendedHeader", linkpath: "", uname: this.uname || "", gname: this.gname || "", devmaj: 0, devmin: 0, atime: this.atime, ctime: this.ctime }).encode(r), r.write(t, 512, e, "utf8");
    for (let n = e + 512;n < r.length; n++)
      r[n] = 0;
    return r;
  }
  encodeBody() {
    return this.encodeField("path") + this.encodeField("ctime") + this.encodeField("atime") + this.encodeField("dev") + this.encodeField("ino") + this.encodeField("nlink") + this.encodeField("charset") + this.encodeField("comment") + this.encodeField("gid") + this.encodeField("gname") + this.encodeField("linkpath") + this.encodeField("mtime") + this.encodeField("size") + this.encodeField("uid") + this.encodeField("uname");
  }
  encodeField(t) {
    if (this[t] === undefined)
      return "";
    let e = this[t], i = e instanceof Date ? e.getTime() / 1000 : e, r = " " + (t === "dev" || t === "ino" || t === "nlink" ? "SCHILY." : "") + t + "=" + i + `
`, n = Buffer.byteLength(r), o = Math.floor(Math.log(n) / Math.log(10)) + 1;
    return n + o >= Math.pow(10, o) && (o += 1), o + n + r;
  }
  static parse(t, e, i = false) {
    return new s(Sn(yn(t), e), i);
  }
};
var Sn = (s2, t) => t ? Object.assign({}, t, s2) : s2;
var yn = (s2) => s2.replace(/\n$/, "").split(`
`).reduce(Rn, Object.create(null));
var Rn = (s2, t) => {
  let e = parseInt(t, 10);
  if (e !== Buffer.byteLength(t) + 1)
    return s2;
  t = t.slice((e + " ").length);
  let i = t.split("="), r = i.shift();
  if (!r)
    return s2;
  let n = r.replace(/^SCHILY\.(dev|ino|nlink)/, "$1"), o = i.join("=");
  return s2[n] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(n) ? new Date(Number(o) * 1000) : /^[0-9]+$/.test(o) ? +o : o, s2;
};
var bn = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
var f = bn !== "win32" ? (s2) => s2 : (s2) => s2 && s2.replaceAll(/\\/g, "/");
var Yt = class extends D {
  extended;
  globalExtended;
  header;
  startBlockSize;
  blockRemain;
  remain;
  type;
  meta = false;
  ignore = false;
  path;
  mode;
  uid;
  gid;
  uname;
  gname;
  size = 0;
  mtime;
  atime;
  ctime;
  linkpath;
  dev;
  ino;
  nlink;
  invalid = false;
  absolute;
  unsupported = false;
  constructor(t, e, i) {
    switch (super({}), this.pause(), this.extended = e, this.globalExtended = i, this.header = t, this.remain = t.size ?? 0, this.startBlockSize = 512 * Math.ceil(this.remain / 512), this.blockRemain = this.startBlockSize, this.type = t.type, this.type) {
      case "File":
      case "OldFile":
      case "Link":
      case "SymbolicLink":
      case "CharacterDevice":
      case "BlockDevice":
      case "Directory":
      case "FIFO":
      case "ContiguousFile":
      case "GNUDumpDir":
        break;
      case "NextFileHasLongLinkpath":
      case "NextFileHasLongPath":
      case "OldGnuLongPath":
      case "GlobalExtendedHeader":
      case "ExtendedHeader":
      case "OldExtendedHeader":
        this.meta = true;
        break;
      default:
        this.ignore = true;
    }
    if (!t.path)
      throw new Error("no path provided for tar.ReadEntry");
    this.path = f(t.path), this.mode = t.mode, this.mode && (this.mode = this.mode & 4095), this.uid = t.uid, this.gid = t.gid, this.uname = t.uname, this.gname = t.gname, this.size = this.remain, this.mtime = t.mtime, this.atime = t.atime, this.ctime = t.ctime, this.linkpath = t.linkpath ? f(t.linkpath) : undefined, this.uname = t.uname, this.gname = t.gname, e && this.#t(e), i && this.#t(i, true);
  }
  write(t) {
    let e = t.length;
    if (e > this.blockRemain)
      throw new Error("writing more to entry than is appropriate");
    let i = this.remain, r = this.blockRemain;
    return this.remain = Math.max(0, i - e), this.blockRemain = Math.max(0, r - e), this.ignore ? true : i >= e ? super.write(t) : super.write(t.subarray(0, i));
  }
  #t(t, e = false) {
    t.path && (t.path = f(t.path)), t.linkpath && (t.linkpath = f(t.linkpath)), Object.assign(this, Object.fromEntries(Object.entries(t).filter(([i, r]) => !(r == null || i === "path" && e))));
  }
};
var Lt = (s2, t, e, i = {}) => {
  s2.file && (i.file = s2.file), s2.cwd && (i.cwd = s2.cwd), i.code = e instanceof Error && e.code || t, i.tarCode = t, !s2.strict && i.recoverable !== false ? (e instanceof Error && (i = Object.assign(e, i), e = e.message), s2.emit("warn", t, e, i)) : e instanceof Error ? s2.emit("error", Object.assign(e, i)) : s2.emit("error", Object.assign(new Error(`${t}: ${e}`), i));
};
var gn = 1024 * 1024;
var Zi = Buffer.from([31, 139]);
var Yi = Buffer.from([40, 181, 47, 253]);
var On = Math.max(Zi.length, Yi.length);
var B = Symbol("state");
var Nt = Symbol("writeEntry");
var et = Symbol("readEntry");
var Ui = Symbol("nextEntry");
var Us = Symbol("processEntry");
var V = Symbol("extendedHeader");
var ae = Symbol("globalExtendedHeader");
var ft = Symbol("meta");
var Hs = Symbol("emitMeta");
var p = Symbol("buffer");
var it = Symbol("queue");
var dt = Symbol("ended");
var Hi = Symbol("emittedEnd");
var At = Symbol("emit");
var y = Symbol("unzip");
var Ve = Symbol("consumeChunk");
var $e = Symbol("consumeChunkSub");
var Wi = Symbol("consumeBody");
var Ws = Symbol("consumeMeta");
var Gs = Symbol("consumeHeader");
var le = Symbol("consuming");
var Gi = Symbol("bufferConcat");
var Xe = Symbol("maybeEnd");
var Kt = Symbol("writing");
var ut = Symbol("aborted");
var qe = Symbol("onDone");
var Dt = Symbol("sawValidEntry");
var je = Symbol("sawNullBlock");
var Qe = Symbol("sawEOF");
var Zs = Symbol("closeStream");
var Tn = () => true;
var st = class extends _n {
  file;
  strict;
  maxMetaEntrySize;
  filter;
  brotli;
  zstd;
  writable = true;
  readable = false;
  [it] = [];
  [p];
  [et];
  [Nt];
  [B] = "begin";
  [ft] = "";
  [V];
  [ae];
  [dt] = false;
  [y];
  [ut] = false;
  [Dt];
  [je] = false;
  [Qe] = false;
  [Kt] = false;
  [le] = false;
  [Hi] = false;
  constructor(t = {}) {
    super(), this.file = t.file || "", this.on(qe, () => {
      (this[B] === "begin" || this[Dt] === false) && this.warn("TAR_BAD_ARCHIVE", "Unrecognized archive format");
    }), t.ondone ? this.on(qe, t.ondone) : this.on(qe, () => {
      this.emit("prefinish"), this.emit("finish"), this.emit("end");
    }), this.strict = !!t.strict, this.maxMetaEntrySize = t.maxMetaEntrySize || gn, this.filter = typeof t.filter == "function" ? t.filter : Tn;
    let e = t.file && (t.file.endsWith(".tar.br") || t.file.endsWith(".tbr"));
    this.brotli = !(t.gzip || t.zstd) && t.brotli !== undefined ? t.brotli : e ? undefined : false;
    let i = t.file && (t.file.endsWith(".tar.zst") || t.file.endsWith(".tzst"));
    this.zstd = !(t.gzip || t.brotli) && t.zstd !== undefined ? t.zstd : i ? true : undefined, this.on("end", () => this[Zs]()), typeof t.onwarn == "function" && this.on("warn", t.onwarn), typeof t.onReadEntry == "function" && this.on("entry", t.onReadEntry);
  }
  warn(t, e, i = {}) {
    Lt(this, t, e, i);
  }
  [Gs](t, e) {
    this[Dt] === undefined && (this[Dt] = false);
    let i;
    try {
      i = new F(t, e, this[V], this[ae]);
    } catch (r) {
      return this.warn("TAR_ENTRY_INVALID", r);
    }
    if (i.nullBlock)
      this[je] ? (this[Qe] = true, this[B] === "begin" && (this[B] = "header"), this[At]("eof")) : (this[je] = true, this[At]("nullBlock"));
    else if (this[je] = false, !i.cksumValid)
      this.warn("TAR_ENTRY_INVALID", "checksum failure", { header: i });
    else if (!i.path)
      this.warn("TAR_ENTRY_INVALID", "path is required", { header: i });
    else {
      let r = i.type;
      if (/^(Symbolic)?Link$/.test(r) && !i.linkpath)
        this.warn("TAR_ENTRY_INVALID", "linkpath required", { header: i });
      else if (!/^(Symbolic)?Link$/.test(r) && !/^(Global)?ExtendedHeader$/.test(r) && i.linkpath)
        this.warn("TAR_ENTRY_INVALID", "linkpath forbidden", { header: i });
      else {
        let n = this[Nt] = new Yt(i, this[V], this[ae]);
        if (!this[Dt])
          if (n.remain) {
            let o = () => {
              n.invalid || (this[Dt] = true);
            };
            n.on("end", o);
          } else
            this[Dt] = true;
        n.meta ? n.size > this.maxMetaEntrySize ? (n.ignore = true, this[At]("ignoredEntry", n), this[B] = "ignore", n.resume()) : n.size > 0 && (this[ft] = "", n.on("data", (o) => this[ft] += o), this[B] = "meta") : (this[V] = undefined, n.ignore = n.ignore || !this.filter(n.path, n), n.ignore ? (this[At]("ignoredEntry", n), this[B] = n.remain ? "ignore" : "header", n.resume()) : (n.remain ? this[B] = "body" : (this[B] = "header", n.end()), this[et] ? this[it].push(n) : (this[it].push(n), this[Ui]())));
      }
    }
  }
  [Zs]() {
    queueMicrotask(() => this.emit("close"));
  }
  [Us](t) {
    let e = true;
    if (!t)
      this[et] = undefined, e = false;
    else if (Array.isArray(t)) {
      let [i, ...r] = t;
      this.emit(i, ...r);
    } else
      this[et] = t, this.emit("entry", t), t.emittedEnd || (t.on("end", () => this[Ui]()), e = false);
    return e;
  }
  [Ui]() {
    do
      ;
    while (this[Us](this[it].shift()));
    if (this[it].length === 0) {
      let t = this[et];
      !t || t.flowing || t.size === t.remain ? this[Kt] || this.emit("drain") : t.once("drain", () => this.emit("drain"));
    }
  }
  [Wi](t, e) {
    let i = this[Nt];
    if (!i)
      throw new Error("attempt to consume body without entry??");
    let r = i.blockRemain ?? 0, n = r >= t.length && e === 0 ? t : t.subarray(e, e + r);
    return i.write(n), i.blockRemain || (this[B] = "header", this[Nt] = undefined, i.end()), n.length;
  }
  [Ws](t, e) {
    let i = this[Nt], r = this[Wi](t, e);
    return !this[Nt] && i && this[Hs](i), r;
  }
  [At](t, e, i) {
    this[it].length === 0 && !this[et] ? this.emit(t, e, i) : this[it].push([t, e, i]);
  }
  [Hs](t) {
    switch (this[At]("meta", this[ft]), t.type) {
      case "ExtendedHeader":
      case "OldExtendedHeader":
        this[V] = ct.parse(this[ft], this[V], false);
        break;
      case "GlobalExtendedHeader":
        this[ae] = ct.parse(this[ft], this[ae], true);
        break;
      case "NextFileHasLongPath":
      case "OldGnuLongPath": {
        let e = this[V] ?? Object.create(null);
        this[V] = e, e.path = this[ft].replace(/\0.*/, "");
        break;
      }
      case "NextFileHasLongLinkpath": {
        let e = this[V] || Object.create(null);
        this[V] = e, e.linkpath = this[ft].replace(/\0.*/, "");
        break;
      }
      default:
        throw new Error("unknown meta: " + t.type);
    }
  }
  abort(t) {
    this[ut] = true, this.emit("abort", t), this.warn("TAR_ABORT", t, { recoverable: false });
  }
  write(t, e, i) {
    if (typeof e == "function" && (i = e, e = undefined), typeof t == "string" && (t = Buffer.from(t, typeof e == "string" ? e : "utf8")), this[ut])
      return i?.(), false;
    if ((this[y] === undefined || this.brotli === undefined && this[y] === false) && t) {
      if (this[p] && (t = Buffer.concat([this[p], t]), this[p] = undefined), t.length < On)
        return this[p] = t, i?.(), true;
      for (let a = 0;this[y] === undefined && a < Zi.length; a++)
        t[a] !== Zi[a] && (this[y] = false);
      let o = false;
      if (this[y] === false && this.zstd !== false) {
        o = true;
        for (let a = 0;a < Yi.length; a++)
          if (t[a] !== Yi[a]) {
            o = false;
            break;
          }
      }
      let h = this.brotli === undefined && !o;
      if (this[y] === false && h)
        if (t.length < 512)
          if (this[dt])
            this.brotli = true;
          else
            return this[p] = t, i?.(), true;
        else
          try {
            new F(t.subarray(0, 512)), this.brotli = false;
          } catch {
            this.brotli = true;
          }
      if (this[y] === undefined || this[y] === false && (this.brotli || o)) {
        let a = this[dt];
        this[dt] = false, this[y] = this[y] === undefined ? new ze({}) : o ? new Ye({}) : new We({}), this[y].on("data", (c) => this[Ve](c)), this[y].on("error", (c) => this.abort(c)), this[y].on("end", () => {
          this[dt] = true, this[Ve]();
        }), this[Kt] = true;
        let l = !!this[y][a ? "end" : "write"](t);
        return this[Kt] = false, i?.(), l;
      }
    }
    this[Kt] = true, this[y] ? this[y].write(t) : this[Ve](t), this[Kt] = false;
    let n = this[it].length > 0 ? false : this[et] ? this[et].flowing : true;
    return !n && this[it].length === 0 && this[et]?.once("drain", () => this.emit("drain")), i?.(), n;
  }
  [Gi](t) {
    t && !this[ut] && (this[p] = this[p] ? Buffer.concat([this[p], t]) : t);
  }
  [Xe]() {
    if (this[dt] && !this[Hi] && !this[ut] && !this[le]) {
      this[Hi] = true;
      let t = this[Nt];
      if (t && t.blockRemain) {
        let e = this[p] ? this[p].length : 0;
        this.warn("TAR_BAD_ARCHIVE", `Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`, { entry: t }), this[p] && t.write(this[p]), t.end();
      }
      this[At](qe);
    }
  }
  [Ve](t) {
    if (this[le] && t)
      this[Gi](t);
    else if (!t && !this[p])
      this[Xe]();
    else if (t) {
      if (this[le] = true, this[p]) {
        this[Gi](t);
        let e = this[p];
        this[p] = undefined, this[$e](e);
      } else
        this[$e](t);
      for (;this[p] && this[p]?.length >= 512 && !this[ut] && !this[Qe]; ) {
        let e = this[p];
        this[p] = undefined, this[$e](e);
      }
      this[le] = false;
    }
    (!this[p] || this[dt]) && this[Xe]();
  }
  [$e](t) {
    let e = 0, i = t.length;
    for (;e + 512 <= i && !this[ut] && !this[Qe]; )
      switch (this[B]) {
        case "begin":
        case "header":
          this[Gs](t, e), e += 512;
          break;
        case "ignore":
        case "body":
          e += this[Wi](t, e);
          break;
        case "meta":
          e += this[Ws](t, e);
          break;
        default:
          throw new Error("invalid state: " + this[B]);
      }
    e < i && (this[p] = this[p] ? Buffer.concat([t.subarray(e), this[p]]) : t.subarray(e));
  }
  end(t, e, i) {
    return typeof t == "function" && (i = t, e = undefined, t = undefined), typeof e == "function" && (i = e, e = undefined), typeof t == "string" && (t = Buffer.from(t, e)), i && this.once("finish", i), this[ut] || (this[y] ? (t && this[y].write(t), this[y].end()) : (this[dt] = true, (this.brotli === undefined || this.zstd === undefined) && (t = t || Buffer.alloc(0)), t && this.write(t), this[Xe]())), this;
  }
};
var mt = (s2) => {
  let t = s2.length - 1, e = -1;
  for (;t > -1 && s2.charAt(t) === "/"; )
    e = t, t--;
  return e === -1 ? s2 : s2.slice(0, e);
};
var Nn = (s2) => {
  let t = s2.onReadEntry;
  s2.onReadEntry = t ? (e) => {
    t(e), e.resume();
  } : (e) => e.resume();
};
var Ki = (s2, t) => {
  let e = new Map(t.map((n) => [mt(n), true])), i = s2.filter, r = (n, o = "") => {
    let h = o || Ln(n).root || ".", a;
    if (n === h)
      a = false;
    else {
      let l = e.get(n);
      a = l !== undefined ? l : r(xn(n), h);
    }
    return e.set(n, a), a;
  };
  s2.filter = i ? (n, o) => i(n, o) && r(mt(n)) : (n) => r(mt(n));
};
var An = (s2) => {
  let t = new st(s2), e = s2.file, i;
  try {
    i = Vt.openSync(e, "r");
    let r = Vt.fstatSync(i), n = s2.maxReadSize || 16 * 1024 * 1024;
    if (r.size < n) {
      let o = Buffer.allocUnsafe(r.size), h = Vt.readSync(i, o, 0, r.size, 0);
      t.end(h === o.byteLength ? o : o.subarray(0, h));
    } else {
      let o = 0, h = Buffer.allocUnsafe(n);
      for (;o < r.size; ) {
        let a = Vt.readSync(i, h, 0, n, o);
        if (a === 0)
          break;
        o += a, t.write(h.subarray(0, a));
      }
      t.end();
    }
  } finally {
    if (typeof i == "number")
      try {
        Vt.closeSync(i);
      } catch {}
  }
};
var Dn = (s2, t) => {
  let e = new st(s2), i = s2.maxReadSize || 16 * 1024 * 1024, r = s2.file;
  return new Promise((o, h) => {
    e.on("error", h), e.on("end", o), Vt.stat(r, (a, l) => {
      if (a)
        h(a);
      else {
        let c = new _t(r, { readSize: i, size: l.size });
        c.on("error", h), c.pipe(e);
      }
    });
  });
};
var It = K(An, Dn, (s2) => new st(s2), (s2) => new st(s2), (s2, t) => {
  t?.length && Ki(s2, t), s2.noResume || Nn(s2);
});
var Vi = (s2, t, e) => (s2 &= 4095, e && (s2 = (s2 | 384) & -19), t && (s2 & 256 && (s2 |= 64), s2 & 32 && (s2 |= 8), s2 & 4 && (s2 |= 1)), s2);
var { isAbsolute: Cn, parse: Ys } = In;
var ce = (s2) => {
  let t = "", e = Ys(s2);
  for (;Cn(s2) || e.root; ) {
    let i = s2.charAt(0) === "/" && s2.slice(0, 4) !== "//?/" ? "/" : e.root;
    s2 = s2.slice(i.length), t += i, e = Ys(s2);
  }
  return [t, s2];
};
var Je = ["|", "<", ">", "?", ":"];
var $i = Je.map((s2) => String.fromCodePoint(61440 + Number(s2.codePointAt(0))));
var Fn = new Map(Je.map((s2, t) => [s2, $i[t]]));
var kn = new Map($i.map((s2, t) => [s2, Je[t]]));
var Xi = (s2) => Je.reduce((t, e) => t.split(e).join(Fn.get(e)), s2);
var Ks = (s2) => $i.reduce((t, e) => t.split(e).join(kn.get(e)), s2);
var Js = (s2, t) => t ? (s2 = f(s2).replace(/^\.(\/|$)/, ""), mt(t) + "/" + s2) : f(s2);
var vn = 16 * 1024 * 1024;
var Xs = Symbol("process");
var qs = Symbol("file");
var js = Symbol("directory");
var ji = Symbol("symlink");
var Qs = Symbol("hardlink");
var fe = Symbol("header");
var ti = Symbol("read");
var Qi = Symbol("lstat");
var ei = Symbol("onlstat");
var Ji = Symbol("onread");
var ts = Symbol("onreadlink");
var es = Symbol("openfile");
var is = Symbol("onopenfile");
var pt = Symbol("close");
var ii = Symbol("mode");
var ss = Symbol("awaitDrain");
var qi = Symbol("ondrain");
var X = Symbol("prefix");
var de = class extends D {
  path;
  portable;
  myuid = process.getuid && process.getuid() || 0;
  myuser = process.env.USER || "";
  maxReadSize;
  linkCache;
  statCache;
  preservePaths;
  cwd;
  strict;
  mtime;
  noPax;
  noMtime;
  prefix;
  fd;
  blockLen = 0;
  blockRemain = 0;
  buf;
  pos = 0;
  remain = 0;
  length = 0;
  offset = 0;
  win32;
  absolute;
  header;
  type;
  linkpath;
  stat;
  onWriteEntry;
  #t = false;
  constructor(t, e = {}) {
    let i = re(e);
    super(), this.path = f(t), this.portable = !!i.portable, this.maxReadSize = i.maxReadSize || vn, this.linkCache = i.linkCache || new Map, this.statCache = i.statCache || new Map, this.preservePaths = !!i.preservePaths, this.cwd = f(i.cwd || process.cwd()), this.strict = !!i.strict, this.noPax = !!i.noPax, this.noMtime = !!i.noMtime, this.mtime = i.mtime, this.prefix = i.prefix ? f(i.prefix) : undefined, this.onWriteEntry = i.onWriteEntry, typeof i.onwarn == "function" && this.on("warn", i.onwarn);
    let r = false;
    if (!this.preservePaths) {
      let [o, h] = ce(this.path);
      o && typeof h == "string" && (this.path = h, r = o);
    }
    this.win32 = !!i.win32 || process.platform === "win32", this.win32 && (this.path = Ks(this.path.replaceAll(/\\/g, "/")), t = t.replaceAll(/\\/g, "/")), this.absolute = f(i.absolute || $s.resolve(this.cwd, t)), this.path === "" && (this.path = "./"), r && this.warn("TAR_ENTRY_INFO", `stripping ${r} from absolute path`, { entry: this, path: r + this.path });
    let n = this.statCache.get(this.absolute);
    n ? this[ei](n) : this[Qi]();
  }
  warn(t, e, i = {}) {
    return Lt(this, t, e, i);
  }
  emit(t, ...e) {
    return t === "error" && (this.#t = true), super.emit(t, ...e);
  }
  [Qi]() {
    $.lstat(this.absolute, (t, e) => {
      if (t)
        return this.emit("error", t);
      this[ei](e);
    });
  }
  [ei](t) {
    this.statCache.set(this.absolute, t), this.stat = t, t.isFile() || (t.size = 0), this.type = Mn(t), this.emit("stat", t), this[Xs]();
  }
  [Xs]() {
    switch (this.type) {
      case "File":
        return this[qs]();
      case "Directory":
        return this[js]();
      case "SymbolicLink":
        return this[ji]();
      default:
        return this.end();
    }
  }
  [ii](t) {
    return Vi(t, this.type === "Directory", this.portable);
  }
  [X](t) {
    return Js(t, this.prefix);
  }
  [fe]() {
    if (!this.stat)
      throw new Error("cannot write header before stat");
    this.type === "Directory" && this.portable && (this.noMtime = true), this.onWriteEntry?.(this), this.header = new F({ path: this[X](this.path), linkpath: this.type === "Link" && this.linkpath !== undefined ? this[X](this.linkpath) : this.linkpath, mode: this[ii](this.stat.mode), uid: this.portable ? undefined : this.stat.uid, gid: this.portable ? undefined : this.stat.gid, size: this.stat.size, mtime: this.noMtime ? undefined : this.mtime || this.stat.mtime, type: this.type === "Unsupported" ? undefined : this.type, uname: this.portable ? undefined : this.stat.uid === this.myuid ? this.myuser : "", atime: this.portable ? undefined : this.stat.atime, ctime: this.portable ? undefined : this.stat.ctime }), this.header.encode() && !this.noPax && super.write(new ct({ atime: this.portable ? undefined : this.header.atime, ctime: this.portable ? undefined : this.header.ctime, gid: this.portable ? undefined : this.header.gid, mtime: this.noMtime ? undefined : this.mtime || this.header.mtime, path: this[X](this.path), linkpath: this.type === "Link" && this.linkpath !== undefined ? this[X](this.linkpath) : this.linkpath, size: this.header.size, uid: this.portable ? undefined : this.header.uid, uname: this.portable ? undefined : this.header.uname, dev: this.portable ? undefined : this.stat.dev, ino: this.portable ? undefined : this.stat.ino, nlink: this.portable ? undefined : this.stat.nlink }).encode());
    let t = this.header?.block;
    if (!t)
      throw new Error("failed to encode header");
    super.write(t);
  }
  [js]() {
    if (!this.stat)
      throw new Error("cannot create directory entry without stat");
    this.path.slice(-1) !== "/" && (this.path += "/"), this.stat.size = 0, this[fe](), this.end();
  }
  [ji]() {
    $.readlink(this.absolute, (t, e) => {
      if (t)
        return this.emit("error", t);
      this[ts](e);
    });
  }
  [ts](t) {
    this.linkpath = f(t), this[fe](), this.end();
  }
  [Qs](t) {
    if (!this.stat)
      throw new Error("cannot create link entry without stat");
    this.type = "Link", this.linkpath = f($s.relative(this.cwd, t)), this.stat.size = 0, this[fe](), this.end();
  }
  [qs]() {
    if (!this.stat)
      throw new Error("cannot create file entry without stat");
    if (this.stat.nlink > 1) {
      let t = `${this.stat.dev}:${this.stat.ino}`, e = this.linkCache.get(t);
      if (e?.indexOf(this.cwd) === 0)
        return this[Qs](e);
      this.linkCache.set(t, this.absolute);
    }
    if (this[fe](), this.stat.size === 0)
      return this.end();
    this[es]();
  }
  [es]() {
    $.open(this.absolute, "r", (t, e) => {
      if (t)
        return this.emit("error", t);
      this[is](e);
    });
  }
  [is](t) {
    if (this.fd = t, this.#t)
      return this[pt]();
    if (!this.stat)
      throw new Error("should stat before calling onopenfile");
    this.blockLen = 512 * Math.ceil(this.stat.size / 512), this.blockRemain = this.blockLen;
    let e = Math.min(this.blockLen, this.maxReadSize);
    this.buf = Buffer.allocUnsafe(e), this.offset = 0, this.pos = 0, this.remain = this.stat.size, this.length = this.buf.length, this[ti]();
  }
  [ti]() {
    let { fd: t, buf: e, offset: i, length: r, pos: n } = this;
    if (t === undefined || e === undefined)
      throw new Error("cannot read file without first opening");
    $.read(t, e, i, r, n, (o, h) => {
      if (o)
        return this[pt](() => this.emit("error", o));
      this[Ji](h);
    });
  }
  [pt](t = () => {}) {
    this.fd !== undefined && $.close(this.fd, t);
  }
  [Ji](t) {
    if (t <= 0 && this.remain > 0) {
      let r = Object.assign(new Error("encountered unexpected EOF"), { path: this.absolute, syscall: "read", code: "EOF" });
      return this[pt](() => this.emit("error", r));
    }
    if (t > this.remain) {
      let r = Object.assign(new Error("did not encounter expected EOF"), { path: this.absolute, syscall: "read", code: "EOF" });
      return this[pt](() => this.emit("error", r));
    }
    if (!this.buf)
      throw new Error("should have created buffer prior to reading");
    if (t === this.remain)
      for (let r = t;r < this.length && t < this.blockRemain; r++)
        this.buf[r + this.offset] = 0, t++, this.remain++;
    let e = this.offset === 0 && t === this.buf.length ? this.buf : this.buf.subarray(this.offset, this.offset + t);
    this.write(e) ? this[qi]() : this[ss](() => this[qi]());
  }
  [ss](t) {
    this.once("drain", t);
  }
  write(t, e, i) {
    if (typeof e == "function" && (i = e, e = undefined), typeof t == "string" && (t = Buffer.from(t, typeof e == "string" ? e : "utf8")), this.blockRemain < t.length) {
      let r = Object.assign(new Error("writing more data than expected"), { path: this.absolute });
      return this.emit("error", r);
    }
    return this.remain -= t.length, this.blockRemain -= t.length, this.pos += t.length, this.offset += t.length, super.write(t, null, i);
  }
  [qi]() {
    if (!this.remain)
      return this.blockRemain && super.write(Buffer.alloc(this.blockRemain)), this[pt]((t) => t ? this.emit("error", t) : this.end());
    if (!this.buf)
      throw new Error("buffer lost somehow in ONDRAIN");
    this.offset >= this.length && (this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)), this.offset = 0), this.length = this.buf.length - this.offset, this[ti]();
  }
};
var si = class extends de {
  sync = true;
  [Qi]() {
    this[ei]($.lstatSync(this.absolute));
  }
  [ji]() {
    this[ts]($.readlinkSync(this.absolute));
  }
  [es]() {
    this[is]($.openSync(this.absolute, "r"));
  }
  [ti]() {
    let t = true;
    try {
      let { fd: e, buf: i, offset: r, length: n, pos: o } = this;
      if (e === undefined || i === undefined)
        throw new Error("fd and buf must be set in READ method");
      let h = $.readSync(e, i, r, n, o);
      this[Ji](h), t = false;
    } finally {
      if (t)
        try {
          this[pt](() => {});
        } catch {}
    }
  }
  [ss](t) {
    t();
  }
  [pt](t = () => {}) {
    this.fd !== undefined && $.closeSync(this.fd), t();
  }
};
var ri = class extends D {
  blockLen = 0;
  blockRemain = 0;
  buf = 0;
  pos = 0;
  remain = 0;
  length = 0;
  preservePaths;
  portable;
  strict;
  noPax;
  noMtime;
  readEntry;
  type;
  prefix;
  path;
  mode;
  uid;
  gid;
  uname;
  gname;
  header;
  mtime;
  atime;
  ctime;
  linkpath;
  size;
  onWriteEntry;
  warn(t, e, i = {}) {
    return Lt(this, t, e, i);
  }
  constructor(t, e = {}) {
    let i = re(e);
    super(), this.preservePaths = !!i.preservePaths, this.portable = !!i.portable, this.strict = !!i.strict, this.noPax = !!i.noPax, this.noMtime = !!i.noMtime, this.onWriteEntry = i.onWriteEntry, this.readEntry = t;
    let { type: r } = t;
    if (r === "Unsupported")
      throw new Error("writing entry that should be ignored");
    this.type = r, this.type === "Directory" && this.portable && (this.noMtime = true), this.prefix = i.prefix, this.path = f(t.path), this.mode = t.mode !== undefined ? this[ii](t.mode) : undefined, this.uid = this.portable ? undefined : t.uid, this.gid = this.portable ? undefined : t.gid, this.uname = this.portable ? undefined : t.uname, this.gname = this.portable ? undefined : t.gname, this.size = t.size, this.mtime = this.noMtime ? undefined : i.mtime || t.mtime, this.atime = this.portable ? undefined : t.atime, this.ctime = this.portable ? undefined : t.ctime, this.linkpath = t.linkpath !== undefined ? f(t.linkpath) : undefined, typeof i.onwarn == "function" && this.on("warn", i.onwarn);
    let n = false;
    if (!this.preservePaths) {
      let [h, a] = ce(this.path);
      h && typeof a == "string" && (this.path = a, n = h);
    }
    this.remain = t.size, this.blockRemain = t.startBlockSize, this.onWriteEntry?.(this), this.header = new F({ path: this[X](this.path), linkpath: this.type === "Link" && this.linkpath !== undefined ? this[X](this.linkpath) : this.linkpath, mode: this.mode, uid: this.portable ? undefined : this.uid, gid: this.portable ? undefined : this.gid, size: this.size, mtime: this.noMtime ? undefined : this.mtime, type: this.type, uname: this.portable ? undefined : this.uname, atime: this.portable ? undefined : this.atime, ctime: this.portable ? undefined : this.ctime }), n && this.warn("TAR_ENTRY_INFO", `stripping ${n} from absolute path`, { entry: this, path: n + this.path }), this.header.encode() && !this.noPax && super.write(new ct({ atime: this.portable ? undefined : this.atime, ctime: this.portable ? undefined : this.ctime, gid: this.portable ? undefined : this.gid, mtime: this.noMtime ? undefined : this.mtime, path: this[X](this.path), linkpath: this.type === "Link" && this.linkpath !== undefined ? this[X](this.linkpath) : this.linkpath, size: this.size, uid: this.portable ? undefined : this.uid, uname: this.portable ? undefined : this.uname, dev: this.portable ? undefined : this.readEntry.dev, ino: this.portable ? undefined : this.readEntry.ino, nlink: this.portable ? undefined : this.readEntry.nlink }).encode());
    let o = this.header?.block;
    if (!o)
      throw new Error("failed to encode header");
    super.write(o), t.pipe(this);
  }
  [X](t) {
    return Js(t, this.prefix);
  }
  [ii](t) {
    return Vi(t, this.type === "Directory", this.portable);
  }
  write(t, e, i) {
    typeof e == "function" && (i = e, e = undefined), typeof t == "string" && (t = Buffer.from(t, typeof e == "string" ? e : "utf8"));
    let r = t.length;
    if (r > this.blockRemain)
      throw new Error("writing more to entry than is appropriate");
    return this.blockRemain -= r, super.write(t, i);
  }
  end(t, e, i) {
    return this.blockRemain && super.write(Buffer.alloc(this.blockRemain)), typeof t == "function" && (i = t, e = undefined, t = undefined), typeof e == "function" && (i = e, e = undefined), typeof t == "string" && (t = Buffer.from(t, e ?? "utf8")), i && this.once("finish", i), t ? super.end(t, i) : super.end(i), this;
  }
};
var Mn = (s2) => s2.isFile() ? "File" : s2.isDirectory() ? "Directory" : s2.isSymbolicLink() ? "SymbolicLink" : "Unsupported";
var ni = class s2 {
  tail;
  head;
  length = 0;
  static create(t = []) {
    return new s2(t);
  }
  constructor(t = []) {
    for (let e of t)
      this.push(e);
  }
  *[Symbol.iterator]() {
    for (let t = this.head;t; t = t.next)
      yield t.value;
  }
  removeNode(t) {
    if (t.list !== this)
      throw new Error("removing node which does not belong to this list");
    let { next: e, prev: i } = t;
    return e && (e.prev = i), i && (i.next = e), t === this.head && (this.head = e), t === this.tail && (this.tail = i), this.length--, t.next = undefined, t.prev = undefined, t.list = undefined, e;
  }
  unshiftNode(t) {
    if (t === this.head)
      return;
    t.list && t.list.removeNode(t);
    let e = this.head;
    t.list = this, t.next = e, e && (e.prev = t), this.head = t, this.tail || (this.tail = t), this.length++;
  }
  pushNode(t) {
    if (t === this.tail)
      return;
    t.list && t.list.removeNode(t);
    let e = this.tail;
    t.list = this, t.prev = e, e && (e.next = t), this.tail = t, this.head || (this.head = t), this.length++;
  }
  push(...t) {
    for (let e = 0, i = t.length;e < i; e++)
      Pn(this, t[e]);
    return this.length;
  }
  unshift(...t) {
    for (var e = 0, i = t.length;e < i; e++)
      zn(this, t[e]);
    return this.length;
  }
  pop() {
    if (!this.tail)
      return;
    let t = this.tail.value, e = this.tail;
    return this.tail = this.tail.prev, this.tail ? this.tail.next = undefined : this.head = undefined, e.list = undefined, this.length--, t;
  }
  shift() {
    if (!this.head)
      return;
    let t = this.head.value, e = this.head;
    return this.head = this.head.next, this.head ? this.head.prev = undefined : this.tail = undefined, e.list = undefined, this.length--, t;
  }
  forEach(t, e) {
    e = e || this;
    for (let i = this.head, r = 0;i; r++)
      t.call(e, i.value, r, this), i = i.next;
  }
  forEachReverse(t, e) {
    e = e || this;
    for (let i = this.tail, r = this.length - 1;i; r--)
      t.call(e, i.value, r, this), i = i.prev;
  }
  get(t) {
    let e = 0, i = this.head;
    for (;i && e < t; e++)
      i = i.next;
    if (e === t && i)
      return i.value;
  }
  getReverse(t) {
    let e = 0, i = this.tail;
    for (;i && e < t; e++)
      i = i.prev;
    if (e === t && i)
      return i.value;
  }
  map(t, e) {
    e = e || this;
    let i = new s2;
    for (let r = this.head;r; )
      i.push(t.call(e, r.value, this)), r = r.next;
    return i;
  }
  mapReverse(t, e) {
    e = e || this;
    var i = new s2;
    for (let r = this.tail;r; )
      i.push(t.call(e, r.value, this)), r = r.prev;
    return i;
  }
  reduce(t, e) {
    let i, r = this.head;
    if (arguments.length > 1)
      i = e;
    else if (this.head)
      r = this.head.next, i = this.head.value;
    else
      throw new TypeError("Reduce of empty list with no initial value");
    for (var n = 0;r; n++)
      i = t(i, r.value, n), r = r.next;
    return i;
  }
  reduceReverse(t, e) {
    let i, r = this.tail;
    if (arguments.length > 1)
      i = e;
    else if (this.tail)
      r = this.tail.prev, i = this.tail.value;
    else
      throw new TypeError("Reduce of empty list with no initial value");
    for (let n = this.length - 1;r; n--)
      i = t(i, r.value, n), r = r.prev;
    return i;
  }
  toArray() {
    let t = new Array(this.length);
    for (let e = 0, i = this.head;i; e++)
      t[e] = i.value, i = i.next;
    return t;
  }
  toArrayReverse() {
    let t = new Array(this.length);
    for (let e = 0, i = this.tail;i; e++)
      t[e] = i.value, i = i.prev;
    return t;
  }
  slice(t = 0, e = this.length) {
    e < 0 && (e += this.length), t < 0 && (t += this.length);
    let i = new s2;
    if (e < t || e < 0)
      return i;
    t < 0 && (t = 0), e > this.length && (e = this.length);
    let r = this.head, n = 0;
    for (n = 0;r && n < t; n++)
      r = r.next;
    for (;r && n < e; n++, r = r.next)
      i.push(r.value);
    return i;
  }
  sliceReverse(t = 0, e = this.length) {
    e < 0 && (e += this.length), t < 0 && (t += this.length);
    let i = new s2;
    if (e < t || e < 0)
      return i;
    t < 0 && (t = 0), e > this.length && (e = this.length);
    let r = this.length, n = this.tail;
    for (;n && r > e; r--)
      n = n.prev;
    for (;n && r > t; r--, n = n.prev)
      i.push(n.value);
    return i;
  }
  splice(t, e = 0, ...i) {
    t > this.length && (t = this.length - 1), t < 0 && (t = this.length + t);
    let r = this.head;
    for (let o = 0;r && o < t; o++)
      r = r.next;
    let n = [];
    for (let o = 0;r && o < e; o++)
      n.push(r.value), r = this.removeNode(r);
    r ? r !== this.tail && (r = r.prev) : r = this.tail;
    for (let o of i)
      r = Bn(this, r, o);
    return n;
  }
  reverse() {
    let t = this.head, e = this.tail;
    for (let i = t;i; i = i.prev) {
      let r = i.prev;
      i.prev = i.next, i.next = r;
    }
    return this.head = e, this.tail = t, this;
  }
};
function Bn(s3, t, e) {
  let i = t, r = t ? t.next : s3.head, n = new ue(e, i, r, s3);
  return n.next === undefined && (s3.tail = n), n.prev === undefined && (s3.head = n), s3.length++, n;
}
function Pn(s3, t) {
  s3.tail = new ue(t, s3.tail, undefined, s3), s3.head || (s3.head = s3.tail), s3.length++;
}
function zn(s3, t) {
  s3.head = new ue(t, undefined, s3.head, s3), s3.tail || (s3.tail = s3.head), s3.length++;
}
var ue = class {
  list;
  next;
  prev;
  value;
  constructor(t, e, i, r) {
    this.list = r, this.value = t, e ? (e.next = this, this.prev = e) : this.prev = undefined, i ? (i.prev = this, this.next = i) : this.next = undefined;
  }
};
var di = class {
  path;
  absolute;
  entry;
  stat;
  readdir;
  pending = false;
  ignore = false;
  piped = false;
  constructor(t, e) {
    this.path = t || "./", this.absolute = e;
  }
};
var tr = Buffer.alloc(1024);
var oi = Symbol("onStat");
var me = Symbol("ended");
var W = Symbol("queue");
var Ct = Symbol("current");
var Ft = Symbol("process");
var pe = Symbol("processing");
var rs = Symbol("processJob");
var G = Symbol("jobs");
var ns = Symbol("jobDone");
var hi = Symbol("addFSEntry");
var er = Symbol("addTarEntry");
var as = Symbol("stat");
var ls = Symbol("readdir");
var ai = Symbol("onreaddir");
var li = Symbol("pipe");
var ir = Symbol("entry");
var os = Symbol("entryOpt");
var ci = Symbol("writeEntryClass");
var rr = Symbol("write");
var hs = Symbol("ondrain");
var Et = class extends D {
  sync = false;
  opt;
  cwd;
  maxReadSize;
  preservePaths;
  strict;
  noPax;
  prefix;
  linkCache;
  statCache;
  file;
  portable;
  zip;
  readdirCache;
  noDirRecurse;
  follow;
  noMtime;
  mtime;
  filter;
  jobs;
  [ci];
  onWriteEntry;
  [W];
  [G] = 0;
  [pe] = false;
  [me] = false;
  constructor(t = {}) {
    if (super(), this.opt = t, this.file = t.file || "", this.cwd = t.cwd || process.cwd(), this.maxReadSize = t.maxReadSize, this.preservePaths = !!t.preservePaths, this.strict = !!t.strict, this.noPax = !!t.noPax, this.prefix = f(t.prefix || ""), this.linkCache = t.linkCache || new Map, this.statCache = t.statCache || new Map, this.readdirCache = t.readdirCache || new Map, this.onWriteEntry = t.onWriteEntry, this[ci] = de, typeof t.onwarn == "function" && this.on("warn", t.onwarn), this.portable = !!t.portable, t.gzip || t.brotli || t.zstd) {
      if ((t.gzip ? 1 : 0) + (t.brotli ? 1 : 0) + (t.zstd ? 1 : 0) > 1)
        throw new TypeError("gzip, brotli, zstd are mutually exclusive");
      if (t.gzip && (typeof t.gzip != "object" && (t.gzip = {}), this.portable && (t.gzip.portable = true), this.zip = new Pe(t.gzip)), t.brotli && (typeof t.brotli != "object" && (t.brotli = {}), this.zip = new He(t.brotli)), t.zstd && (typeof t.zstd != "object" && (t.zstd = {}), this.zip = new Ze(t.zstd)), !this.zip)
        throw new Error("impossible");
      let e = this.zip;
      e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[hs]()), this.on("resume", () => e.resume());
    } else
      this.on("drain", this[hs]);
    this.noDirRecurse = !!t.noDirRecurse, this.follow = !!t.follow, this.noMtime = !!t.noMtime, t.mtime && (this.mtime = t.mtime), this.filter = typeof t.filter == "function" ? t.filter : () => true, this[W] = new ni, this[G] = 0, this.jobs = Number(t.jobs) || 4, this[pe] = false, this[me] = false;
  }
  [rr](t) {
    return super.write(t);
  }
  add(t) {
    return this.write(t), this;
  }
  end(t, e, i) {
    return typeof t == "function" && (i = t, t = undefined), typeof e == "function" && (i = e, e = undefined), t && this.add(t), this[me] = true, this[Ft](), i && i(), this;
  }
  write(t) {
    if (this[me])
      throw new Error("write after end");
    return t instanceof Yt ? this[er](t) : this[hi](t), this.flowing;
  }
  [er](t) {
    let e = f(sr.resolve(this.cwd, t.path));
    if (!this.filter(t.path, t))
      t.resume();
    else {
      let i = new di(t.path, e);
      i.entry = new ri(t, this[os](i)), i.entry.on("end", () => this[ns](i)), this[G] += 1, this[W].push(i);
    }
    this[Ft]();
  }
  [hi](t) {
    let e = f(sr.resolve(this.cwd, t));
    this[W].push(new di(t, e)), this[Ft]();
  }
  [as](t) {
    t.pending = true, this[G] += 1;
    let e = this.follow ? "stat" : "lstat";
    fi[e](t.absolute, (i, r) => {
      t.pending = false, this[G] -= 1, i ? this.emit("error", i) : this[oi](t, r);
    });
  }
  [oi](t, e) {
    this.statCache.set(t.absolute, e), t.stat = e, this.filter(t.path, e) ? e.isFile() && e.nlink > 1 && t === this[Ct] && !this.linkCache.get(`${e.dev}:${e.ino}`) && !this.sync && this[rs](t) : t.ignore = true, this[Ft]();
  }
  [ls](t) {
    t.pending = true, this[G] += 1, fi.readdir(t.absolute, (e, i) => {
      if (t.pending = false, this[G] -= 1, e)
        return this.emit("error", e);
      this[ai](t, i);
    });
  }
  [ai](t, e) {
    this.readdirCache.set(t.absolute, e), t.readdir = e, this[Ft]();
  }
  [Ft]() {
    if (!this[pe]) {
      this[pe] = true;
      for (let t = this[W].head;t && this[G] < this.jobs; t = t.next)
        if (this[rs](t.value), t.value.ignore) {
          let e = t.next;
          this[W].removeNode(t), t.next = e;
        }
      this[pe] = false, this[me] && this[W].length === 0 && this[G] === 0 && (this.zip ? this.zip.end(tr) : (super.write(tr), super.end()));
    }
  }
  get [Ct]() {
    return this[W] && this[W].head && this[W].head.value;
  }
  [ns](t) {
    this[W].shift(), this[G] -= 1, this[Ft]();
  }
  [rs](t) {
    if (!t.pending) {
      if (t.entry) {
        t === this[Ct] && !t.piped && this[li](t);
        return;
      }
      if (!t.stat) {
        let e = this.statCache.get(t.absolute);
        e ? this[oi](t, e) : this[as](t);
      }
      if (t.stat && !t.ignore) {
        if (!this.noDirRecurse && t.stat.isDirectory() && !t.readdir) {
          let e = this.readdirCache.get(t.absolute);
          if (e ? this[ai](t, e) : this[ls](t), !t.readdir)
            return;
        }
        if (t.entry = this[ir](t), !t.entry) {
          t.ignore = true;
          return;
        }
        t === this[Ct] && !t.piped && this[li](t);
      }
    }
  }
  [os](t) {
    return { onwarn: (e, i, r) => this.warn(e, i, r), noPax: this.noPax, cwd: this.cwd, absolute: t.absolute, preservePaths: this.preservePaths, maxReadSize: this.maxReadSize, strict: this.strict, portable: this.portable, linkCache: this.linkCache, statCache: this.statCache, noMtime: this.noMtime, mtime: this.mtime, prefix: this.prefix, onWriteEntry: this.onWriteEntry };
  }
  [ir](t) {
    this[G] += 1;
    try {
      return new this[ci](t.path, this[os](t)).on("end", () => this[ns](t)).on("error", (i) => this.emit("error", i));
    } catch (e) {
      this.emit("error", e);
    }
  }
  [hs]() {
    this[Ct] && this[Ct].entry && this[Ct].entry.resume();
  }
  [li](t) {
    t.piped = true, t.readdir && t.readdir.forEach((r) => {
      let n = t.path, o = n === "./" ? "" : n.replace(/\/*$/, "/");
      this[hi](o + r);
    });
    let e = t.entry, i = this.zip;
    if (!e)
      throw new Error("cannot pipe without source");
    i ? e.on("data", (r) => {
      i.write(r) || e.pause();
    }) : e.on("data", (r) => {
      super.write(r) || e.pause();
    });
  }
  pause() {
    return this.zip && this.zip.pause(), super.pause();
  }
  warn(t, e, i = {}) {
    Lt(this, t, e, i);
  }
};
var kt = class extends Et {
  sync = true;
  constructor(t) {
    super(t), this[ci] = si;
  }
  pause() {}
  resume() {}
  [as](t) {
    let e = this.follow ? "statSync" : "lstatSync";
    this[oi](t, fi[e](t.absolute));
  }
  [ls](t) {
    this[ai](t, fi.readdirSync(t.absolute));
  }
  [li](t) {
    let e = t.entry, i = this.zip;
    if (t.readdir && t.readdir.forEach((r) => {
      let n = t.path, o = n === "./" ? "" : n.replace(/\/*$/, "/");
      this[hi](o + r);
    }), !e)
      throw new Error("Cannot pipe without source");
    i ? e.on("data", (r) => {
      i.write(r);
    }) : e.on("data", (r) => {
      super[rr](r);
    });
  }
};
var Un = (s3, t) => {
  let e = new kt(s3), i = new Wt(s3.file, { mode: s3.mode || 438 });
  e.pipe(i), or(e, t);
};
var Hn = (s3, t) => {
  let e = new Et(s3), i = new tt(s3.file, { mode: s3.mode || 438 });
  e.pipe(i);
  let r = new Promise((n, o) => {
    i.on("error", o), i.on("close", n), e.on("error", o);
  });
  return hr(e, t).catch((n) => e.emit("error", n)), r;
};
var or = (s3, t) => {
  t.forEach((e) => {
    e.charAt(0) === "@" ? It({ file: nr.resolve(s3.cwd, e.slice(1)), sync: true, noResume: true, onReadEntry: (i) => s3.add(i) }) : s3.add(e);
  }), s3.end();
};
var hr = async (s3, t) => {
  for (let e of t)
    e.charAt(0) === "@" ? await It({ file: nr.resolve(String(s3.cwd), e.slice(1)), noResume: true, onReadEntry: (i) => {
      s3.add(i);
    } }) : s3.add(e);
  s3.end();
};
var Wn = (s3, t) => {
  let e = new kt(s3);
  return or(e, t), e;
};
var Gn = (s3, t) => {
  let e = new Et(s3);
  return hr(e, t).catch((i) => e.emit("error", i)), e;
};
var Zn = K(Un, Hn, Wn, Gn, (s3, t) => {
  if (!t?.length)
    throw new TypeError("no paths specified to add to archive");
});
var Yn = process.env.__FAKE_PLATFORM__ || process.platform;
var fr = Yn === "win32";
var { O_CREAT: dr, O_NOFOLLOW: ar, O_TRUNC: ur, O_WRONLY: mr } = cr.constants;
var pr = Number(process.env.__FAKE_FS_O_FILENAME__) || cr.constants.UV_FS_O_FILEMAP || 0;
var Kn = fr && !!pr;
var Vn = 512 * 1024;
var $n = pr | ur | dr | mr;
var lr = !fr && typeof ar == "number" ? ar | ur | dr | mr : null;
var cs = lr !== null ? () => lr : Kn ? (s3) => s3 < Vn ? $n : "w" : () => "w";
var fs = (s3, t, e) => {
  try {
    return mi.lchownSync(s3, t, e);
  } catch (i) {
    if (i?.code !== "ENOENT")
      throw i;
  }
};
var ui = (s3, t, e, i) => {
  mi.lchown(s3, t, e, (r) => {
    i(r && r?.code !== "ENOENT" ? r : null);
  });
};
var Xn = (s3, t, e, i, r) => {
  if (t.isDirectory())
    ds(Ee.resolve(s3, t.name), e, i, (n) => {
      if (n)
        return r(n);
      let o = Ee.resolve(s3, t.name);
      ui(o, e, i, r);
    });
  else {
    let n = Ee.resolve(s3, t.name);
    ui(n, e, i, r);
  }
};
var ds = (s3, t, e, i) => {
  mi.readdir(s3, { withFileTypes: true }, (r, n) => {
    if (r) {
      if (r.code === "ENOENT")
        return i();
      if (r.code !== "ENOTDIR" && r.code !== "ENOTSUP")
        return i(r);
    }
    if (r || !n.length)
      return ui(s3, t, e, i);
    let o = n.length, h = null, a = (l) => {
      if (!h) {
        if (l)
          return i(h = l);
        if (--o === 0)
          return ui(s3, t, e, i);
      }
    };
    for (let l of n)
      Xn(s3, l, t, e, a);
  });
};
var qn = (s3, t, e, i) => {
  t.isDirectory() && us(Ee.resolve(s3, t.name), e, i), fs(Ee.resolve(s3, t.name), e, i);
};
var us = (s3, t, e) => {
  let i;
  try {
    i = mi.readdirSync(s3, { withFileTypes: true });
  } catch (r) {
    let n = r;
    if (n?.code === "ENOENT")
      return;
    if (n?.code === "ENOTDIR" || n?.code === "ENOTSUP")
      return fs(s3, t, e);
    throw n;
  }
  for (let r of i)
    qn(s3, r, t, e);
  return fs(s3, t, e);
};
var we = class extends Error {
  path;
  code;
  syscall = "chdir";
  constructor(t, e) {
    super(`${e}: Cannot cd into '${t}'`), this.path = t, this.code = e;
  }
  get name() {
    return "CwdError";
  }
};
var wt = class extends Error {
  path;
  symlink;
  syscall = "symlink";
  code = "TAR_SYMLINK_ERROR";
  constructor(t, e) {
    super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"), this.symlink = t, this.path = e;
  }
  get name() {
    return "SymlinkError";
  }
};
var Qn = (s3, t) => {
  k.stat(s3, (e, i) => {
    (e || !i.isDirectory()) && (e = new we(s3, e?.code || "ENOTDIR")), t(e);
  });
};
var Er = (s3, t, e) => {
  s3 = f(s3);
  let i = t.umask ?? 18, r = t.mode | 448, n = (r & i) !== 0, o = t.uid, h = t.gid, a = typeof o == "number" && typeof h == "number" && (o !== t.processUid || h !== t.processGid), l = t.preserve, c = t.unlink, d = f(t.cwd), S = (E, x) => {
    E ? e(E) : x && a ? ds(x, o, h, (xe) => S(xe)) : n ? k.chmod(s3, r, e) : e();
  };
  if (s3 === d)
    return Qn(s3, S);
  if (l)
    return jn.mkdir(s3, { mode: r, recursive: true }).then((E) => S(null, E ?? undefined), S);
  let N = f(pi.relative(d, s3)).split("/");
  ms(d, N, r, c, d, undefined, S);
};
var ms = (s3, t, e, i, r, n, o) => {
  if (t.length === 0)
    return o(null, n);
  let h = t.shift(), a = f(pi.resolve(s3 + "/" + h));
  k.mkdir(a, e, wr(a, t, e, i, r, n, o));
};
var wr = (s3, t, e, i, r, n, o) => (h) => {
  h ? k.lstat(s3, (a, l) => {
    if (a)
      a.path = a.path && f(a.path), o(a);
    else if (l.isDirectory())
      ms(s3, t, e, i, r, n, o);
    else if (i)
      k.unlink(s3, (c) => {
        if (c)
          return o(c);
        k.mkdir(s3, e, wr(s3, t, e, i, r, n, o));
      });
    else {
      if (l.isSymbolicLink())
        return o(new wt(s3, s3 + "/" + t.join("/")));
      o(h);
    }
  }) : (n = n || s3, ms(s3, t, e, i, r, n, o));
};
var Jn = (s3) => {
  let t = false, e;
  try {
    t = k.statSync(s3).isDirectory();
  } catch (i) {
    e = i?.code;
  } finally {
    if (!t)
      throw new we(s3, e ?? "ENOTDIR");
  }
};
var Sr = (s3, t) => {
  s3 = f(s3);
  let e = t.umask ?? 18, i = t.mode | 448, r = (i & e) !== 0, n = t.uid, o = t.gid, h = typeof n == "number" && typeof o == "number" && (n !== t.processUid || o !== t.processGid), a = t.preserve, l = t.unlink, c = f(t.cwd), d = (E) => {
    E && h && us(E, n, o), r && k.chmodSync(s3, i);
  };
  if (s3 === c)
    return Jn(c), d();
  if (a)
    return d(k.mkdirSync(s3, { mode: i, recursive: true }) ?? undefined);
  let T = f(pi.relative(c, s3)).split("/"), N;
  for (let E = T.shift(), x = c;E && (x += "/" + E); E = T.shift()) {
    x = f(pi.resolve(x));
    try {
      k.mkdirSync(x, i), N = N || x;
    } catch {
      let xe = k.lstatSync(x);
      if (xe.isDirectory())
        continue;
      if (l) {
        k.unlinkSync(x), k.mkdirSync(x, i), N = N || x;
        continue;
      } else if (xe.isSymbolicLink())
        return new wt(x, x + "/" + T.join("/"));
    }
  }
  return d(N);
};
var ps = Object.create(null);
var yr = 1e4;
var $t = new Set;
var Rr = (s3) => {
  $t.has(s3) ? $t.delete(s3) : ps[s3] = s3.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"), $t.add(s3);
  let t = ps[s3], e = $t.size - yr;
  if (e > yr / 10) {
    for (let i of $t)
      if ($t.delete(i), delete ps[i], --e <= 0)
        break;
  }
  return t;
};
var to = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
var eo = to === "win32";
var io = (s3) => s3.split("/").slice(0, -1).reduce((e, i) => {
  let r = e.at(-1);
  return r !== undefined && (i = br(r, i)), e.push(i || "/"), e;
}, []);
var Ei = class {
  #t = new Map;
  #i = new Map;
  #s = new Set;
  reserve(t, e) {
    t = eo ? ["win32 parallelization disabled"] : t.map((r) => mt(br(Rr(r))));
    let i = new Set(t.map((r) => io(r)).reduce((r, n) => r.concat(n)));
    this.#i.set(e, { dirs: i, paths: t });
    for (let r of t) {
      let n = this.#t.get(r);
      n ? n.push(e) : this.#t.set(r, [e]);
    }
    for (let r of i) {
      let n = this.#t.get(r);
      if (!n)
        this.#t.set(r, [new Set([e])]);
      else {
        let o = n.at(-1);
        o instanceof Set ? o.add(e) : n.push(new Set([e]));
      }
    }
    return this.#r(e);
  }
  #n(t) {
    let e = this.#i.get(t);
    if (!e)
      throw new Error("function does not have any path reservations");
    return { paths: e.paths.map((i) => this.#t.get(i)), dirs: [...e.dirs].map((i) => this.#t.get(i)) };
  }
  check(t) {
    let { paths: e, dirs: i } = this.#n(t);
    return e.every((r) => r && r[0] === t) && i.every((r) => r && r[0] instanceof Set && r[0].has(t));
  }
  #r(t) {
    return this.#s.has(t) || !this.check(t) ? false : (this.#s.add(t), t(() => this.#e(t)), true);
  }
  #e(t) {
    if (!this.#s.has(t))
      return false;
    let e = this.#i.get(t);
    if (!e)
      throw new Error("invalid reservation");
    let { paths: i, dirs: r } = e, n = new Set;
    for (let o of i) {
      let h = this.#t.get(o);
      if (!h || h?.[0] !== t)
        continue;
      let a = h[1];
      if (!a) {
        this.#t.delete(o);
        continue;
      }
      if (h.shift(), typeof a == "function")
        n.add(a);
      else
        for (let l of a)
          n.add(l);
    }
    for (let o of r) {
      let h = this.#t.get(o), a = h?.[0];
      if (!(!h || !(a instanceof Set)))
        if (a.size === 1 && h.length === 1) {
          this.#t.delete(o);
          continue;
        } else if (a.size === 1) {
          h.shift();
          let l = h[0];
          typeof l == "function" && n.add(l);
        } else
          a.delete(t);
    }
    return this.#s.delete(t), n.forEach((o) => this.#r(o)), true;
  }
};
var _r = () => process.umask();
var gr = Symbol("onEntry");
var ys = Symbol("checkFs");
var Or = Symbol("checkFs2");
var Rs = Symbol("isReusable");
var P = Symbol("makeFs");
var bs = Symbol("file");
var _s = Symbol("directory");
var Si = Symbol("link");
var Tr = Symbol("symlink");
var xr = Symbol("hardlink");
var ye = Symbol("ensureNoSymlink");
var Lr = Symbol("unsupported");
var Nr = Symbol("checkPath");
var Es = Symbol("stripAbsolutePath");
var St = Symbol("mkdir");
var O = Symbol("onError");
var wi = Symbol("pending");
var Ar = Symbol("pend");
var Xt = Symbol("unpend");
var ws = Symbol("ended");
var Ss = Symbol("maybeClose");
var gs = Symbol("skip");
var Re = Symbol("doChown");
var be = Symbol("uid");
var _e = Symbol("gid");
var ge = Symbol("checkedCwd");
var ro = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
var Oe = ro === "win32";
var no = 1024;
var oo = (s3, t) => {
  if (!Oe)
    return u.unlink(s3, t);
  let e = s3 + ".DELETE." + Ir(16).toString("hex");
  u.rename(s3, e, (i) => {
    if (i)
      return t(i);
    u.unlink(e, t);
  });
};
var ho = (s3) => {
  if (!Oe)
    return u.unlinkSync(s3);
  let t = s3 + ".DELETE." + Ir(16).toString("hex");
  u.renameSync(s3, t), u.unlinkSync(t);
};
var Dr = (s3, t, e) => s3 !== undefined && s3 === s3 >>> 0 ? s3 : t !== undefined && t === t >>> 0 ? t : e;
var qt = class extends st {
  [ws] = false;
  [ge] = false;
  [wi] = 0;
  reservations = new Ei;
  transform;
  writable = true;
  readable = false;
  uid;
  gid;
  setOwner;
  preserveOwner;
  processGid;
  processUid;
  maxDepth;
  forceChown;
  win32;
  newer;
  keep;
  noMtime;
  preservePaths;
  unlink;
  cwd;
  strip;
  processUmask;
  umask;
  dmode;
  fmode;
  chmod;
  constructor(t = {}) {
    if (t.ondone = () => {
      this[ws] = true, this[Ss]();
    }, super(t), this.transform = t.transform, this.chmod = !!t.chmod, typeof t.uid == "number" || typeof t.gid == "number") {
      if (typeof t.uid != "number" || typeof t.gid != "number")
        throw new TypeError("cannot set owner without number uid and gid");
      if (t.preserveOwner)
        throw new TypeError("cannot preserve owner in archive and also set owner explicitly");
      this.uid = t.uid, this.gid = t.gid, this.setOwner = true;
    } else
      this.uid = undefined, this.gid = undefined, this.setOwner = false;
    this.preserveOwner = t.preserveOwner === undefined && typeof t.uid != "number" ? !!(process.getuid && process.getuid() === 0) : !!t.preserveOwner, this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : undefined, this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : undefined, this.maxDepth = typeof t.maxDepth == "number" ? t.maxDepth : no, this.forceChown = t.forceChown === true, this.win32 = !!t.win32 || Oe, this.newer = !!t.newer, this.keep = !!t.keep, this.noMtime = !!t.noMtime, this.preservePaths = !!t.preservePaths, this.unlink = !!t.unlink, this.cwd = f(R.resolve(t.cwd || process.cwd())), this.strip = Number(t.strip) || 0, this.processUmask = this.chmod ? typeof t.processUmask == "number" ? t.processUmask : _r() : 0, this.umask = typeof t.umask == "number" ? t.umask : this.processUmask, this.dmode = t.dmode || 511 & ~this.umask, this.fmode = t.fmode || 438 & ~this.umask, this.on("entry", (e) => this[gr](e));
  }
  warn(t, e, i = {}) {
    return (t === "TAR_BAD_ARCHIVE" || t === "TAR_ABORT") && (i.recoverable = false), super.warn(t, e, i);
  }
  [Ss]() {
    this[ws] && this[wi] === 0 && (this.emit("prefinish"), this.emit("finish"), this.emit("end"));
  }
  [Es](t, e) {
    let i = t[e], { type: r } = t;
    if (!i || this.preservePaths)
      return true;
    let [n, o] = ce(i), h = o.replaceAll(/\\/g, "/").split("/");
    if (h.includes("..") || Oe && /^[a-z]:\.\.$/i.test(h[0] ?? "")) {
      if (e === "path" || r === "Link")
        return this.warn("TAR_ENTRY_ERROR", `${e} contains '..'`, { entry: t, [e]: i }), false;
      let a = R.posix.dirname(t.path), l = R.posix.normalize(R.posix.join(a, h.join("/")));
      if (l.startsWith("../") || l === "..")
        return this.warn("TAR_ENTRY_ERROR", `${e} escapes extraction directory`, { entry: t, [e]: i }), false;
    }
    return n && (t[e] = String(o), this.warn("TAR_ENTRY_INFO", `stripping ${n} from absolute ${e}`, { entry: t, [e]: i })), true;
  }
  [Nr](t) {
    let e = f(t.path), i = e.split("/");
    if (this.strip) {
      if (i.length < this.strip)
        return false;
      if (t.type === "Link") {
        let r = f(String(t.linkpath)).split("/");
        if (r.length >= this.strip)
          t.linkpath = r.slice(this.strip).join("/");
        else
          return false;
      }
      i.splice(0, this.strip), t.path = i.join("/");
    }
    if (isFinite(this.maxDepth) && i.length > this.maxDepth)
      return this.warn("TAR_ENTRY_ERROR", "path excessively deep", { entry: t, path: e, depth: i.length, maxDepth: this.maxDepth }), false;
    if (!this[Es](t, "path") || !this[Es](t, "linkpath"))
      return false;
    if (t.absolute = R.isAbsolute(t.path) ? f(R.resolve(t.path)) : f(R.resolve(this.cwd, t.path)), !this.preservePaths && typeof t.absolute == "string" && t.absolute.indexOf(this.cwd + "/") !== 0 && t.absolute !== this.cwd)
      return this.warn("TAR_ENTRY_ERROR", "path escaped extraction target", { entry: t, path: f(t.path), resolvedPath: t.absolute, cwd: this.cwd }), false;
    if (t.absolute === this.cwd && t.type !== "Directory" && t.type !== "GNUDumpDir")
      return false;
    if (this.win32) {
      let { root: r } = R.win32.parse(String(t.absolute));
      t.absolute = r + Xi(String(t.absolute).slice(r.length));
      let { root: n } = R.win32.parse(t.path);
      t.path = n + Xi(t.path.slice(n.length));
    }
    return true;
  }
  [gr](t) {
    if (!this[Nr](t))
      return t.resume();
    switch (so.equal(typeof t.absolute, "string"), t.type) {
      case "Directory":
      case "GNUDumpDir":
        t.mode && (t.mode = t.mode | 448);
      case "File":
      case "OldFile":
      case "ContiguousFile":
      case "Link":
      case "SymbolicLink":
        return this[ys](t);
      default:
        return this[Lr](t);
    }
  }
  [O](t, e) {
    t.name === "CwdError" ? this.emit("error", t) : (this.warn("TAR_ENTRY_ERROR", t, { entry: e }), this[Xt](), e.resume());
  }
  [St](t, e, i) {
    Er(f(t), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cwd: this.cwd, mode: e }, i);
  }
  [Re](t) {
    return this.forceChown || this.preserveOwner && (typeof t.uid == "number" && t.uid !== this.processUid || typeof t.gid == "number" && t.gid !== this.processGid) || typeof this.uid == "number" && this.uid !== this.processUid || typeof this.gid == "number" && this.gid !== this.processGid;
  }
  [be](t) {
    return Dr(this.uid, t.uid, this.processUid);
  }
  [_e](t) {
    return Dr(this.gid, t.gid, this.processGid);
  }
  [bs](t, e) {
    let i = typeof t.mode == "number" ? t.mode & 4095 : this.fmode, r = new tt(String(t.absolute), { flags: cs(t.size), mode: i, autoClose: false });
    r.on("error", (a) => {
      r.fd && u.close(r.fd, () => {}), r.write = () => true, this[O](a, t), e();
    });
    let n = 1, o = (a) => {
      if (a) {
        r.fd && u.close(r.fd, () => {}), this[O](a, t), e();
        return;
      }
      --n === 0 && r.fd !== undefined && u.close(r.fd, (l) => {
        l ? this[O](l, t) : this[Xt](), e();
      });
    };
    r.on("finish", () => {
      let a = String(t.absolute), l = r.fd;
      if (typeof l == "number" && t.mtime && !this.noMtime) {
        n++;
        let c = t.atime || new Date, d = t.mtime;
        u.futimes(l, c, d, (S) => S ? u.utimes(a, c, d, (T) => o(T && S)) : o());
      }
      if (typeof l == "number" && this[Re](t)) {
        n++;
        let c = this[be](t), d = this[_e](t);
        typeof c == "number" && typeof d == "number" && u.fchown(l, c, d, (S) => S ? u.chown(a, c, d, (T) => o(T && S)) : o());
      }
      o();
    });
    let h = this.transform && this.transform(t) || t;
    h !== t && (h.on("error", (a) => {
      this[O](a, t), e();
    }), t.pipe(h)), h.pipe(r);
  }
  [_s](t, e) {
    let i = typeof t.mode == "number" ? t.mode & 4095 : this.dmode;
    this[St](String(t.absolute), i, (r) => {
      if (r) {
        this[O](r, t), e();
        return;
      }
      let n = 1, o = () => {
        --n === 0 && (e(), this[Xt](), t.resume());
      };
      t.mtime && !this.noMtime && (n++, u.utimes(String(t.absolute), t.atime || new Date, t.mtime, o)), this[Re](t) && (n++, u.chown(String(t.absolute), Number(this[be](t)), Number(this[_e](t)), o)), o();
    });
  }
  [Lr](t) {
    t.unsupported = true, this.warn("TAR_ENTRY_UNSUPPORTED", `unsupported entry type: ${t.type}`, { entry: t }), t.resume();
  }
  [Tr](t, e) {
    let i = f(R.relative(this.cwd, R.resolve(R.dirname(String(t.absolute)), String(t.linkpath)))).split("/");
    this[ye](t, this.cwd, i, () => this[Si](t, String(t.linkpath), "symlink", e), (r) => {
      this[O](r, t), e();
    });
  }
  [xr](t, e) {
    let i = f(R.resolve(this.cwd, String(t.linkpath))), r = f(String(t.linkpath)).split("/");
    this[ye](t, this.cwd, r, () => this[Si](t, i, "link", e), (n) => {
      this[O](n, t), e();
    });
  }
  [ye](t, e, i, r, n) {
    let o = i.shift();
    if (this.preservePaths || o === undefined)
      return r();
    let h = R.resolve(e, o);
    u.lstat(h, (a, l) => {
      if (a)
        return r();
      if (l?.isSymbolicLink())
        return n(new wt(h, R.resolve(h, i.join("/"))));
      this[ye](t, h, i, r, n);
    });
  }
  [Ar]() {
    this[wi]++;
  }
  [Xt]() {
    this[wi]--, this[Ss]();
  }
  [gs](t) {
    this[Xt](), t.resume();
  }
  [Rs](t, e) {
    return t.type === "File" && !this.unlink && e.isFile() && e.nlink <= 1 && !Oe;
  }
  [ys](t) {
    this[Ar]();
    let e = [t.path];
    t.linkpath && e.push(t.linkpath), this.reservations.reserve(e, (i) => this[Or](t, i));
  }
  [Or](t, e) {
    let i = (h) => {
      e(h);
    }, r = () => {
      this[St](this.cwd, this.dmode, (h) => {
        if (h) {
          this[O](h, t), i();
          return;
        }
        this[ge] = true, n();
      });
    }, n = () => {
      if (t.absolute !== this.cwd) {
        let h = f(R.dirname(String(t.absolute)));
        if (h !== this.cwd)
          return this[St](h, this.dmode, (a) => {
            if (a) {
              this[O](a, t), i();
              return;
            }
            o();
          });
      }
      o();
    }, o = () => {
      u.lstat(String(t.absolute), (h, a) => {
        if (a && (this.keep || this.newer && a.mtime > (t.mtime ?? a.mtime))) {
          this[gs](t), i();
          return;
        }
        if (h || this[Rs](t, a))
          return this[P](null, t, i);
        if (a.isDirectory()) {
          if (t.type === "Directory") {
            let l = this.chmod && t.mode && (a.mode & 4095) !== t.mode, c = (d) => this[P](d ?? null, t, i);
            return l ? u.chmod(String(t.absolute), Number(t.mode), c) : c();
          }
          if (t.absolute !== this.cwd)
            return u.rmdir(String(t.absolute), (l) => this[P](l ?? null, t, i));
        }
        if (t.absolute === this.cwd)
          return this[P](null, t, i);
        oo(String(t.absolute), (l) => this[P](l ?? null, t, i));
      });
    };
    this[ge] ? n() : r();
  }
  [P](t, e, i) {
    if (t) {
      this[O](t, e), i();
      return;
    }
    switch (e.type) {
      case "File":
      case "OldFile":
      case "ContiguousFile":
        return this[bs](e, i);
      case "Link":
        return this[xr](e, i);
      case "SymbolicLink":
        return this[Tr](e, i);
      case "Directory":
      case "GNUDumpDir":
        return this[_s](e, i);
    }
  }
  [Si](t, e, i, r) {
    u[i](e, String(t.absolute), (n) => {
      n ? this[O](n, t) : (this[Xt](), t.resume()), r();
    });
  }
};
var Se = (s3) => {
  try {
    return [null, s3()];
  } catch (t) {
    return [t, null];
  }
};
var Te = class extends qt {
  sync = true;
  [P](t, e) {
    return super[P](t, e, () => {});
  }
  [ys](t) {
    if (!this[ge]) {
      let n = this[St](this.cwd, this.dmode);
      if (n)
        return this[O](n, t);
      this[ge] = true;
    }
    if (t.absolute !== this.cwd) {
      let n = f(R.dirname(String(t.absolute)));
      if (n !== this.cwd) {
        let o = this[St](n, this.dmode);
        if (o)
          return this[O](o, t);
      }
    }
    let [e, i] = Se(() => u.lstatSync(String(t.absolute)));
    if (i && (this.keep || this.newer && i.mtime > (t.mtime ?? i.mtime)))
      return this[gs](t);
    if (e || this[Rs](t, i))
      return this[P](null, t);
    if (i.isDirectory()) {
      if (t.type === "Directory") {
        let o = this.chmod && t.mode && (i.mode & 4095) !== t.mode, [h] = o ? Se(() => {
          u.chmodSync(String(t.absolute), Number(t.mode));
        }) : [];
        return this[P](h, t);
      }
      let [n] = Se(() => u.rmdirSync(String(t.absolute)));
      this[P](n, t);
    }
    let [r] = t.absolute === this.cwd ? [] : Se(() => ho(String(t.absolute)));
    this[P](r, t);
  }
  [bs](t, e) {
    let i = typeof t.mode == "number" ? t.mode & 4095 : this.fmode, r = (h) => {
      let a;
      try {
        u.closeSync(n);
      } catch (l) {
        a = l;
      }
      (h || a) && this[O](h || a, t), e();
    }, n;
    try {
      n = u.openSync(String(t.absolute), cs(t.size), i);
    } catch (h) {
      return r(h);
    }
    let o = this.transform && this.transform(t) || t;
    o !== t && (o.on("error", (h) => this[O](h, t)), t.pipe(o)), o.on("data", (h) => {
      try {
        u.writeSync(n, h, 0, h.length);
      } catch (a) {
        r(a);
      }
    }), o.on("end", () => {
      let h = null;
      if (t.mtime && !this.noMtime) {
        let a = t.atime || new Date, l = t.mtime;
        try {
          u.futimesSync(n, a, l);
        } catch (c) {
          try {
            u.utimesSync(String(t.absolute), a, l);
          } catch {
            h = c;
          }
        }
      }
      if (this[Re](t)) {
        let a = this[be](t), l = this[_e](t);
        try {
          u.fchownSync(n, Number(a), Number(l));
        } catch (c) {
          try {
            u.chownSync(String(t.absolute), Number(a), Number(l));
          } catch {
            h = h || c;
          }
        }
      }
      r(h);
    });
  }
  [_s](t, e) {
    let i = typeof t.mode == "number" ? t.mode & 4095 : this.dmode, r = this[St](String(t.absolute), i);
    if (r) {
      this[O](r, t), e();
      return;
    }
    if (t.mtime && !this.noMtime)
      try {
        u.utimesSync(String(t.absolute), t.atime || new Date, t.mtime);
      } catch {}
    if (this[Re](t))
      try {
        u.chownSync(String(t.absolute), Number(this[be](t)), Number(this[_e](t)));
      } catch {}
    e(), t.resume();
  }
  [St](t, e) {
    try {
      return Sr(f(t), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cwd: this.cwd, mode: e });
    } catch (i) {
      return i;
    }
  }
  [ye](t, e, i, r, n) {
    if (this.preservePaths || i.length === 0)
      return r();
    let o = e;
    for (let h of i) {
      o = R.resolve(o, h);
      let [a, l] = Se(() => u.lstatSync(o));
      if (a)
        return r();
      if (l.isSymbolicLink())
        return n(new wt(o, R.resolve(e, i.join("/"))));
    }
    r();
  }
  [Si](t, e, i, r) {
    let n = `${i}Sync`;
    try {
      u[n](e, String(t.absolute)), r(), t.resume();
    } catch (o) {
      return this[O](o, t);
    }
  }
};
var ao = (s3) => {
  let t = new Te(s3), e = s3.file, i = Cr.statSync(e), r = s3.maxReadSize || 16 * 1024 * 1024;
  new Me(e, { readSize: r, size: i.size }).pipe(t);
};
var lo = (s3, t) => {
  let e = new qt(s3), i = s3.maxReadSize || 16 * 1024 * 1024, r = s3.file;
  return new Promise((o, h) => {
    e.on("error", h), e.on("close", o), Cr.stat(r, (a, l) => {
      if (a)
        h(a);
      else {
        let c = new _t(r, { readSize: i, size: l.size });
        c.on("error", h), c.pipe(e);
      }
    });
  });
};
var co = K(ao, lo, (s3) => new Te(s3), (s3) => new qt(s3), (s3, t) => {
  t?.length && Ki(s3, t);
});
var fo = (s3, t) => {
  let e = new kt(s3), i = true, r, n;
  try {
    try {
      r = v.openSync(s3.file, "r+");
    } catch (a) {
      if (a?.code === "ENOENT")
        r = v.openSync(s3.file, "w+");
      else
        throw a;
    }
    let o = v.fstatSync(r), h = Buffer.alloc(512);
    t:
      for (n = 0;n < o.size; n += 512) {
        for (let c = 0, d = 0;c < 512; c += d) {
          if (d = v.readSync(r, h, c, h.length - c, n + c), n === 0 && h[0] === 31 && h[1] === 139)
            throw new Error("cannot append to compressed archives");
          if (!d)
            break t;
        }
        let a = new F(h);
        if (!a.cksumValid)
          break;
        let l = 512 * Math.ceil((a.size || 0) / 512);
        if (n + l + 512 > o.size)
          break;
        n += l, s3.mtimeCache && a.mtime && s3.mtimeCache.set(String(a.path), a.mtime);
      }
    i = false, uo(s3, e, n, r, t);
  } finally {
    if (i)
      try {
        v.closeSync(r);
      } catch {}
  }
};
var uo = (s3, t, e, i, r) => {
  let n = new Wt(s3.file, { fd: i, start: e });
  t.pipe(n), po(t, r);
};
var mo = (s3, t) => {
  t = Array.from(t);
  let e = new Et(s3), i = (n, o, h) => {
    let a = (T, N) => {
      T ? v.close(n, (E) => h(T)) : h(null, N);
    }, l = 0;
    if (o === 0)
      return a(null, 0);
    let c = 0, d = Buffer.alloc(512), S = (T, N) => {
      if (T || N === undefined)
        return a(T);
      if (c += N, c < 512 && N)
        return v.read(n, d, c, d.length - c, l + c, S);
      if (l === 0 && d[0] === 31 && d[1] === 139)
        return a(new Error("cannot append to compressed archives"));
      if (c < 512)
        return a(null, l);
      let E = new F(d);
      if (!E.cksumValid)
        return a(null, l);
      let x = 512 * Math.ceil((E.size ?? 0) / 512);
      if (l + x + 512 > o || (l += x + 512, l >= o))
        return a(null, l);
      s3.mtimeCache && E.mtime && s3.mtimeCache.set(String(E.path), E.mtime), c = 0, v.read(n, d, 0, 512, l, S);
    };
    v.read(n, d, 0, 512, l, S);
  };
  return new Promise((n, o) => {
    e.on("error", o);
    let h = "r+", a = (l, c) => {
      if (l && l.code === "ENOENT" && h === "r+")
        return h = "w+", v.open(s3.file, h, a);
      if (l || !c)
        return o(l);
      v.fstat(c, (d, S) => {
        if (d)
          return v.close(c, () => o(d));
        i(c, S.size, (T, N) => {
          if (T)
            return o(T);
          let E = new tt(s3.file, { fd: c, start: N });
          e.pipe(E), E.on("error", o), E.on("close", n), Eo(e, t);
        });
      });
    };
    v.open(s3.file, h, a);
  });
};
var po = (s3, t) => {
  t.forEach((e) => {
    e.charAt(0) === "@" ? It({ file: Fr.resolve(s3.cwd, e.slice(1)), sync: true, noResume: true, onReadEntry: (i) => s3.add(i) }) : s3.add(e);
  }), s3.end();
};
var Eo = async (s3, t) => {
  for (let e of t)
    e.charAt(0) === "@" ? await It({ file: Fr.resolve(String(s3.cwd), e.slice(1)), noResume: true, onReadEntry: (i) => s3.add(i) }) : s3.add(e);
  s3.end();
};
var vt = K(fo, mo, () => {
  throw new TypeError("file is required");
}, () => {
  throw new TypeError("file is required");
}, (s3, t) => {
  if (!Fs(s3))
    throw new TypeError("file is required");
  if (s3.gzip || s3.brotli || s3.zstd || s3.file.endsWith(".br") || s3.file.endsWith(".tbr"))
    throw new TypeError("cannot append to compressed archives");
  if (!t?.length)
    throw new TypeError("no paths specified to add/replace");
});
var wo = K(vt.syncFile, vt.asyncFile, vt.syncNoFile, vt.asyncNoFile, (s3, t = []) => {
  vt.validate?.(s3, t), So(s3);
});
var So = (s3) => {
  let t = s3.filter;
  s3.mtimeCache || (s3.mtimeCache = new Map), s3.filter = t ? (e, i) => t(e, i) && !((s3.mtimeCache?.get(e) ?? i.mtime ?? 0) > (i.mtime ?? 0)) : (e, i) => !((s3.mtimeCache?.get(e) ?? i.mtime ?? 0) > (i.mtime ?? 0));
};

// src/commands/upgrade.ts
var import_adm_zip = __toESM(require_adm_zip(), 1);
var GITHUB_REPO = "botpress/adk";
var REGISTRY_URL = "https://registry.npmjs.org/@botpress/adk-cli";
function getPlatformInfo() {
  const platform = process.platform;
  const arch = process.arch;
  let target;
  let extension = "";
  let isWindows = false;
  if (platform === "darwin") {
    target = arch === "arm64" ? "darwin-arm64" : "darwin-x64";
  } else if (platform === "linux") {
    target = "linux-x64";
  } else if (platform === "win32") {
    target = "windows-x64";
    extension = ".exe";
    isWindows = true;
  } else {
    throw new AdkError({
      code: "UNSUPPORTED_PLATFORM",
      message: `Unsupported platform: ${platform}-${arch}`,
      expected: true
    });
  }
  return { target, extension, isWindows };
}
async function getVersion(tagOrVersion) {
  const response = await fetch(REGISTRY_URL, {
    headers: { Accept: "application/json" }
  });
  if (!response.ok) {
    throw new AdkError({
      code: "UPGRADE_VERSION_LOOKUP",
      message: "Failed to fetch version information from npm",
      expected: true,
      details: { status: response.status }
    });
  }
  const data = await response.json();
  const distTags = data["dist-tags"] || {};
  const versions = Object.keys(data.versions || {});
  if (!tagOrVersion) {
    const latest = distTags?.latest;
    if (!latest) {
      throw new AdkError({
        code: "UPGRADE_VERSION_LOOKUP",
        message: "Could not determine latest version",
        expected: true
      });
    }
    return { version: latest, tag: "latest" };
  }
  if (distTags[tagOrVersion]) {
    return { version: distTags[tagOrVersion], tag: tagOrVersion };
  }
  const normalizedVersion = tagOrVersion.replace(/^v/, "");
  if (versions.includes(normalizedVersion)) {
    return { version: normalizedVersion, tag: null };
  }
  const availableTags = Object.keys(distTags).join(", ");
  throw new AdkError({
    code: "UPGRADE_VERSION_LOOKUP",
    message: `Unknown tag or version: ${tagOrVersion}

   Available tags: ${availableTags}
   Or specify a version like: 1.13.0`,
    expected: true
  });
}
async function downloadBinary(version, target, extension, logger) {
  const fileName = `adk-${target}${extension}`;
  const downloadUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${fileName}.tar.gz`;
  logger.info(`Downloading adk v${version} for ${target}...`);
  logger.info(`   ${downloadUrl}`);
  const response = await fetch(downloadUrl);
  if (!response.ok) {
    throw new AdkError({
      code: "UPGRADE_DOWNLOAD_FAILED",
      message: `Failed to download: ${response.status} ${response.statusText}`,
      expected: true,
      details: { status: response.status }
    });
  }
  const buffer = Buffer.from(await response.arrayBuffer());
  const tmpDir = join(tmpdir(), `adk-upgrade-${Date.now()}`);
  mkdirSync(tmpDir, { recursive: true });
  const tarPath = join(tmpDir, "adk.tar.gz");
  writeFileSync(tarPath, buffer);
  co({
    file: tarPath,
    cwd: tmpDir,
    sync: true
  });
  const binaryPath = join(tmpDir, fileName);
  const binaryBuffer = readFileSync(binaryPath);
  try {
    unlinkSync(tarPath);
    unlinkSync(binaryPath);
    rmdirSync(tmpDir);
  } catch {}
  return binaryBuffer;
}
async function downloadBinaryWindows(version, target, extension, logger) {
  const fileName = `adk-${target}${extension}`;
  const archiveName = `adk-${target}.zip`;
  const downloadUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${archiveName}`;
  logger.info(`Downloading adk v${version} for ${target}...`);
  logger.info(`   ${downloadUrl}`);
  const response = await fetch(downloadUrl);
  if (!response.ok) {
    throw new AdkError({
      code: "UPGRADE_DOWNLOAD_FAILED",
      message: `Failed to download: ${response.status} ${response.statusText}`,
      expected: true,
      details: { status: response.status }
    });
  }
  const buffer = Buffer.from(await response.arrayBuffer());
  const zip = new import_adm_zip.default(buffer);
  const zipEntries = zip.getEntries();
  const binaryEntry = zipEntries.find((entry) => entry.entryName === fileName);
  if (!binaryEntry) {
    throw new AdkError({
      code: "UPGRADE_ARCHIVE",
      message: `Binary not found in archive: ${fileName}`
    });
  }
  return binaryEntry.getData();
}
var RUNTIME_BASENAMES = new Set(["bun", "bunx", "node", "nodejs", "npm", "npx", "pnpm", "pnpx", "yarn", "yarnpkg", "corepack"].flatMap((n) => [
  n,
  `${n}.exe`,
  `${n}.cmd`
]));
function isRuntimeOrPackageManagerExecutable(path) {
  return RUNTIME_BASENAMES.has(basename(path).toLowerCase());
}
var PACKAGE_MANAGER_DIR_MARKERS = ["/node_modules/", "/.bun/install/", "/.npm/", "/.pnpm/", "/.yarn/"];
function isInPackageManagerDirectory(path) {
  const normalized = path.replace(/\\/g, "/");
  return PACKAGE_MANAGER_DIR_MARKERS.some((marker) => normalized.includes(marker));
}
function isLaunchedAsScript() {
  const script = process.argv[1];
  return !!script && script !== process.execPath && /\.(c|m)?js$/i.test(script) && existsSync(script);
}
function getCurrentBinaryPath() {
  const execPath = process.execPath;
  if (isLaunchedAsScript() || isInPackageManagerDirectory(execPath) || isRuntimeOrPackageManagerExecutable(execPath)) {
    throw new AdkError({
      code: "UPGRADE_REFUSED_RUNTIME",
      message: `Refusing to self-upgrade because ADK is running through a JavaScript runtime or package manager: ${execPath}

` + `Please upgrade ADK using the same method you used to install it, for example:
` + `   bun add -g @botpress/adk-cli@latest
` + `Or reinstall with the standalone installer:
` + `   curl -fsSL https://github.com/${GITHUB_REPO}/releases/latest/download/install.sh | bash
` + `   powershell -c "irm https://github.com/${GITHUB_REPO}/releases/latest/download/install.ps1 | iex"`,
      expected: true
    });
  }
  return execPath;
}
function checkWritePermissions(path) {
  try {
    const dir = dirname(path);
    accessSync(dir, constants.W_OK);
    if (existsSync(path)) {
      accessSync(path, constants.W_OK);
    }
    return true;
  } catch {
    return false;
  }
}
function rerunWithSudo(binaryPath, tagOrVersion) {
  const args = ["self-upgrade"];
  if (tagOrVersion) {
    args.push(tagOrVersion);
  }
  try {
    const result = spawnSync("sudo", [binaryPath, ...args], { stdio: "inherit" });
    process.exit(result.status ?? 1);
  } catch {
    return false;
  }
  return true;
}
function replaceBinary(currentPath, newBinaryBuffer, isWindows, logger) {
  if (isWindows) {
    const batchScript = `
@echo off
ping /n 2 127.0.0.1 > NUL
move /y "${currentPath}.new" "${currentPath}"
del "%~f0"
    `.trim();
    const batchPath = join(tmpdir(), "adk-upgrade.bat");
    writeFileSync(batchPath, batchScript);
    writeFileSync(currentPath + ".new", newBinaryBuffer);
    logger.info("Update downloaded!", "green");
    logger.info("   Restart your terminal to use the new version.");
    execSync(`start "" /b "${batchPath}"`, { shell: "cmd.exe", windowsHide: true });
  } else {
    const backupPath = currentPath + ".backup";
    try {
      renameSync(currentPath, backupPath);
      writeFileSync(currentPath, newBinaryBuffer);
      chmodSync(currentPath, 493);
      unlinkSync(backupPath);
      logger.info("Successfully upgraded!", "green");
    } catch (error) {
      if (existsSync(backupPath)) {
        try {
          renameSync(backupPath, currentPath);
        } catch {}
      }
      throw error;
    }
  }
}
async function adkSelfUpgrade(currentVersion, tagOrVersion) {
  const logger = createCliLogger();
  try {
    const { isWindows } = getPlatformInfo();
    const currentPath = getCurrentBinaryPath();
    logger.info(`Current version: ${currentVersion}`);
    logger.info(`Binary path: ${currentPath}`);
    const { version: targetVersion, tag } = await getVersion(tagOrVersion);
    if (tag) {
      logger.info(`Target: ${tag} (v${targetVersion})`);
    } else {
      logger.info(`Target version: ${targetVersion}`);
    }
    if (currentVersion === targetVersion) {
      logger.info("You already have this version!", "green");
      return;
    }
    const sudoHint = `sudo adk self-upgrade${tagOrVersion ? ` ${tagOrVersion}` : ""}`;
    if (!isWindows && !checkWritePermissions(currentPath)) {
      logger.warn(`
   Permission denied for: ${currentPath}`);
      if (process.stdin.isTTY) {
        const retry = await promptYesNo("   Retry with sudo? [Y/n] ", process.stderr, { defaultYes: true });
        if (retry) {
          rerunWithSudo(currentPath, tagOrVersion);
        }
      }
      logger.error(`
   Try running with sudo:`);
      logger.info(`   ${sudoHint}`, "cyan");
      throw new AdkError({ code: "UPGRADE_PERMISSION", message: "Permission denied", expected: true });
    }
    const { target, extension } = getPlatformInfo();
    let binaryBuffer;
    if (isWindows) {
      binaryBuffer = await downloadBinaryWindows(targetVersion, target, extension, logger);
    } else {
      binaryBuffer = await downloadBinary(targetVersion, target, extension, logger);
    }
    replaceBinary(currentPath, binaryBuffer, isWindows, logger);
    if (!isWindows) {
      logger.info(`
   v${currentVersion} \u2192 v${targetVersion}`);
      logger.info(`
   Run adk --version to verify`, "cyan");
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    if (isAdkError(error) && error.code === "UPGRADE_REFUSED_RUNTIME") {
      logger.error(`
${errorMessage}`);
      throw new AdkError({
        code: "UPGRADE_REFUSED_RUNTIME",
        message: "Self-upgrade refused",
        expected: true,
        cause: error
      });
    }
    if (isAdkError(error) && error.code === "UPGRADE_PERMISSION") {
      throw error;
    }
    const errCode = error instanceof Error && "code" in error ? error.code : undefined;
    if (errCode === "EACCES" || errCode === "EPERM") {
      const sudoHint = `sudo adk self-upgrade${tagOrVersion ? ` ${tagOrVersion}` : ""}`;
      logger.warn(`
   Permission denied: ${errorMessage}`);
      if (process.stdin.isTTY) {
        const retry = await promptYesNo("   Retry with sudo? [Y/n] ", process.stderr, { defaultYes: true });
        if (retry) {
          rerunWithSudo(process.execPath, tagOrVersion);
        }
      }
      logger.error(`
   Try running with sudo:`);
      logger.info(`   ${sudoHint}`, "cyan");
      throw new AdkError({ code: "UPGRADE_PERMISSION", message: "Permission denied", expected: true, cause: error });
    }
    logger.error(`
Upgrade failed: ${errorMessage}`);
    logger.error(`
   You can manually download from:`);
    logger.error(`   https://github.com/${GITHUB_REPO}/releases/latest`);
    throw error;
  }
}
export {
  adkSelfUpgrade
};