const e = require(`./chunk-BDDJmn7V.js`);
let t = require(`electron`),
  n = require(`node:path`),
  r = e.n(n, 1);
n = e.n(n);
let i = require(`node:crypto`),
  a = require(`node:events`),
  o = require(`node:fs`),
  s = e.n(o, 1);
o = e.n(o);
let c = require(`node:os`),
  l = e.n(c, 1);
c = e.n(c);
let u = require(`node:stream/promises`),
  d = require(`node:net`);
d = e.n(d, 1);
let f = require(`node:fs/promises`);
f = e.n(f, 1);
let p = require(`node:stream`),
  m = require(`node:child_process`);
var h = class extends Error {
    constructor(e, t) {
      super(t), this.code = e
    }
  },
  g = {
    MODULE_NOT_FOUND: `MODULE_NOT_FOUND`,
    UNKNOWN_ERROR: `UNKNOWN_ERROR`,
    TWOFA_CODE_REQUIRED: `TWOFA_CODE_REQUIRED`,
    AUTH_ERROR: `AUTH_ERROR`,
    AUTH_CANCELLED: `AUTH_CANCELLED`,
    HASH_ERROR: `HASH_ERROR`,
    DOWNLOAD_ERROR: `DOWNLOAD_ERROR`,
    UNKNOWN_OS: `UNKNOWN_OS`,
    FETCH_ERROR: `FETCH_ERROR`,
    NET_ERROR: `NET_ERROR`,
    FILE_ERROR: `FILE_ERROR`,
    EXEC_ERROR: `EXEC_ERROR`,
    JAVA_ERROR: `JAVA_ERROR`,
    PATCHER_ERROR: `PATCHER_ERROR`,
    MINECRAFT_ERROR: `MINECRAFT_ERROR`,
    CONFIG_ERROR: `CONFIG_ERROR`
  },
  _ = class {
    constructor(e) {
      e.endsWith(`/`) && (e = e.slice(0, -1)), this.url = `${e}/api/auth`
    }
    async auth(e, t, n) {
      try {
        let r = await fetch(`${this.url}/authenticate`, {
          method: `POST`,
          headers: {
            "Content-Type": `application/json`
          },
          body: JSON.stringify({
            email: e,
            password: t,
            code: n
          })
        });
        if (!r.ok) {
          let e = await r.text();
          throw new h(g.AUTH_ERROR, `AzAuth authentication failed: HTTP ${r.status} ${e}`)
        }
        let i = await r.json();
        if (i.status == `pending` && i.reason == `2fa`) throw new h(g.TWOFA_CODE_REQUIRED, `2FA code required`);
        if (i.status == `error`) throw new h(g.AUTH_ERROR, `AzAuth authentication failed: ${i.reason}`);
        return {
          name: i.username,
          uuid: i.uuid,
          clientToken: i.uuid,
          accessToken: i.access_token,
          userProperties: {},
          meta: {
            online: !1,
            type: `azuriom`
          }
        }
      } catch (e) {
        throw e instanceof h ? e : new h(g.AUTH_ERROR, `AzAuth authentication failed: ${e instanceof Error?e.message:e}`)
      }
    }
    async verify(e) {
      try {
        let t = await fetch(`${this.url}/verify`, {
          method: `POST`,
          headers: {
            "Content-Type": `application/json`
          },
          body: JSON.stringify({
            access_token: e.accessToken
          })
        });
        if (!t.ok) {
          let e = await t.text();
          throw new h(g.AUTH_ERROR, `AzAuth verify failed: HTTP ${t.status} ${e}`)
        }
        let n = await t.json();
        if (n.status == `error`) throw new h(g.AUTH_ERROR, `AzAuth verify failed: ${n.reason}`);
        return {
          name: n.username,
          uuid: n.uuid,
          accessToken: n.accessToken,
          clientToken: n.clientToken,
          userProperties: {},
          meta: {
            online: !1,
            type: `azuriom`
          }
        }
      } catch (e) {
        throw e instanceof h ? e : new h(g.AUTH_ERROR, `AzAuth verify failed: ${e instanceof Error?e.message:e}`)
      }
    }
    async logout(e) {
      try {
        let t = await fetch(`${this.url}/logout`, {
          method: `POST`,
          headers: {
            "Content-Type": `application/json`
          },
          body: JSON.stringify({
            access_token: e.accessToken
          })
        });
        if (!t.ok) {
          let e = await t.text();
          throw new h(g.AUTH_ERROR, `AzAuth logout failed: HTTP ${t.status} ${e}`)
        }
      } catch (e) {
        throw e instanceof h ? e : new h(g.AUTH_ERROR, `AzAuth logout failed: ${e instanceof Error?e.message:e}`)
      }
    }
  },
  v = class {
    constructor() {
      this.emitter = new a.EventEmitter
    }
    on(e, t) {
      return this.emitter.on(e, t), this
    }
    forwardEvents(e) {
      let t = this.emit;
      this.emit = (n, ...r) => (e.emit(n, ...r), t.apply(this, [n, ...r]))
    }
    emit(e, ...t) {
      return this.emitter.emit(e, ...t)
    }
  },
  y = new class {
    getOS() {
      if (process.platform === `win32`) return `win`;
      if (process.platform === `darwin`) return `mac`;
      if (process.platform === `linux`) return `lin`;
      throw new h(g.UNKNOWN_OS, `Unknown operating system`)
    }
    getOS_MCCode() {
      if (process.platform === `win32`) return `windows`;
      if (process.platform === `darwin`) return `osx`;
      if (process.platform === `linux`) return `linux`;
      throw new h(g.UNKNOWN_OS, `Unknown operating system`)
    }
    getArch() {
      if (process.arch.includes(`64`)) return `64`;
      if (process.arch.includes(`32`)) return `32`;
      throw new h(g.UNKNOWN_OS, `Unknown architecture`)
    }
    getArch_MCCode() {
      return process.arch === `x64` || process.arch === `arm64` ? `x64` : `x86`
    }
    getOSVersion() {
      return l.default.release()
    }
    getAppDataFolder() {
      return this.getOS() === `win` ? process.env.APPDATA + `` : this.getOS() === `mac` ? process.env.HOME + `/Library/Application Support` : process.env.HOME + ``
    }
    getRootFolder(e) {
      if (e.slug && e.storage === `isolated`) {
        let t = this.sanitizeSlug(e.slug);
        return r.default.join(this.getServerFolder(e.root), t)
      }
      return this.getServerFolder(e.root)
    }
    getServerFolder(e) {
      return e = e.replace(/[^a-z0-9]/gi, `_`).toLowerCase(), e = this.getOS() === `mac` ? e : `.${e}`, r.default.join(this.getAppDataFolder(), e)
    }
    sanitizeSlug(e) {
      return e.toLowerCase().replace(/\s+/g, `-`).replace(/[^a-z0-9\-]/g, ``)
    }
    getTempFolder() {
      return this.getOS() === `win` ? process.env.TEMP + `` : `/tmp`
    }
    async getFileHash(e) {
      try {
        let t = (0, i.createHash)(`sha1`);
        return await (0, u.pipeline)(s.default.createReadStream(e), t), t.digest(`hex`)
      } catch (t) {
        throw new h(g.HASH_ERROR, `Error while getting hash of the file ${e}: ${t}`)
      }
    }
    isLibAllowed(e) {
      return e.rules ? e.rules.length > 1 ? e.rules[0].action === `allow` && e.rules[1].action === `disallow` ? e.rules[1].os.name !== this.getOS_MCCode() : !1 : e.rules[0].action === `allow` && e.rules[0].os ? e.rules[0].os.name === this.getOS_MCCode() : !0 : !0
    }
    isArgAllowed(e) {
      if (e.rules)
        if (e.rules.length > 1) {
          if (e.rules[0].action === `allow` && e.rules[1].action === `disallow`) {
            if (e.rules[1].os.name) return e.rules[1].os.name !== this.getOS_MCCode();
            if (e.rules[1].os.arch) return e.rules[1].os.arch !== this.getArch_MCCode()
          }
          return !1
        } else return e.rules[0].action === `allow` && e.rules[0].os ? e.rules[0].os.name ? e.rules[0].os.name === this.getOS_MCCode() && e.rules[0].os.version ? +this.getOSVersion().split(`.`)[0] >= 10 : e.rules[0].os.name === this.getOS_MCCode() : e.rules[0].os.arch ? e.rules[0].os.arch === this.getArch_MCCode() : e.rules[0].os.name === this.getOS_MCCode() : !(e.rules[0].action === `allow` && e.rules[0].features);
      return !0
    }
    getLibraryName(e) {
      if (e.includes(`@`)) {
        let t = e.split(`:`);
        if (t.length === 4) {
          let e = t[1] || ``,
            n = t[2] || ``,
            [r, i] = (t[3] || ``).split(`@`);
          return `${e}-${n}${r?`-`+r:``}.${i}`
        }
        if (t.length === 3) {
          let e = t[1] || ``,
            [n, r] = (t[2] || ``).split(`@`);
          return `${e}-${n}.${r}`
        }
      }
      let t = e.split(`:`);
      return `${t[1]}-${t[2]}${t[3]?`-`+t[3]:``}.jar`
    }
    getLibraryPath(e, ...t) {
      let n = e.replace(/@([a-z]*)$/, ``).split(`:`);
      return r.default.join(...t, `${n[0].replace(/\./g,`/`)}/${n[1]}/${n[2]}/`)
    }
    isNewer(e, t) {
      if (e.sha1 === t.sha1) return null;
      let n = e => e.replace(/\\/g, `/`).replace(/\/$/, ``);
      if (r.default.dirname(n(e.path)) !== r.default.dirname(n(t.path))) return !1;
      let i = this.parseVersion(r.default.basename(n(e.path))),
        a = this.parseVersion(r.default.basename(n(t.path)));
      for (let e = 0; e < Math.max(i.length, a.length); e++) {
        let t = i[e] ?? 0,
          n = a[e] ?? 0;
        if (n > t) return !0;
        if (n < t) return !1
      }
      return !1
    }
    async getRemoteFileSize(e, t) {
      try {
        let n = await fetch(e, {
          method: `HEAD`,
          headers: {
            Connection: `close`
          }
        });
        if (!n.ok) throw new h(g.FETCH_ERROR, `${t}: HTTP ${n.status} ${await n.text()}`);
        return Number(n.headers.get(`Content-Length`) ?? 0)
      } catch (e) {
        throw new h(g.FETCH_ERROR, `${t}: ${e instanceof Error?e.message:e}`)
      }
    }
    async getRemoteFileSha1(e, t) {
      try {
        let n = await fetch(e, {
          headers: {
            Connection: `close`
          }
        });
        if (!n.ok) throw new h(g.FETCH_ERROR, `${t}: HTTP ${n.status} ${await n.text()}`);
        return await n.text().then(e => e.trim())
      } catch (e) {
        throw new h(g.FETCH_ERROR, `${t}: ${e instanceof Error?e.message:e}`)
      }
    }
    parseVersion(e) {
      return e.split(`-`)[0].split(`+`)[0].split(`.`).map(e => parseInt(e) || 0)
    }
  },
  b = class extends v {
    constructor(e) {
      super(), this.url = `${e}/files/bootstraps/${y.getOS()}`
    }
    async checkForUpdate() {
      try {
        let e = await this.getUpdater(),
          t = await e.checkForUpdates();
        return t && t.updateInfo.version !== e.currentVersion.version ? {
          updateAvailable: !0,
          currentVersion: e.currentVersion,
          latestVersion: t.updateInfo.version,
          updateInfo: {
            releaseName: t.updateInfo.releaseName ?? null,
            releaseNotes: t.updateInfo.releaseNotes ?? null,
            releaseDate: new Date(t.updateInfo.releaseDate)
          }
        } : {
          updateAvailable: !1,
          currentVersion: e.currentVersion.version,
          latestVersion: e.currentVersion.version
        }
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Error while checking for updates: ${e.message??e}`)
      }
    }
    async download() {
      try {
        return (await (await this.getUpdater()).downloadUpdate())[0] ?? ``
      } catch (e) {
        throw e instanceof h ? e : new h(g.DOWNLOAD_ERROR, `Error while downloading update: ${e.message??e}`)
      }
    }
    async runUpdate(e = !1) {
      try {
        (await this.getUpdater()).quitAndInstall(e, !0)
      } catch (e) {
        throw e instanceof h ? e : new h(g.EXEC_ERROR, `Error while running the installer: ${e.message??e}`)
      }
    }
    async getUpdater() {
      if (this.autoUpdater) return this.autoUpdater;
      try {
        this.autoUpdater = (await Promise.resolve().then(() => e.n(require(`./main-CyGMgeb9.js`).default, 1))).autoUpdater
      } catch {
        throw new h(g.MODULE_NOT_FOUND, "`electron-updater` module is not installed. Please install it with `npm i electron-updater` to use the Bootstraps feature.")
      }
      return this.autoUpdater.autoDownload = !1, this.autoUpdater.autoInstallOnAppQuit = !0, this.autoUpdater.setFeedURL({
        provider: `generic`,
        url: this.url
      }), this.autoUpdater.on(`error`, e => {
        this.emit(`bootstraps_error`, {
          message: e.message ?? e
        })
      }), this.autoUpdater.on(`download-progress`, e => {
        this.emit(`download_progress`, {
          downloaded: {
            amount: 0,
            size: e.transferred
          },
          total: {
            amount: 1,
            size: e.total
          },
          speed: e.bytesPerSecond,
          type: `BOOTSTRAP`
        })
      }), this.autoUpdater.on(`update-downloaded`, () => {
        this.emit(`download_end`, {
          downloaded: {
            amount: 1,
            size: -1
          }
        })
      }), this.autoUpdater
    }
  },
  x = class {
    constructor(e) {
      this.url = `${e}/api`
    }
    async getMaintenance() {
      try {
        let e = await fetch(`${this.url}/maintenance`);
        if (!e.ok) {
          let t = await e.text();
          throw new h(g.FETCH_ERROR, `Error while fetching maintenance status: HTTP ${e.status} ${t}`)
        }
        let t = await e.json();
        return t.startTime ? t : null
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Error while fetching maintenance status: ${e instanceof Error?e.message:e}`)
      }
    }
  },
  S = class {
    constructor(e) {
      this.url = `${e}/api`
    }
    async getNews() {
      try {
        let e = await fetch(`${this.url}/news`);
        if (!e.ok) {
          let t = await e.text();
          throw new h(g.FETCH_ERROR, `Error while fetching News from the EML AdminTool: HTTP ${e.status} ${t}`)
        }
        return (await e.json()).news
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Error while fetching News from the EML AdminTool: ${e instanceof Error?e.message:e}`)
      }
    }
    async getCategories() {
      try {
        let e = await fetch(`${this.url}/news/categories`);
        if (!e.ok) {
          let t = await e.text();
          throw new h(g.FETCH_ERROR, `Error while fetching News Categories from the EML AdminTool: HTTP ${e.status} ${t}`)
        }
        return (await e.json()).categories
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Error while fetching News Categories from the EML AdminTool: ${e instanceof Error?e.message:e}`)
      }
    }
    async getNewsByCategory(e) {
      return []
    }
  },
  C = class {
    constructor(e) {
      this.url = `${e}/api`
    }
    async getBackground() {
      try {
        let e = await fetch(`${this.url}/background`);
        if (!e.ok) {
          let t = await e.text();
          throw new h(g.FETCH_ERROR, `Error while fetching background: HTTP ${e.status} ${t}`)
        }
        return await e.json() ?? null
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Error while fetching background: ${e instanceof Error?e.message:e}`)
      }
    }
  },
  w = class {
    writeByte(e) {
      let t = Buffer.alloc(1);
      return t.writeUInt8(e), t
    }
    writeShort(e) {
      let t = Buffer.alloc(2);
      return t.writeUInt16BE(e), t
    }
    writeInt(e) {
      let t = Buffer.alloc(4);
      return t.writeUInt32BE(e), t
    }
    writeVarInt(e) {
      let t = Buffer.alloc(5),
        n = 0;
      for (;;)
        if (e & 4294967168) t.writeUInt8(e & 127 | 128, n++), e >>>= 7;
        else {
          t.writeUInt8(e, n++);
          break
        } return t.subarray(0, n)
    }
    writeString(e) {
      return Buffer.from(e, `utf8`)
    }
    writeUShort(e) {
      return Buffer.from([e >> 8, e & 255])
    }
    writeStringUTF16BE(e) {
      let t = Buffer.from(e, `utf16le`),
        n = Buffer.alloc(t.length);
      for (let e = 0; e < t.length; e += 2) n[e] = t[e + 1], n[e + 1] = t[e];
      return Buffer.concat([n])
    }
    concat(e) {
      let t = 0;
      for (let n = 0; n < e.length; n++) t += e[n].length;
      return Buffer.concat([this.writeVarInt(t), ...e])
    }
  },
  T = class {
    constructor(e) {
      this.buffer = e, this.offset = 0
    }
    readVarInt() {
      let e = 0,
        t = 0;
      for (;;) {
        let n = this.buffer.readUInt8(this.offset++);
        if (e |= (n & 127) << t++ * 7, (n & 128) != 128) break
      }
      return e
    }
    readString() {
      let e = this.readVarInt(),
        t = this.buffer.toString(`utf8`, this.offset, this.offset + e);
      return this.offset += e, t
    }
    readStringUTF16BE() {
      let e = this.readVarInt() * 2,
        t = Buffer.from(this.buffer.subarray(this.offset + 1, this.offset + e));
      for (let e = 0; e < t.length; e += 2) {
        let n = t[e];
        t[e] = t[e + 1], t[e + 1] = n
      }
      let n = t.toString(`utf16le`);
      return this.offset += e, n
    }
    readShort() {
      let e = this.buffer.readUInt16BE(this.offset);
      return this.offset += 2, e
    }
    readStringUTF16BE_Old() {
      this.offset += 1;
      let e = this.readShort() * 2,
        t = Buffer.from(this.buffer.subarray(this.offset, this.offset + e));
      for (let e = 0; e < t.length; e += 2) {
        let n = t[e];
        t[e] = t[e + 1], t[e + 1] = n
      }
      let n = t.toString(`utf16le`);
      return this.offset += e, n
    }
    getOffset() {
      return this.offset
    }
  },
  E = class {
    constructor(e, t = 25565, n = `modern`, r = -1, i = 5) {
      this.ip = e, this.port = t, this.protocol = n, this.pvn = r, this.timeout = i
    }
    async getStatus() {
      return new Promise((e, t) => {
        let n = new w,
          r = Date.now(),
          i = d.createConnection(this.port, this.ip);
        i.setNoDelay(!0);
        let a = setTimeout(() => {
          t(new h(g.NET_ERROR, `Connection timed out`))
        }, this.timeout * 1e3);
        i.on(`connect`, () => {
          if (this.protocol === `modern`) {
            let e = n.concat([n.writeVarInt(0), n.writeVarInt(this.pvn), n.writeVarInt(this.ip.length), n.writeString(this.ip), n.writeUShort(this.port), n.writeVarInt(1)]);
            i.write(e);
            let t = n.concat([n.writeVarInt(0)]);
            i.write(t)
          } else if (this.protocol === `1.6`) {
            let e = Buffer.concat([n.writeByte(254), n.writeByte(1), n.writeByte(250), n.writeShort(11), n.writeStringUTF16BE(`MC|PingHost`), n.writeShort(7 + 2 * this.ip.length), n.writeByte(74), n.writeShort(this.ip.length), n.writeStringUTF16BE(this.ip), n.writeInt(this.port)]);
            i.write(e)
          } else if (this.protocol === `1.4-1.5`) {
            let e = Buffer.concat([n.writeByte(254), n.writeByte(1)]);
            i.write(e)
          } else if (this.protocol === `beta1.8-1.3`) {
            let e = n.writeByte(254);
            i.write(e)
          } else t(new h(g.NET_ERROR, `Unsupported protocol version`))
        });
        let o = Buffer.alloc(0);
        i.on(`data`, n => {
          let s = Date.now() - r,
            c = typeof n == `string` ? Buffer.from(n) : n;
          if (o = Buffer.concat([o, c]), !(o.length < 5)) {
            if (this.protocol === `modern`) {
              let n = new T(o),
                r = n.readVarInt();
              if (o.length - n.getOffset() < r) return;
              if (n.readVarInt() === 0) try {
                let t = JSON.parse(n.readString());
                e({
                  ping: s,
                  version: t.version.name,
                  motd: typeof t.description == `object` && typeof t.description.text == `string` ? t.description.text : typeof t.description == `string` ? t.description : ``,
                  players: {
                    max: t.players.max,
                    online: t.players.online
                  }
                }), i.destroy(), clearTimeout(a)
              } catch (e) {
                t(new h(g.NET_ERROR, `Received invalid response: ${e}`)), i.destroy(), clearTimeout(a)
              } else t(new h(g.NET_ERROR, `Received unexpected packet`)), i.destroy(), clearTimeout(a)
            } else if (this.protocol === `1.6` || this.protocol === `1.4-1.5`)
              if (o.readUInt8(0) === 255) {
                let n = new T(o).readStringUTF16BE_Old().split(`\0`);
                n[0] !== `§1` && (t(new h(g.NET_ERROR, `Received invalid response: the first field is not '§1'`)), i.destroy(), clearTimeout(a)), e({
                  ping: s,
                  version: n[2],
                  motd: n[3],
                  players: {
                    max: +n[5],
                    online: +n[4]
                  }
                }), i.destroy(), clearTimeout(a)
              } else t(new h(g.NET_ERROR, `Received invalid response: wrong packet identifier`)), i.destroy(), clearTimeout(a);
            else if (this.protocol === `beta1.8-1.3`) {
              let n = new T(o).readStringUTF16BE_Old();
              if (this.protocol === `beta1.8-1.3`) {
                let t = n.split(`§`);
                e({
                  ping: s,
                  version: `< 1.4`,
                  motd: t[0],
                  players: {
                    max: +t[2],
                    online: +t[1]
                  }
                }), i.destroy(), clearTimeout(a)
              } else t(new h(g.NET_ERROR, `Received invalid response: wrong packet identifier`)), i.destroy(), clearTimeout(a)
            }
          }
        }), i.on(`error`, e => t(new h(g.NET_ERROR, e)))
      })
    }
  },
  D = `https://piston-meta.mojang.com/mc/game/version_manifest_v2.json`,
  O = `https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json`,
  k = new class {
    async getMinecraftManifest(e, t) {
      let n = e.minecraft.version ?? t?.minecraftVersion;
      if (!n) throw new h(g.MINECRAFT_ERROR, `Minecraft version is not specified in the configuration or loader information`);
      try {
        let e = await this.getMinecraftManifestUrl(n),
          t = await fetch(e);
        if (!t.ok) {
          let e = await t.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch Minecraft manifest: HTTP ${t.status} ${e}`)
        }
        return await t.json()
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Failed to fetch Minecraft manifest: ${e instanceof Error?e.message:e}`)
      }
    }
    async getJavaManifest(e, t) {
      try {
        let n = await this.getJavaManifestUrl(e, t),
          r = await fetch(n);
        if (!r.ok) {
          let e = await r.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch Java manifest: HTTP ${r.status} ${e}`)
        }
        return await r.json()
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Failed to fetch Java manifest: ${e instanceof Error?e.message:e}`)
      }
    }
    async getMinecraftManifestUrl(e) {
      try {
        let t = await fetch(D);
        if (!t.ok) {
          let e = await t.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch Minecraft version manifest: HTTP ${t.status} ${e}`)
        }
        let n = await t.json();
        if (e = e === `latest_release` ? n.latest.release : e === `latest_snapshot` ? n.latest.snapshot : e || `latest_release`, !n.versions.find(t => t.id === e)) throw new h(g.MINECRAFT_ERROR, `Minecraft version ${e} not found in manifest`);
        return n.versions.find(t => t.id === e).url
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Failed to fetch Minecraft version manifest: ${e instanceof Error?e.message:e}`)
      }
    }
    async getJavaManifestUrl(e, t) {
      let n = {
          win32: {
            x64: `windows-x64`,
            ia32: `windows-x86`,
            arm64: `windows-arm64`
          },
          darwin: {
            x64: `mac-os`,
            arm64: `mac-os-arm64`
          },
          linux: {
            x64: `linux`,
            ia32: `linux-i386`
          }
        },
        r = process.arch,
        i = process.platform;
      if (i !== `win32` && i !== `darwin` && i !== `linux`) throw new h(g.UNKNOWN_OS, `Unsupported platform: ${i}`);
      if (i === `win32` && r !== `x64` && r !== `ia32` && r !== `arm64` || i === `darwin` && r !== `x64` && r !== `arm64` || i === `linux` && r !== `x64` && r !== `ia32`) throw new h(g.UNKNOWN_OS, `Unsupported architecture: ${r}`);
      try {
        let a = await fetch(O);
        if (!a.ok) {
          let e = await a.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch Java manifest: HTTP ${a.status} ${e}`)
        }
        let o = await a.json(),
          s = n[i][r];
        if (i === `darwin` && r === `arm64`) {
          let t = o[s]?.[e];
          (!t || t.length === 0) && (s = `mac-os`)
        }
        if (o[s][e][0]?.manifest) return o[s][e][0].manifest.url;
        let c = Object.keys(o[s]).find(e => o[s][e][0]?.version.name.split(`.`)[0] === t);
        if (c) return o[s][c][0].manifest.url;
        throw new h(g.JAVA_ERROR, `Java version ${e} not found in manifest`)
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Failed to fetch Java manifest: ${e instanceof Error?e.message:e}`)
      }
    }
  },
  A = class extends v {
    constructor(e) {
      super(), this.CONCURRENCY_LIMIT = 8, this.size = 0, this.amount = 0, this.downloaded = {
        amount: 0,
        size: 0
      }, this.speed = 0, this.lastTime = 0, this.lastSize = 0, this.dest = r.default.join(e)
    }
    async download(e, t = !1) {
      let n = t ? e : await this.getFilesToDownload(e);
      if (this.size = n.reduce((e, t) => e + (t.size ?? 0), 0), this.amount = n.length, this.downloaded = {
          amount: 0,
          size: 0
        }, this.speed = 0, this.lastTime = Date.now(), this.lastSize = 0, this.size === 0 || n.length === 0) {
        this.emit(`download_end`, {
          downloaded: this.downloaded
        });
        return
      }
      let r = [...n],
        i = Array(this.CONCURRENCY_LIMIT).fill(null).map(async () => {
          for (; r.length > 0;) {
            let e = r.shift();
            e && await this.downloadFileWithRetry(e)
          }
        });
      await Promise.all(i), this.emit(`download_end`, {
        downloaded: this.downloaded
      })
    }
    async getFilesToDownload(e) {
      let t = [],
        n = e.map(async e => {
          let n = r.default.join(this.dest, e.path, e.name),
            i = r.default.relative(this.dest, n);
          if (!(i && !i.startsWith(`..`) && !r.default.isAbsolute(i))) {
            this.emit(`download_error`, {
              filename: e.name,
              type: e.type,
              message: `Unsafe file path detected, skipping.`
            });
            return
          }
          if (e.type === `FOLDER`) try {
            await f.default.access(n)
          } catch {
            await f.default.mkdir(n, {
              recursive: !0
            })
          }
          let a = !1;
          try {
            await f.default.access(n), e.sha1 && e.sha1 !== await y.getFileHash(n) && (a = !0)
          } catch {
            a = !0
          }
          a && e.url && t.push(e)
        });
      return await Promise.all(n), t
    }
    async downloadFileWithRetry(e, t = 0) {
      try {
        await this.downloadFile(e), this.downloaded.amount++
      } catch (n) {
        if (t < 5) return await new Promise(e => setTimeout(e, 1e3 * (t + 1))), this.downloadFileWithRetry(e, t + 1);
        throw this.emit(`download_error`, {
          filename: e.name,
          type: e.type,
          message: n.message ?? n
        }), new h(g.DOWNLOAD_ERROR, `Failed to download ${e.name} after 5 attempts`)
      }
    }
    async downloadFile(e) {
      let t = r.default.join(this.dest, e.path),
        n = r.default.join(t, e.name),
        i = 0;
      await f.default.mkdir(t, {
        recursive: !0
      });
      let a = await fetch(e.url, {
        headers: {
          Accept: `application/octet-stream`
        }
      });
      if (!a.ok || !a.body) {
        let t = await a.text();
        throw new h(g.FETCH_ERROR, `Error while fetching ${e.name}: HTTP ${a.status} ${t}`)
      }
      let ab = await a.arrayBuffer(),
        buf = Buffer.from(ab),
        o = s.default.createWriteStream(n),
        l = buf.length;
      return new Promise((t, r) => {
        o.on(`error`, e => { r(e) });
        o.write(buf, async () => {
          o.end();
          try {
            await this.chmodJavaFiles(n, e);
            if (e.sha1) {
              let hash = await y.getFileHash(n);
              if (hash !== e.sha1) {
                await f.default.unlink(n).catch(() => {});
                throw new h(g.HASH_ERROR, `SHA1 mismatch for ${e.name}`)
              }
            }
            this.downloaded.size += l, this.emit(`download_progress`, {
              total: { amount: this.amount, size: this.size },
              downloaded: this.downloaded,
              speed: Math.floor(buf.length / 131072),
              type: e.type
            }), t()
          } catch (e) { r(e) }
        })
      })
    }
    async chmodJavaFiles(e, t) {
      process.platform !== `win32` && t.executable && await f.default.chmod(e, 493)
    }
  },
  j = class extends v {
    constructor(e, t, n) {
      super(), typeof e == `object` && e ? (this.minecraftVersion = e.minecraft?.version, this.root = e.root, this.url = e.url) : (this.minecraftVersion = e ?? void 0, this.root = t, this.url = n)
    }
    async getFiles(e) {
      e ??= await k.getMinecraftManifest({
        minecraft: {
          version: this.minecraftVersion ?? void 0
        },
        url: this.url
      });
      let t = e.javaVersion?.component ?? `jre-legacy`,
        n = e.javaVersion?.majorVersion.toString() ?? `8`,
        i = await k.getJavaManifest(t, n),
        a = [];
      return Object.entries(i.files).forEach(e => {
        let t = this.normalizeJavaPath(e[0], n);
        t && (e[1].type === `directory` ? a.push({
          name: r.default.basename(e[0]),
          path: t,
          url: ``,
          type: `FOLDER`
        }) : e[1].downloads && a.push({
          name: r.default.basename(e[0]),
          path: t,
          url: e[1].downloads.raw.url,
          size: e[1].downloads.raw.size,
          sha1: e[1].downloads.raw.sha1,
          type: `JAVA`,
          executable: e[1].executable === !0
        }))
      }), a
    }
    async download() {
      let e = await this.getFiles(),
        t = new A(y.getServerFolder(this.root));
      t.forwardEvents(this), await t.download(e)
    }
    async check(e = r.default.join(y.getServerFolder(this.root), `runtime`, "jre-${X}", `bin`, `java`), t = 8) {
      return new Promise((n, r) => {
        let i = (0, m.spawn)(e.replace("${X}", t + ``), [`-version`]),
          a = ``;
        i.stdout.on(`data`, e => {
          a += e.toString()
        }), i.stderr.on(`data`, e => {
          a += e.toString()
        }), i.on(`error`, e => {
          r(new h(g.JAVA_ERROR, `Java is not correctly installed: ${e.message}`))
        }), i.on(`close`, e => {
          if (e !== 0 && a.length === 0) {
            r(new h(g.JAVA_ERROR, `Java exited with code ${e}`));
            return
          }
          let i = a.match(/"(.*?)"/),
            o = {
              version: i ? i.pop() : t + ``,
              arch: a.includes(`64-Bit`) ? `64-bit` : `32-bit`
            };
          this.emit(`java_info`, o), n(o)
        })
      })
    }
    normalizeJavaPath(e, t) {
      if (e.endsWith(`.bundle`)) return null;
      if (e.includes(`.bundle/`)) {
        let n = e.indexOf(`.bundle/Contents/Home/`);
        if (n === -1) return null;
        let i = e.slice(n + 22);
        return r.default.join(`runtime`, `jre-${t}`, r.default.dirname(i), `/`)
      }
      return r.default.join(`runtime`, `jre-${t}`, r.default.dirname(e), `/`)
    }
  },
  M = e.t(((e, t) => {
    t.exports = n;

    function n() {
      this.pending = 0, this.max = 1 / 0, this.listeners = [], this.waiting = [], this.error = null
    }
    n.prototype.go = function(e) {
      this.pending < this.max ? i(this, e) : this.waiting.push(e)
    }, n.prototype.wait = function(e) {
      this.pending === 0 ? e(this.error) : this.listeners.push(e)
    }, n.prototype.hold = function() {
      return r(this)
    };

    function r(e) {
      e.pending += 1;
      var t = !1;
      return n;

      function n(n) {
        if (t) throw Error(`callback called twice`);
        if (t = !0, e.error = e.error || n, --e.pending, e.waiting.length > 0 && e.pending < e.max) i(e, e.waiting.shift());
        else if (e.pending === 0) {
          var a = e.listeners;
          e.listeners = [], a.forEach(r)
        }
      }

      function r(t) {
        t(e.error)
      }
    }

    function i(e, t) {
      t(r(e))
    }
  })),
  N = e.t((e => {
    var t = require(`fs`),
      n = require(`util`),
      r = require(`stream`),
      i = r.Readable,
      a = r.Writable,
      o = r.PassThrough,
      s = M(),
      c = require(`events`).EventEmitter;
    e.createFromBuffer = p, e.createFromFd = m, e.BufferSlicer = f, e.FdSlicer = l, n.inherits(l, c);

    function l(e, t) {
      t ||= {}, c.call(this), this.fd = e, this.pend = new s, this.pend.max = 1, this.refCount = 0, this.autoClose = !!t.autoClose
    }
    l.prototype.read = function(e, n, r, i, a) {
      var o = this;
      o.pend.go(function(s) {
        t.read(o.fd, e, n, r, i, function(e, t, n) {
          s(), a(e, t, n)
        })
      })
    }, l.prototype.write = function(e, n, r, i, a) {
      var o = this;
      o.pend.go(function(s) {
        t.write(o.fd, e, n, r, i, function(e, t, n) {
          s(), a(e, t, n)
        })
      })
    }, l.prototype.createReadStream = function(e) {
      return new u(this, e)
    }, l.prototype.createWriteStream = function(e) {
      return new d(this, e)
    }, l.prototype.ref = function() {
      this.refCount += 1
    }, l.prototype.unref = function() {
      var e = this;
      if (--e.refCount, e.refCount > 0) return;
      if (e.refCount < 0) throw Error(`invalid unref`);
      e.autoClose && t.close(e.fd, n);

      function n(t) {
        t ? e.emit(`error`, t) : e.emit(`close`)
      }
    }, n.inherits(u, i);

    function u(e, t) {
      t ||= {}, i.call(this, t), this.context = e, this.context.ref(), this.start = t.start || 0, this.endOffset = t.end, this.pos = this.start, this.destroyed = !1
    }
    u.prototype._read = function(e) {
      var n = this;
      if (!n.destroyed) {
        var r = Math.min(n._readableState.highWaterMark, e);
        if (n.endOffset != null && (r = Math.min(r, n.endOffset - n.pos)), r <= 0) {
          n.destroyed = !0, n.push(null), n.context.unref();
          return
        }
        n.context.pend.go(function(e) {
          if (n.destroyed) return e();
          var i = Buffer.allocUnsafe(r);
          t.read(n.context.fd, i, 0, r, n.pos, function(t, r) {
            t ? n.destroy(t) : r === 0 ? (n.destroyed = !0, n.push(null), n.context.unref()) : (n.pos += r, n.push(i.slice(0, r))), e()
          })
        })
      }
    }, u.prototype.destroy = function(e) {
      this.destroyed || (e ||= Error(`stream destroyed`), this.destroyed = !0, this.emit(`error`, e), this.context.unref())
    }, n.inherits(d, a);

    function d(e, t) {
      t ||= {}, a.call(this, t), this.context = e, this.context.ref(), this.start = t.start || 0, this.endOffset = t.end == null ? 1 / 0 : +t.end, this.bytesWritten = 0, this.pos = this.start, this.destroyed = !1, this.on(`finish`, this.destroy.bind(this))
    }
    d.prototype._write = function(e, n, r) {
      var i = this;
      if (!i.destroyed) {
        if (i.pos + e.length > i.endOffset) {
          var a = Error(`maximum file length exceeded`);
          a.code = `ETOOBIG`, i.destroy(), r(a);
          return
        }
        i.context.pend.go(function(n) {
          if (i.destroyed) return n();
          t.write(i.context.fd, e, 0, e.length, i.pos, function(e, t) {
            e ? (i.destroy(), n(), r(e)) : (i.bytesWritten += t, i.pos += t, i.emit(`progress`), n(), r())
          })
        })
      }
    }, d.prototype.destroy = function() {
      this.destroyed || (this.destroyed = !0, this.context.unref())
    }, n.inherits(f, c);

    function f(e, t) {
      c.call(this), t ||= {}, this.refCount = 0, this.buffer = e, this.maxChunkSize = t.maxChunkSize || 2 ** 53 - 1
    }
    f.prototype.read = function(e, t, n, r, i) {
      if (!(0 <= t && t <= e.length)) throw RangeError(`offset outside buffer: 0 <= ` + t + ` <= ` + e.length);
      if (r < 0) throw RangeError(`position is negative: ` + r);
      if (t + n > e.length && (n = e.length - t), r + n > this.buffer.length && (n = this.buffer.length - r), n <= 0) {
        setImmediate(function() {
          i(null, 0)
        });
        return
      }
      this.buffer.copy(e, t, r, r + n), setImmediate(function() {
        i(null, n)
      })
    }, f.prototype.write = function(e, t, n, r, i) {
      e.copy(this.buffer, r, t, t + n), setImmediate(function() {
        i(null, n, e)
      })
    }, f.prototype.createReadStream = function(e) {
      e ||= {};
      var t = new o(e);
      t.destroyed = !1, t.start = e.start || 0, t.endOffset = e.end, t.pos = t.endOffset || this.buffer.length;
      for (var n = this.buffer.slice(t.start, t.pos), r = 0;;) {
        var i = r + this.maxChunkSize;
        if (i >= n.length) {
          r < n.length && t.write(n.slice(r, n.length));
          break
        }
        t.write(n.slice(r, i)), r = i
      }
      return t.end(), t.destroy = function() {
        t.destroyed = !0
      }, t
    }, f.prototype.createWriteStream = function(e) {
      var t = this;
      e ||= {};
      var n = new a(e);
      return n.start = e.start || 0, n.endOffset = e.end == null ? this.buffer.length : +e.end, n.bytesWritten = 0, n.pos = n.start, n.destroyed = !1, n._write = function(e, r, i) {
        if (!n.destroyed) {
          var a = n.pos + e.length;
          if (a > n.endOffset) {
            var o = Error(`maximum file length exceeded`);
            o.code = `ETOOBIG`, n.destroyed = !0, i(o);
            return
          }
          e.copy(t.buffer, n.pos, 0, e.length), n.bytesWritten += e.length, n.pos = a, n.emit(`progress`), i()
        }
      }, n.destroy = function() {
        n.destroyed = !0
      }, n
    }, f.prototype.ref = function() {
      this.refCount += 1
    }, f.prototype.unref = function() {
      if (--this.refCount, this.refCount < 0) throw Error(`invalid unref`)
    };

    function p(e, t) {
      return new f(e, t)
    }

    function m(e, t) {
      return new l(e, t)
    }
  })),
  P = e.t(((e, t) => {
    var n = require(`buffer`).Buffer,
      r = [0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117];
    typeof Int32Array < `u` && (r = new Int32Array(r));

    function i(e) {
      if (n.isBuffer(e)) return e;
      var t = typeof n.alloc == `function` && typeof n.from == `function`;
      if (typeof e == `number`) return t ? n.alloc(e) : new n(e);
      if (typeof e == `string`) return t ? n.from(e) : new n(e);
      throw Error(`input must be buffer, number, or string, received ` + typeof e)
    }

    function a(e) {
      var t = i(4);
      return t.writeInt32BE(e, 0), t
    }

    function o(e, t) {
      e = i(e), n.isBuffer(t) && (t = t.readUInt32BE(0));
      for (var a = ~~t ^ -1, o = 0; o < e.length; o++) a = r[(a ^ e[o]) & 255] ^ a >>> 8;
      return a ^ -1
    }

    function s() {
      return a(o.apply(null, arguments))
    }
    s.signed = function() {
      return o.apply(null, arguments)
    }, s.unsigned = function() {
      return o.apply(null, arguments) >>> 0
    }, t.exports = s
  })),
  F = e.t((e => {
    var t = require(`fs`),
      n = require(`zlib`),
      r = N(),
      i = P(),
      a = require(`util`),
      o = require(`events`).EventEmitter,
      s = require(`stream`).Transform,
      c = require(`stream`).PassThrough,
      l = require(`stream`).Writable;
    e.open = u;

    function u(e, n, r) {
      typeof n == `function` && (r = n, n = null), n ??= {}, n.autoClose ??= !0, n.lazyEntries ??= !1, n.decodeStrings ??= !0, n.validateEntrySizes ??= !0, n.strictFileNames ??= !1, r ??= j, t.open(e, `r`, function(e, i) {
        if (e) return r(e);
        d(i, n, function(e, n) {
          e && t.close(i, j), r(e, n)
        })
      })
    }

    function d(e, n, i) {
      typeof n == `function` && (i = n, n = null), n ??= {}, n.autoClose ??= !1, n.lazyEntries ??= !1, n.decodeStrings ??= !0, n.validateEntrySizes ??= !0, n.strictFileNames ??= !1, i ??= j, t.fstat(e, function(t, a) {
        if (t) return i(t);
        f(r.createFromFd(e, {
          autoClose: !0
        }), a.size, n, i)
      })
    }

    function f(e, t, n, r) {
      typeof n == `function` && (r = n, n = null), n ??= {}, n.autoClose ??= !0, n.lazyEntries ??= !1, n.decodeStrings ??= !0;
      var i = !!n.decodeStrings;
      if (n.validateEntrySizes ??= !0, n.strictFileNames ??= !1, r ??= j, typeof t != `number`) throw Error(`expected totalSize parameter to be a number`);
      if (t > 2 ** 53 - 1) throw Error(`zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.`);
      e.ref();
      var a = 22,
        o = 20,
        s = Math.min(o + a + 65535, t),
        c = k(s);
      S(e, c, 0, s, t - c.length, function(l) {
        if (l) return r(l);
        for (var u = s - a; u >= 0; --u)
          if (c.readUInt32LE(u) === 101010256) {
            var d = c.subarray(u),
              f = d.readUInt16LE(4),
              m = d.readUInt16LE(10),
              h = d.readUInt32LE(16),
              g = d.readUInt16LE(20),
              _ = d.length - a;
            if (g !== _) return r(Error(`Invalid comment length. Expected: ` + _ + `. Found: ` + g + ". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));
            var v = i ? D(d.subarray(22), !1) : d.subarray(22);
            if (u - o >= 0 && c.readUInt32LE(u - o) === 117853008) {
              var y = O(c.subarray(u - o, u - o + o), 8),
                b = k(56);
              return S(e, b, 0, b.length, y, function(a) {
                return a ? r(a) : b.readUInt32LE(0) === 101075792 ? (f = b.readUInt32LE(16), f === 0 ? (m = O(b, 32), h = O(b, 48), r(null, new p(e, h, t, m, v, n.autoClose, n.lazyEntries, i, n.validateEntrySizes, n.strictFileNames))) : r(Error(`multi-disk zip files are not supported: found disk number: ` + f))) : r(Error(`invalid zip64 end of central directory record signature`))
              })
            }
            return f === 0 ? r(null, new p(e, h, t, m, v, n.autoClose, n.lazyEntries, i, n.validateEntrySizes, n.strictFileNames)) : r(Error(`multi-disk zip files are not supported: found disk number: ` + f))
          } r(Error(`End of central directory record signature not found. Either not a zip file, or file is truncated.`))
      })
    }
    a.inherits(p, o);

    function p(e, t, n, r, i, a, s, c, l, u) {
      var d = this;
      o.call(d), d.reader = e, d.reader.on(`error`, function(e) {
        h(d, e)
      }), d.reader.once(`close`, function() {
        d.emit(`close`)
      }), d.readEntryCursor = t, d.fileSize = n, d.entryCount = r, d.comment = i, d.entriesRead = 0, d.autoClose = !!a, d.lazyEntries = !!s, d.decodeStrings = !!c, d.validateEntrySizes = !!l, d.strictFileNames = !!u, d.isOpen = !0, d.emittedError = !1, d.lazyEntries || d._readEntry()
    }
    p.prototype.close = function() {
      this.isOpen && (this.isOpen = !1, this.reader.unref())
    };

    function m(e, t) {
      e.autoClose && e.close(), h(e, t)
    }

    function h(e, t) {
      e.emittedError || (e.emittedError = !0, e.emit(`error`, t))
    }
    p.prototype.readEntry = function() {
      if (!this.lazyEntries) throw Error(`readEntry() called without lazyEntries:true`);
      this._readEntry()
    }, p.prototype._readEntry = function() {
      var e = this;
      if (e.entryCount === e.entriesRead) {
        setImmediate(function() {
          e.autoClose && e.close(), !e.emittedError && e.emit(`end`)
        });
        return
      }
      if (!e.emittedError) {
        var t = k(46);
        S(e.reader, t, 0, t.length, e.readEntryCursor, function(n) {
          if (n) return m(e, n);
          if (!e.emittedError) {
            var r = new g,
              i = t.readUInt32LE(0);
            if (i !== 33639248) return m(e, Error(`invalid central directory file header signature: 0x` + i.toString(16)));
            if (r.versionMadeBy = t.readUInt16LE(4), r.versionNeededToExtract = t.readUInt16LE(6), r.generalPurposeBitFlag = t.readUInt16LE(8), r.compressionMethod = t.readUInt16LE(10), r.lastModFileTime = t.readUInt16LE(12), r.lastModFileDate = t.readUInt16LE(14), r.crc32 = t.readUInt32LE(16), r.compressedSize = t.readUInt32LE(20), r.uncompressedSize = t.readUInt32LE(24), r.fileNameLength = t.readUInt16LE(28), r.extraFieldLength = t.readUInt16LE(30), r.fileCommentLength = t.readUInt16LE(32), r.internalFileAttributes = t.readUInt16LE(36), r.externalFileAttributes = t.readUInt32LE(38), r.relativeOffsetOfLocalHeader = t.readUInt32LE(42), r.generalPurposeBitFlag & 64) return m(e, Error(`strong encryption is not supported`));
            e.readEntryCursor += 46, t = k(r.fileNameLength + r.extraFieldLength + r.fileCommentLength), S(e.reader, t, 0, t.length, e.readEntryCursor, function(n) {
              if (n) return m(e, n);
              if (!e.emittedError) {
                r.fileNameRaw = t.subarray(0, r.fileNameLength);
                var i = r.fileNameLength + r.extraFieldLength;
                r.extraFieldRaw = t.subarray(r.fileNameLength, i), r.fileCommentRaw = t.subarray(i, i + r.fileCommentLength);
                try {
                  r.extraFields = x(r.extraFieldRaw)
                } catch (t) {
                  return m(e, t)
                }
                if (e.decodeStrings) {
                  var a = (r.generalPurposeBitFlag & 2048) != 0;
                  r.fileComment = D(r.fileCommentRaw, a), r.fileName = y(r.generalPurposeBitFlag, r.fileNameRaw, r.extraFields, e.strictFileNames);
                  var o = b(r.fileName);
                  if (o != null) return m(e, Error(o))
                } else r.fileComment = r.fileCommentRaw, r.fileName = r.fileNameRaw;
                r.comment = r.fileComment, e.readEntryCursor += t.length, e.entriesRead += 1;
                for (var s = 0; s < r.extraFields.length; s++) {
                  var c = r.extraFields[s];
                  if (c.id === 1) {
                    var l = c.data,
                      u = 0;
                    if (r.uncompressedSize === 4294967295) {
                      if (u + 8 > l.length) return m(e, Error(`zip64 extended information extra field does not include uncompressed size`));
                      r.uncompressedSize = O(l, u), u += 8
                    }
                    if (r.compressedSize === 4294967295) {
                      if (u + 8 > l.length) return m(e, Error(`zip64 extended information extra field does not include compressed size`));
                      r.compressedSize = O(l, u), u += 8
                    }
                    if (r.relativeOffsetOfLocalHeader === 4294967295) {
                      if (u + 8 > l.length) return m(e, Error(`zip64 extended information extra field does not include relative header offset`));
                      r.relativeOffsetOfLocalHeader = O(l, u), u += 8
                    }
                    break
                  }
                }
                if (e.validateEntrySizes && r.compressionMethod === 0) {
                  var d = r.uncompressedSize;
                  if (r.isEncrypted() && (d += 12), r.compressedSize !== d) {
                    var f = `compressed/uncompressed size mismatch for stored file: ` + r.compressedSize + ` != ` + r.uncompressedSize;
                    return m(e, Error(f))
                  }
                }
                e.emit(`entry`, r), e.lazyEntries || e._readEntry()
              }
            })
          }
        })
      }
    }, p.prototype.openReadStream = function(e, t, n) {
      var r = this,
        i = 0,
        a = e.compressedSize;
      if (n ?? (n = t, t = null), t == null) t = {};
      else {
        if (t.decodeFileData === !1) {
          if (t.decrypt != null) throw Error(`cannot use options.decrypt when options.decodeFileData === false`);
          if (t.decompress != null) throw Error(`cannot use options.decompress when options.decodeFileData === false`)
        } else {
          if (t.decrypt != null) {
            if (!e.isEncrypted()) throw Error(`options.decrypt can only be specified for encrypted entries. See also option decodeFileData.`);
            if (t.decrypt !== !1) throw Error(`invalid options.decrypt value: ` + t.decrypt);
            if (e.isCompressed() && t.decompress !== !1) throw Error(`entry is encrypted and compressed, and options.decompress !== false. See also option decodeFileData.`)
          }
          if (t.decompress != null) {
            if (!e.isCompressed()) throw Error(`options.decompress can only be specified for compressed entries. See also option decodeFileData.`);
            if (!(t.decompress === !1 || t.decompress === !0)) throw Error(`invalid options.decompress value: ` + t.decompress);
            s = t.decompress
          }
        }
        if (t.start != null) {
          if (i = t.start, i < 0) throw Error(`options.start < 0`);
          if (i > e.compressedSize) throw Error(`options.start > entry.compressedSize`)
        }
        if (t.end != null) {
          if (a = t.end, a < 0) throw Error(`options.end < 0`);
          if (a > e.compressedSize) throw Error(`options.end > entry.compressedSize`);
          if (a < i) throw Error(`options.end < options.start`)
        }
      }
      var o = t.decodeFileData === !1 || (e.compressionMethod === 0 || e.compressionMethod === 8 && t.decompress === !1) && (!e.isEncrypted() || t.decrypt === !1);
      if ((t.start != null || t.end != null) && !o) throw Error(`start/end range require options.decodeFileData === false for non-trivial encoded entries.`);
      if (!r.isOpen) return n(Error(`closed`));
      if (e.isEncrypted() && !o && t.decrypt !== !1) return n(Error(`entry is encrypted, and options.decodeFileData !== false`));
      var s;
      if (o) s = !1;
      else if (e.compressionMethod === 8) s = t.decodeFileData !== !0;
      else return n(Error(`unsupported compression method: ` + e.compressionMethod));
      r.readLocalFileHeader(e, {
        minimal: !0
      }, function(t, o) {
        if (t) return n(t);
        r.openReadStreamLowLevel(o.fileDataStart, e.compressedSize, i, a, s, e.uncompressedSize, n)
      })
    }, p.prototype.openReadStreamLowLevel = function(e, t, r, i, a, o, s) {
      var c = this;
      e + t;
      var l = c.reader.createReadStream({
          start: e + r,
          end: e + i
        }),
        u = l;
      if (a) {
        var d = !1,
          f = n.createInflateRaw();
        l.on(`error`, function(e) {
          setImmediate(function() {
            d || f.emit(`error`, e)
          })
        }), l.pipe(f), c.validateEntrySizes ? (u = new C(o), f.on(`error`, function(e) {
          setImmediate(function() {
            d || u.emit(`error`, e)
          })
        }), f.pipe(u)) : u = f, A(u, function() {
          d = !0, f !== u && f.unpipe(u), l.unpipe(f), l.destroy()
        })
      }
      s(null, u)
    }, p.prototype.readLocalFileHeader = function(e, t, n) {
      var r = this;
      n ?? (n = t, t = null), t ??= {}, r.reader.ref();
      var i = k(30);
      S(r.reader, i, 0, i.length, e.relativeOffsetOfLocalHeader, function(a) {
        try {
          if (a) return n(a);
          var o = i.readUInt32LE(0);
          if (o !== 67324752) return n(Error(`invalid local file header signature: 0x` + o.toString(16)));
          var s = i.readUInt16LE(26),
            c = i.readUInt16LE(28),
            l = e.relativeOffsetOfLocalHeader + 30 + s + c;
          if (l + e.compressedSize > r.fileSize) return n(Error(`file data overflows file bounds: ` + l + ` + ` + e.compressedSize + ` > ` + r.fileSize));
          if (t.minimal) return n(null, {
            fileDataStart: l
          });
          var u = new _;
          u.fileDataStart = l, u.versionNeededToExtract = i.readUInt16LE(4), u.generalPurposeBitFlag = i.readUInt16LE(6), u.compressionMethod = i.readUInt16LE(8), u.lastModFileTime = i.readUInt16LE(10), u.lastModFileDate = i.readUInt16LE(12), u.crc32 = i.readUInt32LE(14), u.compressedSize = i.readUInt32LE(18), u.uncompressedSize = i.readUInt32LE(22), u.fileNameLength = s, u.extraFieldLength = c, i = k(s + c), r.reader.ref(), S(r.reader, i, 0, i.length, e.relativeOffsetOfLocalHeader + 30, function(e) {
            try {
              return e ? n(e) : (u.fileName = i.subarray(0, s), u.extraField = i.subarray(s), n(null, u))
            } finally {
              r.reader.unref()
            }
          })
        } finally {
          r.reader.unref()
        }
      })
    };

    function g() {}
    g.prototype.getLastModDate = function(e) {
      if (e ??= {}, !e.forceDosFormat)
        for (var t = 0; t < this.extraFields.length; t++) {
          var n = this.extraFields[t];
          if (n.id === 21589) {
            var r = n.data;
            if (r.length < 5 || !(r[0] & 1)) continue;
            var i = r.readInt32LE(1);
            return new Date(i * 1e3)
          } else if (n.id === 10) {
            var r = n.data;
            if (r.length !== 32 || r.readUInt16LE(4) !== 1 || r.readUInt16LE(6) !== 24) continue;
            var a = (r.readUInt32LE(8) + 4294967296 * r.readInt32LE(12)) / 1e4 - 0xa9730b66800;
            return new Date(a)
          }
        }
      return v(this.lastModFileDate, this.lastModFileTime, e.timezone)
    }, g.prototype.canDecodeFileData = function() {
      return !this.isEncrypted() && (this.compressionMethod === 0 || this.compressionMethod === 8)
    }, g.prototype.isEncrypted = function() {
      return (this.generalPurposeBitFlag & 1) != 0
    }, g.prototype.isCompressed = function() {
      return this.compressionMethod === 8
    };

    function _() {}

    function v(e, t, n) {
      var r = e & 31,
        i = (e >> 5 & 15) - 1,
        a = (e >> 9 & 127) + 1980,
        o = 0,
        s = (t & 31) * 2,
        c = t >> 5 & 63,
        l = t >> 11 & 31;
      if (n == null || n === `local`) return new Date(a, i, r, l, c, s, o);
      if (n === `UTC`) return new Date(Date.UTC(a, i, r, l, c, s, o));
      throw Error(`unrecognized options.timezone: ` + options.timezone)
    }

    function y(e, t, n, r) {
      for (var a = null, o = 0; o < n.length; o++) {
        var s = n[o];
        if (s.id === 28789) {
          if (s.data.length < 6 || s.data.readUInt8(0) !== 1) continue;
          var c = s.data.readUInt32LE(1);
          if (i.unsigned(t) !== c) continue;
          a = D(s.data.subarray(5), !0);
          break
        }
      }
      return a ??= D(t, (e & 2048) != 0), r || (a = a.replace(/\\/g, `/`)), a
    }

    function b(e) {
      return e.indexOf(`\\`) === -1 ? /^[a-zA-Z]:/.test(e) || /^\//.test(e) ? `absolute path: ` + e : e.split(`/`).indexOf(`..`) === -1 ? null : `invalid relative path: ` + e : `invalid characters in fileName: ` + e
    }

    function x(e) {
      for (var t = [], n = 0; n < e.length - 3;) {
        var r = e.readUInt16LE(n + 0),
          i = e.readUInt16LE(n + 2),
          a = n + 4,
          o = a + i;
        if (o > e.length) throw Error(`extra field length exceeds extra field buffer size`);
        var s = e.subarray(a, o);
        t.push({
          id: r,
          data: s
        }), n = o
      }
      return t
    }

    function S(e, t, n, r, i, a) {
      if (r === 0) return setImmediate(function() {
        a(null, k(0))
      });
      e.read(t, n, r, i, function(e, t) {
        if (e) return a(e);
        if (t < r) return a(Error(`unexpected EOF`));
        a()
      })
    }
    a.inherits(C, s);

    function C(e) {
      s.call(this), this.actualByteCount = 0, this.expectedByteCount = e
    }
    C.prototype._transform = function(e, t, n) {
      if (this.actualByteCount += e.length, this.actualByteCount > this.expectedByteCount) {
        var r = `too many bytes in the stream. expected ` + this.expectedByteCount + `. got at least ` + this.actualByteCount;
        return n(Error(r))
      }
      n(null, e)
    }, C.prototype._flush = function(e) {
      if (this.actualByteCount < this.expectedByteCount) {
        var t = `not enough bytes in the stream. expected ` + this.expectedByteCount + `. got only ` + this.actualByteCount;
        return e(Error(t))
      }
      e()
    }, a.inherits(w, o);

    function w() {
      o.call(this), this.refCount = 0
    }
    w.prototype.ref = function() {
      this.refCount += 1
    }, w.prototype.unref = function() {
      var e = this;
      if (--e.refCount, e.refCount > 0) return;
      if (e.refCount < 0) throw Error(`invalid unref`);
      e.close(t);

      function t(t) {
        if (t) return e.emit(`error`, t);
        e.emit(`close`)
      }
    }, w.prototype.createReadStream = function(e) {
      e ??= {};
      var t = e.start,
        n = e.end;
      if (t === n) {
        var r = new c;
        return setImmediate(function() {
          r.end()
        }), r
      }
      var i = this._readStreamForRange(t, n),
        a = !1,
        o = new T(this);
      i.on(`error`, function(e) {
        setImmediate(function() {
          a || o.emit(`error`, e)
        })
      }), A(o, function() {
        i.unpipe(o), o.unref(), i.destroy()
      });
      var s = new C(n - t);
      return o.on(`error`, function(e) {
        setImmediate(function() {
          a || s.emit(`error`, e)
        })
      }), A(s, function() {
        a = !0, o.unpipe(s), o.destroy()
      }), i.pipe(o).pipe(s)
    }, w.prototype._readStreamForRange = function(e, t) {
      throw Error(`not implemented`)
    }, w.prototype.read = function(e, t, n, r, i) {
      var a = this.createReadStream({
          start: r,
          end: r + n
        }),
        o = new l,
        s = 0;
      o._write = function(n, r, i) {
        n.copy(e, t + s, 0, n.length), s += n.length, i()
      }, o.on(`finish`, i), a.on(`error`, function(e) {
        i(e)
      }), a.pipe(o)
    }, w.prototype.close = function(e) {
      setImmediate(e)
    }, a.inherits(T, c);

    function T(e) {
      c.call(this), this.context = e, this.context.ref(), this.unreffedYet = !1
    }
    T.prototype._flush = function(e) {
      this.unref(), e()
    }, T.prototype.unref = function(e) {
      this.unreffedYet || (this.unreffedYet = !0, this.context.unref())
    };
    var E = `\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñÑªº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;

    function D(e, t) {
      if (t) return e.toString(`utf8`);
      for (var n = ``, r = 0; r < e.length; r++) n += E[e[r]];
      return n
    }

    function O(e, t) {
      var n = e.readUInt32LE(t);
      return e.readUInt32LE(t + 4) * 4294967296 + n
    }
    var k = typeof Buffer.allocUnsafe == `function` ? function(e) {
      return Buffer.allocUnsafe(e)
    } : function(e) {
      return new Buffer(e)
    };

    function A(e, t) {
      typeof e.destroy == `function` ? e._destroy = function(e, n) {
        t(), n?.(e)
      } : e.destroy = t
    }

    function j(e) {
      if (e) throw e
    }
  })),
  I = e.n(F(), 1),
  ee = class extends v {
    constructor(e, t, n) {
      super(), this.config = e, this.manifest = t, this.loader = n
    }
    async getJava() {
      let e = await new j(this.config).getFiles(this.manifest);
      return this.config.java.install === `auto` ? {
        java: e,
        files: e
      } : {
        java: [],
        files: e
      }
    }
    async getModpack() {
      let e = y.sanitizeSlug(this.config.storage === `shared` && this.config.slug ? this.config.slug : ``),
        t = r.default.join(this.config.root, e).replaceAll(`\\`, `/`);
      if ((0, s.existsSync)(t) || await f.default.mkdir(t, {
          recursive: !0
        }), !this.config.url && !this.config.minecraft.modpackUrl) return {
        modpack: [],
        files: []
      };
      try {
        let e = this.config.url ? `${this.config.url}/api/files-updater/${this.config.slug??``}` : this.config.minecraft.modpackUrl,
          t = await fetch(e);
        if (!t.ok) {
          let e = await t.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch modpack files: HTTP ${t.status} ${e}`)
        }
        let n = await t.json(),
          r = this.mapFiles(n.files);
        return {
          modpack: r,
          files: r
        }
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Failed to fetch modpack files: ${e instanceof Error?e.message:e}`)
      }
    }
    async getLibraries() {
      let e = [],
        t = [];
      return (0, s.existsSync)(r.default.join(this.config.root, `versions`, this.manifest.id)) || await f.default.mkdir(r.default.join(this.config.root, `versions`, this.manifest.id), {
        recursive: !0
      }), e.push({
        name: `${this.manifest.id}.json`,
        path: r.default.join(`versions`, this.manifest.id, `/`),
        url: ``,
        type: `OTHER`
      }), await f.default.writeFile(r.default.join(this.config.root, `versions`, this.manifest.id, `${this.manifest.id}.json`), JSON.stringify(this.manifest, null, 2)), this.manifest.libraries.forEach(e => {
        let n, i;
        if (e.natives) {
          n = `NATIVE`;
          let t = e.downloads.classifiers,
            r = e.natives[y.getOS_MCCode()];
          if (!r) return;
          i = t ? t[r.replace("${arch}", y.getArch())] : void 0
        } else {
          if (!y.isLibAllowed(e)) return;
          n = `LIBRARY`, i = e.downloads.artifact
        }
        let a, o;
        i && (i.path ? (a = r.default.basename(i.path), o = r.default.join(`libraries`, r.default.dirname(i.path), `/`)) : (a = y.getLibraryName(e.name), o = y.getLibraryPath(e.name, `libraries`)), t.push({
          name: a,
          path: o,
          url: i.url,
          sha1: i.sha1,
          size: i.size,
          type: n,
          extra: `MINECRAFT`
        }))
      }), t.push({
        name: `${this.manifest.id}.jar`,
        path: r.default.join(`versions`, this.manifest.id, `/`),
        url: this.manifest.downloads.client.url,
        sha1: this.manifest.downloads.client.sha1,
        size: this.manifest.downloads.client.size,
        type: `LIBRARY`,
        extra: `MINECRAFT`
      }), this.loader.file && t.push({
        ...this.loader.file,
        extra: `LOADER`
      }), e.push(...t), {
        libraries: t,
        files: e
      }
    }
    async getAssets() {
      try {
        let e = [],
          t = [],
          n = await fetch(this.manifest.assetIndex.url);
        if (!n.ok) {
          let e = await n.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch assets index: HTTP ${n.status} ${e}`)
        }
        let i = await n.json();
        return (0, s.existsSync)(r.default.join(this.config.root, `assets`, `indexes`)) || await f.default.mkdir(r.default.join(this.config.root, `assets`, `indexes`), {
          recursive: !0
        }), e.push({
          name: `${this.manifest.assets}.json`,
          path: r.default.join(`assets`, `indexes`, `/`),
          url: ``,
          type: `OTHER`
        }), await f.default.writeFile(r.default.join(this.config.root, `assets`, `indexes`, `${this.manifest.assets}.json`), JSON.stringify(i, null, 2)), Object.values(i.objects).forEach(e => {
          t.push({
            name: e.hash,
            path: r.default.join(`assets`, `objects`, e.hash.substring(0, 2), `/`),
            url: `https://resources.download.minecraft.net/${e.hash.substring(0,2)}/${e.hash}`,
            sha1: e.hash,
            size: e.size,
            type: `ASSET`
          })
        }), e.push(...t), {
          assets: t,
          files: e
        }
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Failed to fetch assets index: ${e instanceof Error?e.message:e}`)
      }
    }
    async getInjector() {
      if (this.config.account.meta.type !== `yggdrasil`) return {
        injector: [],
        files: []
      };
      let e = `https://github.com/yushijinhun/authlib-injector/releases/download/v1.2.7/authlib-injector-1.2.7.jar`,
        t = [{
          name: `authlib-injector.jar`,
          path: `libraries/`,
          url: e,
          sha1: ``,
          size: await y.getRemoteFileSize(e, `Failed to get authlib-injector file size`),
          type: `LIBRARY`
        }];
      return {
        injector: t,
        files: t
      }
    }
    async getLog4j() {
      let e = [];
      return +this.manifest.id.split(`.`)[1] <= 16 && +this.manifest.id.split(`.`)[1] >= 12 ? e.push({
        name: `log4j2_112-116.xml`,
        path: ``,
        url: `https://launcher.mojang.com/v1/objects/02937d122c86ce73319ef9975b58896fc1b491d1/log4j2_112-116.xml`,
        sha1: `02937d122c86ce73319ef9975b58896fc1b491d1`,
        size: 4096,
        type: `CONFIG`
      }) : +this.manifest.id.split(`.`)[1] <= 11 && +this.manifest.id.split(`.`)[1] >= 7 && e.push({
        name: `log4j2_17-111.xml`,
        path: ``,
        url: `https://launcher.mojang.com/v1/objects/4bb89a97a66f350bc9f73b3ca8509632682aea2e/log4j2_17-111.xml`,
        sha1: `4bb89a97a66f350bc9f73b3ca8509632682aea2e`,
        size: 4096,
        type: `CONFIG`
      }), {
        log4j: e,
        files: e
      }
    }
    async extractNatives(e) {
      let t = e.filter(e => e.type === `NATIVE`),
        n = r.default.resolve(this.config.root, `bin`, this.manifest.id),
        i = [];
      (0, s.existsSync)(n) || await f.default.mkdir(n, {
        recursive: !0
      });
      q.default.log(`[extractNatives] Processing ${t.length} native files`);
      let a = t.map(e => new Promise((t, a) => {
        let o = r.default.join(this.config.root, e.path, e.name);
        if (!(0, s.existsSync)(o)) return q.default.log(`[extractNatives] Skipping (not found): ${e.name}`), t();
        let l = setTimeout(() => a(new Error(`Native extraction timeout for ${e.name}`)), 120000);
        q.default.log(`[extractNatives] Opening: ${e.name}`);
        I.open(o, {
          lazyEntries: !0
        }, (o, c) => {
          if (o || !c) return clearTimeout(l), q.default.log(`[extractNatives] Failed to open: ${e.name}`), a(new h(g.FILE_ERROR, `Failed to open ${e.name}`));
          let _n = 0,
            _re = () => { _n++, clearTimeout(l), l = setTimeout(() => a(new Error(`Native extraction timeout for ${e.name}`)), 120000), c.readEntry() };
          _re(), c.on(`entry`, e => {
            if (e.fileName.startsWith(`META-INF`)) return _re();
            let t = e.fileName.replace(/\\/g, `/`).replace(/^\/+/, ``),
              o = r.default.resolve(n, t),
              _l = r.default.relative(n, o);
            if (!(_l && !_l.startsWith(`..`) && !r.default.isAbsolute(_l)) || !t) return q.default.log(`[extractNatives] Unsafe entry skipped: ${e.fileName}`), _re();
            let u = {
              name: r.default.basename(t),
              path: r.default.join(`bin`, this.manifest.id, r.default.dirname(t), `/`),
              url: ``,
              sha1: ``,
              size: e.uncompressedSize
            };
            q.default.log(`[extractNatives] ${e.name}: entry ${_n} - ${e.fileName}`);
            e.fileName.endsWith(`/`) ? (i.push({
              ...u,
              type: `FOLDER`
            }), f.default.mkdir(o, {
              recursive: !0
            }).then(() => _re()).catch(a)) : f.default.mkdir(r.default.dirname(o), {
              recursive: !0
            }).then(() => {
              c.openReadStream(e, (t, n) => {
                if (t || !n) return a(new h(g.FILE_ERROR, `Failed to open read stream for ${e.fileName}`));
                let r = (0, s.createWriteStream)(o);
                n.pipe(r), r.on(`close`, () => {
                  i.push({
                    ...u,
                    type: `NATIVE`
                  }), _re()
                }), r.on(`error`, a), n.on(`error`, a)
              })
            }).catch(a)
          }), c.on(`end`, () => {
            clearTimeout(l), q.default.log(`[extractNatives] Done extracting: ${e.name} (${_n} entries)`), this.emit(`extract_progress`, {
              filename: e.name
            }), t()
          }), c.on(`error`, e => {
            clearTimeout(l), q.default.log(`[extractNatives] Error for ${e.name}: ${e.message}`), a(e)
          })
        })
      }));
      return await Promise.all(a), q.default.log(`[extractNatives] All done: ${i.length} files extracted`), this.emit(`extract_end`, {
        amount: i.length
      }), {
        files: i
      }
      return await Promise.all(a), this.emit(`extract_end`, {
        amount: i.length
      }), {
        files: i
      }
    }
    async copyAssets() {
      let e = [];
      if (this.manifest.assets === `legacy` || this.manifest.assets === `pre-1.6`) {
        (0, s.existsSync)(r.default.join(this.config.root, `assets`, `legacy`)) && this.emit(`copy_debug`, `The 'assets/legacy' directory is no longer used. You can safely remove it from your server's root directory.`);
        let t = await f.default.readFile(r.default.join(this.config.root, `assets`, `indexes`, `${this.manifest.assets}.json`), `utf-8`),
          n = JSON.parse(t),
          i = Object.entries(n.objects).map(async ([t, {
            hash: n,
            size: i
          }]) => {
            let a = r.default.join(`resources`, r.default.dirname(t)),
              o = r.default.basename(t);
            (0, s.existsSync)(r.default.join(this.config.root, a)) || await f.default.mkdir(r.default.join(this.config.root, a), {
              recursive: !0
            }), (0, s.existsSync)(r.default.join(this.config.root, a, o)) || await f.default.copyFile(r.default.join(this.config.root, `assets`, `objects`, n.substring(0, 2), n), r.default.join(this.config.root, a, o)), e.push({
              name: o,
              path: a,
              url: ``,
              sha1: n,
              size: i,
              type: `ASSET`
            }), this.emit(`copy_progress`, {
              filename: n,
              dest: r.default.join(a, o)
            })
          });
        await Promise.all(i)
      }
      return this.emit(`copy_end`, {
        amount: e.length
      }), {
        files: e
      }
    }
    mapFiles(e) {
      let t = y.sanitizeSlug(this.config.slug ?? ``);
      return this.config.storage === `shared` ? e.map(e => ({
        ...e,
        path: r.default.join(t, e.path)
      })) : e
    }
  },
  L = class extends v {
    constructor(e) {
      super(), this.dest = ``, this.dest = r.default.join(e)
    }
    async clean(e, t = [], n = !1) {
      if (n) return;
      let i = new Set(e.map(e => r.default.resolve(`/`, this.dest, e.path, e.name).replace(/\\/g, `/`))),
        a = t.map(e => r.default.resolve(this.dest, e)),
        o = [],
        s = 0,
        c = [];
      await this.browse(this.dest, c);
      for (let e of c) {
        let t = r.default.resolve(`/`, e.path, e.name).replace(/\\/g, `/`),
          n = i.has(t),
          c = a.some(e => t.startsWith(e));
        !n && !c && o.push(f.default.unlink(t).then(() => {
          s++, this.emit(`clean_progress`, {
            filename: e.name
          })
        }).catch(t => {
          this.emit(`clean_error`, {
            filename: e.name,
            message: t
          })
        }))
      }
      await Promise.all(o), this.emit(`clean_end`, {
        amount: s
      })
    }
    async browse(e, t = []) {
      if (!(0, s.existsSync)(e)) return;
      let n = (await f.default.readdir(e)).map(async n => {
        let i = r.default.join(e, n);
        (await f.default.stat(i)).isDirectory() ? await this.browse(i, t) : t.push({
          name: n,
          path: `${e}/`.split(`\\`).join(`/`).replace(/^\/+/, ``)
        })
      });
      await Promise.all(n)
    }
  },
  R = class extends v {
    constructor(e, t, n, r) {
      super(), this.config = e, this.manifest = t, this.loader = n, this.installProfile = r
    }
    async patch() {
      let e = await this.isPatched(),
        t = 0;
      if (e.patched) return this.emit(`patch_end`, {
        amount: t
      }), e.files;
      if (!this.installProfile.processors || this.installProfile.processors.length === 0) return this.emit(`patch_end`, {
        amount: 0
      }), e.files;
      let n = this.installProfile.processors;
      for (let e of n) {
        if (e?.sides && !e.sides.includes(`client`)) continue;
        let n = r.default.join(this.config.root, `libraries`, y.getLibraryPath(e.jar), y.getLibraryName(e.jar)),
          i = e.args.map(e => this.mapPath(this.mapArg(e))),
          a = e.classpath.map(e => `"${r.default.join(this.config.root,`libraries`,y.getLibraryPath(e),y.getLibraryName(e))}"`),
          o = await this.getJarMain(n);
        if (!o) {
          console.warn(`[Patcher] Could not find Main-Class for processor ${e.jar}`);
          continue
        }
        await new Promise(s => {
          let c = (0, m.spawn)(`"${this.config.java.absolutePath.replace("${X}",this.manifest.javaVersion?.majorVersion+`
            `||`
            8`)}"`, [`-Xmx2G`, `-classpath`, [`"${n}"`, ...a].join(r.default.delimiter), o, ...i], {
              shell: !0
            });
          c.stdout.on(`data`, e => this.emit(`patch_debug`, e.toString(`utf8`).replace(/\n$/, ``))), c.stderr.on(`data`, e => this.emit(`patch_debug`, e.toString(`utf8`).replace(/\n$/, ``))), c.on(`close`, n => {
            this.emit(`patch_progress`, {
              filename: y.getLibraryName(e.jar)
            }), t++, s(n)
          })
        })
      }
      let i = await this.isPatched();
      return this.emit(`patch_end`, {
        amount: t
      }), i.files
    }
    async isPatched() {
      let e = this.installProfile.processors,
        t = [];
      e?.forEach(e => {
        e?.sides && !e.sides.includes(`client`) || e.args.forEach(e => {
          if (e = e.replace(/[{}]/g, ``), this.installProfile.data[e]) {
            if (e === `BINPATCH`) return;
            let n = this.installProfile.data[e],
              r = n.client ?? n.path ?? (typeof n == `string` ? n : null);
            r && t.push(r)
          }
        })
      }), t = [...new Set(t)];
      let n = t.map(async e => {
          let t = e.replace(`[`, ``).replace(`]`, ``),
            n = y.getLibraryName(t),
            i = y.getLibraryPath(t),
            a = r.default.join(this.config.root, `libraries`, i),
            o = {
              name: n,
              path: r.default.join(`libraries`, i),
              url: ``,
              type: `LIBRARY`
            };
          try {
            return await f.default.access(r.default.join(a, n)), {
              patched: !0,
              file: o
            }
          } catch {
            return {
              patched: !1,
              file: o
            }
          }
        }),
        i = await Promise.all(n);
      return {
        patched: i.length > 0 && i.every(e => e.patched),
        files: i.map(e => e.file)
      }
    }
    async getJarMain(e) {
      return new Promise(t => {
        if (!(0, s.existsSync)(e)) return t(null);
        let n = setTimeout(() => t(null), 60000);
        I.open(e, {
          lazyEntries: !0
        }, (e, r) => {
          if (e || !r) return clearTimeout(n), t(null);
          r.readEntry(), r.on(`entry`, e => {
            e.fileName === `META-INF/MANIFEST.MF` ? r.openReadStream(e, (e, i) => {
              if (e || !i) return r.close(), clearTimeout(n), t(null);
              let a = ``;
              i.on(`data`, e => a += e.toString(`utf8`)), i.on(`end`, () => {
                clearTimeout(n), r.close();
                try {
                  t(a.split(`Main-Class: `)[1].split(/\r?\n/)[0].trim())
                } catch {
                  t(null)
                }
              })
            }) : r.readEntry()
          }), r.on(`end`, () => (clearTimeout(n), t(null))), r.on(`error`, () => (clearTimeout(n), t(null)))
        })
      })
    }
    mapArg(e) {
      let t = e.replace(/[{}]/g, ``),
        n = this.installProfile.libraries.find(e => {
          if (this.loader.type === `FORGE`) return e.name.startsWith(`net.minecraftforge:forge`);
          if (this.loader.type === `NEOFORGE`) return e.name.startsWith(`net.neoforged:neoforge`)
        });
      if (this.installProfile.data[t]) {
        if (t === `BINPATCH`) {
          let e = y.getLibraryName(this.installProfile.path ?? n.name).replace(/\.jar$/, `-clientdata.lzma`),
            t = y.getLibraryPath(this.installProfile.path ?? n.name, this.config.root, `libraries`);
          return `"${r.default.join(t,e)}"`
        }
        let i = this.installProfile.data[t];
        return i.client ?? i.path ?? (typeof i == `string` ? i : e)
      }
      return e.replace(`{SIDE}`, `client`).replace(/{ROOT}(.*?)/, `"${this.config.root}$1"`).replace(`{MINECRAFT_JAR}`, `"${r.default.join(this.config.root,`versions`,this.manifest.id,`${this.manifest.id}.jar`)}"`).replace(`{MINECRAFT_VERSION}`, `"${r.default.join(this.config.root,`versions`,this.manifest.id,`${this.manifest.id}.json`)}"`).replace(`{INSTALLER}`, `"${r.default.join(this.config.root,`libraries`)}"`).replace(`{LIBRARY_DIR}`, `"${r.default.join(this.config.root,`libraries`)}"`)
    }
    mapPath(e) {
      return e.startsWith(`[`) ? `"${r.default.join(this.config.root,`libraries`,y.getLibraryPath(e.replace(/[\[\]]/g,``)),y.getLibraryName(e.replace(/[\[\]]/g,``)))}"` : e
    }
  },
  te = e.t(((e, t) => {
    function n(e) {
      return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, `default`) ? e.default : e
    }
    var r = new Int32Array([0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117]);

    function i(e) {
      if (Buffer.isBuffer(e)) return e;
      if (typeof e == `number`) return Buffer.alloc(e);
      if (typeof e == `string`) return Buffer.from(e);
      throw Error(`input must be buffer, number, or string, received ` + typeof e)
    }

    function a(e) {
      let t = i(4);
      return t.writeInt32BE(e, 0), t
    }

    function o(e, t) {
      e = i(e), Buffer.isBuffer(t) && (t = t.readUInt32BE(0));
      let n = ~~t ^ -1;
      for (var a = 0; a < e.length; a++) n = r[(n ^ e[a]) & 255] ^ n >>> 8;
      return n ^ -1
    }

    function s() {
      return a(o.apply(null, arguments))
    }
    s.signed = function() {
      return o.apply(null, arguments)
    }, s.unsigned = function() {
      return o.apply(null, arguments) >>> 0
    }, t.exports = n(s)
  })),
  z = e.t((e => {
    var t = require(`fs`),
      n = require(`stream`).Transform,
      r = require(`stream`).PassThrough,
      i = require(`zlib`),
      a = require(`util`),
      o = require(`events`).EventEmitter,
      s = require(`events`).errorMonitor,
      c = te();
    e.ZipFile = l, a.inherits(l, o);

    function l() {
      this.outputStream = new r, this.entries = [], this.outputStreamCursor = 0, this.ended = !1, this.allDone = !1, this.forceZip64Eocd = !1, this.errored = !1, this.on(s, function() {
        this.errored = !0
      })
    }
    l.prototype.addFile = function(e, n, r) {
      var i = this;
      if (n = x(n, !1), r ??= {}, !g(i)) {
        var a = new C(n, !1, r);
        i.entries.push(a), t.stat(e, function(n, o) {
          if (n) return i.emit(`error`, n);
          if (!o.isFile()) return i.emit(`error`, Error(`not a file: ` + e));
          a.uncompressedSize = o.size, r.mtime ?? a.setLastModDate(o.mtime), r.mode ?? a.setFileAttributesMode(o.mode), a.setFileDataPumpFunction(function() {
            var n = t.createReadStream(e);
            a.state = C.FILE_DATA_IN_PROGRESS, n.on(`error`, function(e) {
              i.emit(`error`, e)
            }), f(i, a, n)
          }), m(i)
        })
      }
    }, l.prototype.addReadStream = function(e, t, n) {
      this.addReadStreamLazy(t, n, function(t) {
        t(null, e)
      })
    }, l.prototype.addReadStreamLazy = function(e, t, n) {
      var r = this;
      if (typeof t == `function` && (n = t, t = null), t ??= {}, e = x(e, !1), !g(r)) {
        var i = new C(e, !1, t);
        r.entries.push(i), i.setFileDataPumpFunction(function() {
          i.state = C.FILE_DATA_IN_PROGRESS, n(function(e, t) {
            if (e) return r.emit(`error`, e);
            f(r, i, t)
          })
        }), m(r)
      }
    }, l.prototype.addBuffer = function(e, t, n) {
      var r = this;
      if (t = x(t, !1), e.length > 1073741823) throw Error(`buffer too large: ` + e.length + ` > 1073741823`);
      if (n ??= {}, n.size != null) throw Error(`options.size not allowed`);
      if (g(r)) return;
      var a = new C(t, !1, n);
      a.uncompressedSize = e.length, a.crc32 = c.unsigned(e), a.crcAndFileSizeKnown = !0, r.entries.push(a), a.compressionLevel === 0 ? o(e) : i.deflateRaw(e, {
        level: a.compressionLevel
      }, function(e, t) {
        o(t)
      });

      function o(e) {
        a.compressedSize = e.length, a.setFileDataPumpFunction(function() {
          d(r, e), d(r, a.getDataDescriptor()), a.state = C.FILE_DATA_DONE, setImmediate(function() {
            m(r)
          })
        }), m(r)
      }
    }, l.prototype.addEmptyDirectory = function(e, t) {
      var n = this;
      if (e = x(e, !0), t ??= {}, t.size != null) throw Error(`options.size not allowed`);
      if (t.compress != null) throw Error(`options.compress not allowed`);
      if (t.compressionLevel != null) throw Error(`options.compressionLevel not allowed`);
      if (!g(n)) {
        var r = new C(e, !0, t);
        n.entries.push(r), r.setFileDataPumpFunction(function() {
          d(n, r.getDataDescriptor()), r.state = C.FILE_DATA_DONE, m(n)
        }), m(n)
      }
    };
    var u = U([80, 75, 5, 6]);
    l.prototype.end = function(e, t) {
      if (typeof e == `function` && (t = e, e = null), e ??= {}, !this.ended && (this.ended = !0, !this.errored)) {
        if (this.calculatedTotalSizeCallback = t, this.forceZip64Eocd = !!e.forceZip64Format, e.comment) {
          if (typeof e.comment == `string` ? this.comment = ne(e.comment) : this.comment = e.comment, this.comment.length > 65535) throw Error(`comment is too large`);
          if (W(this.comment, u)) throw Error(`comment contains end of central directory record signature`)
        } else this.comment = S;
        m(this)
      }
    };

    function d(e, t) {
      e.outputStream.write(t), e.outputStreamCursor += t.length
    }

    function f(e, t, n) {
      var a = new z,
        o = new R,
        s = t.compressionLevel === 0 ? new r : new i.DeflateRaw({
          level: t.compressionLevel
        }),
        c = new R;
      n.pipe(a).pipe(o).pipe(s).pipe(c).pipe(e.outputStream, {
        end: !1
      }), c.on(`end`, function() {
        if (t.crc32 = a.crc32, t.uncompressedSize == null) t.uncompressedSize = o.byteCount;
        else if (t.uncompressedSize !== o.byteCount) return e.emit(`error`, Error(`file data stream has unexpected number of bytes`));
        t.compressedSize = c.byteCount, e.outputStreamCursor += t.compressedSize, d(e, t.getDataDescriptor()), t.state = C.FILE_DATA_DONE, m(e)
      })
    }

    function p(e) {
      if (e.compress != null && e.compressionLevel != null && !!e.compress != !!e.compressionLevel) throw Error(`conflicting settings for compress and compressionLevel`);
      return e.compressionLevel == null ? e.compress === !1 ? 0 : 6 : e.compressionLevel
    }

    function m(e) {
      if (e.allDone || e.errored) return;
      if (e.ended && e.calculatedTotalSizeCallback != null) {
        var t = h(e);
        t != null && (e.calculatedTotalSizeCallback(t), e.calculatedTotalSizeCallback = null)
      }
      var n = r();

      function r() {
        for (var t = 0; t < e.entries.length; t++) {
          var n = e.entries[t];
          if (n.state < C.FILE_DATA_DONE) return n
        }
        return null
      }
      if (n != null) {
        if (n.state < C.READY_TO_PUMP_FILE_DATA || n.state === C.FILE_DATA_IN_PROGRESS) return;
        n.relativeOffsetOfLocalHeader = e.outputStreamCursor, d(e, n.getLocalFileHeader()), n.doFileDataPump()
      } else e.ended && (e.offsetOfStartOfCentralDirectory = e.outputStreamCursor, e.entries.forEach(function(t) {
        d(e, t.getCentralDirectoryRecord())
      }), d(e, b(e)), e.outputStream.end(), e.allDone = !0)
    }

    function h(e) {
      for (var t = 0, n = 0, r = 0; r < e.entries.length; r++) {
        var i = e.entries[r];
        if (i.compressionLevel !== 0) return -1;
        if (i.state >= C.READY_TO_PUMP_FILE_DATA) {
          if (i.uncompressedSize == null) return -1
        } else if (i.uncompressedSize == null) return null;
        i.relativeOffsetOfLocalHeader = t;
        var a = i.useZip64Format();
        t += w + i.utf8FileName.length, t += i.uncompressedSize, i.crcAndFileSizeKnown || (a ? t += j : t += A), n += M + i.utf8FileName.length + i.fileComment.length, i.forceDosTimestamp || (n += N), a && (n += P)
      }
      var o = 0;
      return (e.forceZip64Eocd || e.entries.length >= 65535 || n >= 65535 || t >= 4294967295) && (o += _ + v), o += y + e.comment.length, t + n + o
    }

    function g(e) {
      if (e.ended) throw Error(`cannot add entries after calling end()`);
      return !!e.errored
    }
    var _ = 56,
      v = 20,
      y = 22;

    function b(e, t) {
      var n = !1,
        r = e.entries.length;
      (e.forceZip64Eocd || e.entries.length >= 65535) && (r = 65535, n = !0);
      var i = e.outputStreamCursor - e.offsetOfStartOfCentralDirectory,
        a = i;
      (e.forceZip64Eocd || i >= 4294967295) && (a = 4294967295, n = !0);
      var o = e.offsetOfStartOfCentralDirectory;
      if ((e.forceZip64Eocd || e.offsetOfStartOfCentralDirectory >= 4294967295) && (o = 4294967295, n = !0), t) return n ? _ + v + y : y;
      var s = H(y + e.comment.length);
      if (s.writeUInt32LE(101010256, 0), s.writeUInt16LE(0, 4), s.writeUInt16LE(0, 6), s.writeUInt16LE(r, 8), s.writeUInt16LE(r, 10), s.writeUInt32LE(a, 12), s.writeUInt32LE(o, 16), s.writeUInt16LE(e.comment.length, 20), e.comment.copy(s, 22), !n) return s;
      var c = H(_);
      c.writeUInt32LE(101075792, 0), L(c, _ - 12, 4), c.writeUInt16LE(D, 12), c.writeUInt16LE(E, 14), c.writeUInt32LE(0, 16), c.writeUInt32LE(0, 20), L(c, e.entries.length, 24), L(c, e.entries.length, 32), L(c, i, 40), L(c, e.offsetOfStartOfCentralDirectory, 48);
      var l = H(v);
      return l.writeUInt32LE(117853008, 0), l.writeUInt32LE(0, 4), L(l, e.outputStreamCursor, 8), l.writeUInt32LE(1, 16), Buffer.concat([c, l, s])
    }

    function x(e, t) {
      if (e === ``) throw Error(`empty metadataPath`);
      if (e = e.replace(/\\/g, `/`), /^[a-zA-Z]:/.test(e) || /^\//.test(e)) throw Error(`absolute path: ` + e);
      if (e.split(`/`).indexOf(`..`) !== -1) throw Error(`invalid relative path: ` + e);
      var n = /\/$/.test(e);
      if (t) n || (e += `/`);
      else if (n) throw Error(`file path cannot end with '/': ` + e);
      return e
    }
    var S = H(0);

    function C(e, t, n) {
      if (this.utf8FileName = U(e), this.utf8FileName.length > 65535) throw Error(`utf8 file name too long. ` + utf8FileName.length + ` > 65535`);
      if (this.isDirectory = t, this.state = C.WAITING_FOR_METADATA, this.setLastModDate(n.mtime == null ? new Date : n.mtime), this.forceDosTimestamp = !!n.forceDosTimestamp, n.mode == null ? this.setFileAttributesMode(t ? 16893 : 33204) : this.setFileAttributesMode(n.mode), t ? (this.crcAndFileSizeKnown = !0, this.crc32 = 0, this.uncompressedSize = 0, this.compressedSize = 0) : (this.crcAndFileSizeKnown = !1, this.crc32 = null, this.uncompressedSize = null, this.compressedSize = null, n.size != null && (this.uncompressedSize = n.size)), t ? this.compressionLevel = 0 : this.compressionLevel = p(n), this.forceZip64Format = !!n.forceZip64Format, n.fileComment) {
        if (typeof n.fileComment == `string` ? this.fileComment = U(n.fileComment, `utf-8`) : this.fileComment = n.fileComment, this.fileComment.length > 65535) throw Error(`fileComment is too large`)
      } else this.fileComment = S
    }
    C.WAITING_FOR_METADATA = 0, C.READY_TO_PUMP_FILE_DATA = 1, C.FILE_DATA_IN_PROGRESS = 2, C.FILE_DATA_DONE = 3, C.prototype.setLastModDate = function(e) {
      this.mtime = e;
      var t = ee(e);
      this.lastModFileTime = t.time, this.lastModFileDate = t.date
    }, C.prototype.setFileAttributesMode = function(e) {
      if ((e & 65535) !== e) throw Error(`invalid mode. expected: 0 <= ` + e + ` <= 65535`);
      this.externalFileAttributes = e << 16 >>> 0
    }, C.prototype.setFileDataPumpFunction = function(e) {
      this.doFileDataPump = e, this.state = C.READY_TO_PUMP_FILE_DATA
    }, C.prototype.useZip64Format = function() {
      return this.forceZip64Format || this.uncompressedSize != null && this.uncompressedSize > 4294967294 || this.compressedSize != null && this.compressedSize > 4294967294 || this.relativeOffsetOfLocalHeader != null && this.relativeOffsetOfLocalHeader > 4294967294
    };
    var w = 30,
      T = 20,
      E = 45,
      D = 831,
      O = 2048,
      k = 8;
    C.prototype.getLocalFileHeader = function() {
      var e = 0,
        t = 0,
        n = 0;
      this.crcAndFileSizeKnown && (e = this.crc32, t = this.compressedSize, n = this.uncompressedSize);
      var r = H(w),
        i = O;
      return this.crcAndFileSizeKnown || (i |= k), r.writeUInt32LE(67324752, 0), r.writeUInt16LE(T, 4), r.writeUInt16LE(i, 6), r.writeUInt16LE(this.getCompressionMethod(), 8), r.writeUInt16LE(this.lastModFileTime, 10), r.writeUInt16LE(this.lastModFileDate, 12), r.writeUInt32LE(e, 14), r.writeUInt32LE(t, 18), r.writeUInt32LE(n, 22), r.writeUInt16LE(this.utf8FileName.length, 26), r.writeUInt16LE(0, 28), Buffer.concat([r, this.utf8FileName])
    };
    var A = 16,
      j = 24;
    C.prototype.getDataDescriptor = function() {
      if (this.crcAndFileSizeKnown) return S;
      if (this.useZip64Format()) {
        var e = H(j);
        return e.writeUInt32LE(134695760, 0), e.writeUInt32LE(this.crc32, 4), L(e, this.compressedSize, 8), L(e, this.uncompressedSize, 16), e
      } else {
        var e = H(A);
        return e.writeUInt32LE(134695760, 0), e.writeUInt32LE(this.crc32, 4), e.writeUInt32LE(this.compressedSize, 8), e.writeUInt32LE(this.uncompressedSize, 12), e
      }
    };
    var M = 46,
      N = 9,
      P = 28;
    C.prototype.getCentralDirectoryRecord = function() {
      var e = H(M),
        t = O;
      this.crcAndFileSizeKnown || (t |= k);
      var n = S;
      if (!this.forceDosTimestamp) {
        n = H(N), n.writeUInt16LE(21589, 0), n.writeUInt16LE(N - 4, 2), n.writeUInt8(3, 4);
        var r = Math.floor(this.mtime.getTime() / 1e3);
        r < -2147483648 && (r = -2147483648), r > 2147483647 && (r = 2147483647), n.writeUInt32LE(r, 5)
      }
      var i = this.compressedSize,
        a = this.uncompressedSize,
        o = this.relativeOffsetOfLocalHeader,
        s = T,
        c = S;
      return this.useZip64Format() && (i = 4294967295, a = 4294967295, o = 4294967295, s = E, c = H(P), c.writeUInt16LE(1, 0), c.writeUInt16LE(P - 4, 2), L(c, this.uncompressedSize, 4), L(c, this.compressedSize, 12), L(c, this.relativeOffsetOfLocalHeader, 20)), e.writeUInt32LE(33639248, 0), e.writeUInt16LE(D, 4), e.writeUInt16LE(s, 6), e.writeUInt16LE(t, 8), e.writeUInt16LE(this.getCompressionMethod(), 10), e.writeUInt16LE(this.lastModFileTime, 12), e.writeUInt16LE(this.lastModFileDate, 14), e.writeUInt32LE(this.crc32, 16), e.writeUInt32LE(i, 20), e.writeUInt32LE(a, 24), e.writeUInt16LE(this.utf8FileName.length, 28), e.writeUInt16LE(n.length + c.length, 30), e.writeUInt16LE(this.fileComment.length, 32), e.writeUInt16LE(0, 34), e.writeUInt16LE(0, 36), e.writeUInt32LE(this.externalFileAttributes, 38), e.writeUInt32LE(o, 42), Buffer.concat([e, this.utf8FileName, n, c, this.fileComment])
    }, C.prototype.getCompressionMethod = function() {
      return this.compressionLevel === 0 ? 0 : 8
    };
    var F = new Date(1980, 0, 1),
      I = new Date(2107, 11, 31, 23, 59, 58);

    function ee(e) {
      e < F ? e = F : e > I && (e = I);
      var t = 0;
      t |= e.getDate() & 31, t |= (e.getMonth() + 1 & 15) << 5, t |= (e.getFullYear() - 1980 & 127) << 9;
      var n = 0;
      return n |= Math.floor(e.getSeconds() / 2), n |= (e.getMinutes() & 63) << 5, n |= (e.getHours() & 31) << 11, {
        date: t,
        time: n
      }
    }

    function L(e, t, n) {
      var r = Math.floor(t / 4294967296),
        i = t % 4294967296;
      e.writeUInt32LE(i, n), e.writeUInt32LE(r, n + 4)
    }
    a.inherits(R, n);

    function R(e) {
      n.call(this, e), this.byteCount = 0
    }
    R.prototype._transform = function(e, t, n) {
      this.byteCount += e.length, n(null, e)
    }, a.inherits(z, n);

    function z(e) {
      n.call(this, e), this.crc32 = 0
    }
    z.prototype._transform = function(e, t, n) {
      this.crc32 = c.unsigned(e, this.crc32), n(null, e)
    };
    var B = `\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñÑªº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;
    if (B.length !== 256) throw Error(`assertion failure`);
    var V = null;

    function ne(e) {
      if (/^[\x20-\x7e]*$/.test(e)) return U(e, `utf-8`);
      if (V == null) {
        V = {};
        for (var t = 0; t < B.length; t++) V[B[t]] = t
      }
      for (var n = H(e.length), t = 0; t < e.length; t++) {
        var r = V[e[t]];
        if (r == null) throw Error(`character not encodable in CP437: ` + JSON.stringify(e[t]));
        n[t] = r
      }
      return n
    }

    function H(e) {
      H = t;
      try {
        return H(e)
      } catch {
        return H = n, H(e)
      }

      function t(e) {
        return Buffer.allocUnsafe(e)
      }

      function n(e) {
        return new Buffer(e)
      }
    }

    function U(e, t) {
      U = n;
      try {
        return U(e, t)
      } catch {
        return U = r, U(e, t)
      }

      function n(e, t) {
        return Buffer.from(e, t)
      }

      function r(e, t) {
        return new Buffer(e, t)
      }
    }

    function W(e, t) {
      W = n;
      try {
        return W(e, t)
      } catch {
        return W = r, W(e, t)
      }

      function n(e, t) {
        return e.includes(t)
      }

      function r(e, t) {
        for (var n = 0; n <= e.length - t.length; n++)
          for (var r = 0;; r++) {
            if (r === t.length) return !0;
            if (e[n + r] !== t[r]) break
          }
        return !1
      }
    }
  })),
  B = e.n(z(), 1),
  V = class extends v {
    constructor(e, t, n) {
      super(), this.config = e, this.manifest = t, this.loader = n
    }
    async setup() {
      try {
        let e = r.default.join(this.config.root, this.loader.file.path),
          t = r.default.join(this.config.root, `versions`, this.manifest.id);
        (0, s.existsSync)(e) || await f.default.mkdir(e, {
          recursive: !0
        });
        let n = r.default.join(e, this.loader.file.name);
        if ((0, s.existsSync)(n)) {
          let r = await this.validateZip(n);
          if (!r) {
            q.default.log(`[setup] Corrupted zip detected: ${this.loader.file.name}, deleting and requesting re-download`);
            try { await f.default.unlink(n) } catch {}
            throw new h(g.FILE_ERROR, `Corrupted zip`);
          }
        }
        return this.loader.format === `INSTALLER` ? await this.extractJar(e) : await this.extractZip(e, t)
      } catch (e) {
        throw new h(g.FILE_ERROR, `Failed to setup ForgeLike loader: ${e instanceof Error?e.message:e}`)
      }
    }
    async validateZip(e) {
      return new Promise(t => {
        I.open(e, { lazyEntries: !1 }, (n, r) => {
          if (n || !r) return q.default.log(`[validateZip] Invalid: ${e} - ${n?.message}`), t(!1);
          r.close(), t(!0)
        })
      })
    }
    async extractZip(e, t) {
      let n = this.loader.type.toLowerCase(),
        i = r.default.join(e, this.loader.file.name),
        a = r.default.join(t, `${this.manifest.id}.jar`),
        o = r.default.join(t, `${this.manifest.id}-patched.jar`),
        c = [],
        l = 0;
      q.default.log(`[extractZip] Opening minecraft jar: ${a}`);
      let {
          zipfile: u,
          entries: d
        } = await this.openZip(a);
      let {
          zipfile: p,
          entries: m
        } = await this.openZip(i);
      q.default.log(`[extractZip] Opening loader: ${i} (${m.length} entries)`);
      q.default.log(`[extractZip] Merging: ${d.length} minecraft entries + ${m.length} loader entries`);
      try {
        let t = new B.ZipFile,
          i = (0, s.createWriteStream)(o),
          h = new Set(m.map(e => e.fileName)),
          _c = 0;
        t.outputStream.pipe(i);
        q.default.log(`[extractZip] Piping minecraft entries...`);
        for (let e of d) e.fileName.startsWith(`META-INF/`) || e.fileName.endsWith(`/`) || h.has(e.fileName) || (await this.pipeEntryToYazl(u, e, t), _c++);
        q.default.log(`[extractZip] Piping ${m.length} loader entries...`);
        for (let e of m) e.fileName.endsWith(`/`) || (await this.pipeEntryToYazl(p, e, t), l++, _c++, this.emit(`extract_progress`, {
          filename: r.default.basename(e.fileName)
        }));
        q.default.log(`[extractZip] Finalizing merged jar (${_c} total entries)...`);
        t.end(), await new Promise((e, t) => {
          i.on(`close`, e), i.on(`error`, t)
        }), await f.default.unlink(a), await f.default.rename(o, a);
        q.default.log(`[extractZip] Merged jar ready: ${a}`);
        let g = {
          ...this.manifest,
          id: `${n}-${this.loader.loaderVersion}`,
          libraries: []
        };
        return c.push({
          name: `${g.id}.json`,
          path: this.loader.file.path,
          url: ``,
          type: `OTHER`
        }), await f.default.writeFile(r.default.join(e, `${g.id}.json`), JSON.stringify(g, null, 2)), this.emit(`extract_end`, {
          amount: l
        }), {
          loaderManifest: g,
          installProfile: null,
          libraries: [],
          files: c
        }
      } finally {
        u.close(), p.close()
      }
    }
    async extractJar(e) {
      let t = this.loader.type.toLowerCase(),
        n = r.default.join(e, this.loader.file.name),
        i = [],
        a = [],
        o = 0;
      q.default.log(`[extractJar] Opening installer: ${n}`);
      let {
          zipfile: c,
          entries: l
        } = await this.openZip(n);
      q.default.log(`[extractJar] Got ${l.length} entries from zip`);
      try {
        let n = l.find(e => e.fileName === `install_profile.json`);
        if (!n) throw Error(`install_profile.json not found in loader installer`);
        q.default.log(`[extractJar] Reading install_profile.json`);
        let u = await this.readEntryData(c, n),
          d = JSON.parse(u.toString(`utf8`)),
          p;
        q.default.log(`[extractJar] install_profile.json parsed: ${d.install ? `install format` : `json format`}`);
        if (d.install) p = d.versionInfo, d = d.install;
        else {
          let e = r.default.basename(d.json),
            t = l.find(t => t.fileName === e);
          if (!t) throw Error(`${e} not found in loader installer`);
          q.default.log(`[extractJar] Reading version manifest: ${e}`);
          let n = await this.readEntryData(c, t);
          p = JSON.parse(n.toString(`utf8`))
        }
        let m = `${t}-${this.loader.loaderVersion}.json`;
        q.default.log(`[extractJar] Writing loader manifest: ${m}`);
        if (await f.default.writeFile(r.default.join(e, m), JSON.stringify(p, null, 2)), i.push({
            name: m,
            path: this.loader.file.path,
            url: ``,
            type: `OTHER`
          }), o++, this.emit(`extract_progress`, {
            filename: `install_profile.json`
          }), d.filePath) {
          let e = y.getLibraryName(d.path),
            t = y.getLibraryPath(d.path),
            n = r.default.join(this.config.root, `libraries`, t);
          (0, s.existsSync)(n) || await f.default.mkdir(n, {
            recursive: !0
          });
          let i = l.find(e => e.fileName === d.filePath);
          q.default.log(`[extractJar] Extracting library: ${d.filePath}`);
          i && (await this.extractEntryToFile(c, i, r.default.join(n, e)), a.push({
            name: e,
            path: r.default.join(`libraries`, t),
            url: ``,
            type: `LIBRARY`,
            extra: `INSTALL`
          }), o++, this.emit(`extract_progress`, {
            filename: d.filePath
          }))
        } else if (d.path) {
          let e = y.getLibraryPath(d.path),
            t = r.default.join(this.config.root, `libraries`, e);
          (0, s.existsSync)(t) || await f.default.mkdir(t, {
            recursive: !0
          });
          let n = r.default.join(`maven`, e).replace(/\\/g, `/`),
            i = l.filter(e => e.fileName.includes(n) && e.fileName.endsWith(`.jar`));
          q.default.log(`[extractJar] Extracting ${i.length} maven jars from ${n}`);
          i = i.map(async n => {
              await this.extractEntryToFile(c, n, r.default.join(t, r.default.basename(n.fileName))), a.push({
                name: r.default.basename(n.fileName),
                path: r.default.join(`libraries`, e),
                url: ``,
                type: `LIBRARY`,
                extra: `INSTALL`
              }), o++, this.emit(`extract_progress`, {
                filename: r.default.basename(n.fileName)
              })
            });
          await Promise.all(i)
        }
        if (d.processors && d.processors.length > 0) {
          let e = d.libraries.find(e => (e.name + ``).startsWith(`net.minecraftforge:forge:`) || (e.name + ``).startsWith(`net.neoforged:neoforge:`)),
            t = y.getLibraryName(d.path ?? e.name).replace(`.jar`, `-clientdata.lzma`),
            n = y.getLibraryPath(d.path ?? e.name),
            a = r.default.join(this.config.root, `libraries`, n),
            u = l.find(e => e.fileName === `data/client.lzma`);
          q.default.log(`[extractJar] Extracting client.lzma`);
          u && ((0, s.existsSync)(a) || await f.default.mkdir(a, {
            recursive: !0
          }), await this.extractEntryToFile(c, u, r.default.join(a, t)), i.push({
            name: t,
            path: r.default.join(`libraries`, n),
            url: ``,
            type: `LIBRARY`
          }), o++, this.emit(`extract_progress`, {
            filename: t
          }))
        }
        if (d.data?.PATCHED) {
          let e = d.data.PATCHED,
            t = e.client || e.path || (typeof e == `string` ? e : ``);
          if (t && t.startsWith(`[`)) {
            let e = t.replace(`[`, ``).replace(`]`, ``),
              n = y.getLibraryName(e),
              i = y.getLibraryPath(e);
            a.push({
              name: n,
              path: r.default.join(`libraries`, i),
              url: ``,
              sha1: ``,
              size: 0,
              type: `LIBRARY`,
              extra: `INSTALL`
            })
          }
        }
        let [h, g] = await Promise.all([this.formatLibraries(p.libraries, `LOADER`, d), d.libraries ? this.formatLibraries(d.libraries, `INSTALL`, d) : Promise.resolve([])]);
        return a.push(...h), a.push(...g), i.push(...a), q.default.log(`[extractJar] Done: ${a.length} libraries, ${i.length} files, ${o} progress steps`), this.emit(`extract_end`, {
          amount: o
        }), {
          loaderManifest: p,
          installProfile: d,
          libraries: a,
          files: i
        }
      } finally {
        c.close()
      }
    }
    async getMirrorUrl(e) {
      let t = e.url ? [e.url] : [`https://libraries.minecraft.net`, `https://maven.minecraftforge.net/`, `https://maven.neoforged.net/releases/`, `https://maven.creeperhost.net/`];
      for (let n of t) {
        let t = `${n}${y.getLibraryPath(e.name).replaceAll(`\\`,`/`)}${y.getLibraryName(e.name)}`;
        try {
          let e = await fetch(t, {
            method: `HEAD`
          });
          if (!e.ok) continue;
          let n = parseInt(e.headers.get(`Content-Length`) ?? `0`, 10),
            r = await fetch(`${t}.sha1`);
          if (!r.ok) continue;
          return {
            url: t,
            size: n,
            sha1: await r.text()
          }
        } catch {
          continue
        }
      }
      return {
        url: ``,
        size: 0,
        sha1: ``
      }
    }
    async formatLibraries(e, t, n) {
      let i = e.map(async e => {
        let n = `LIBRARY`,
          i;
        if (e.natives) {
          if (i = e.natives[y.getOS_MCCode()], !i) return null;
          n = `NATIVE`
        } else if (!y.isLibAllowed(e) || !e.serverreq && !e.clientreq && !e.url && !e.downloads) return null;
        let a = e.downloads?.artifact,
          o = ``,
          s = ``,
          c = ``,
          l = ``,
          u = 0;
        if (a) a.path ? (o = a.path.split(`/`).pop(), s = r.default.join(`libraries`, a.path.split(`/`).slice(0, -1).join(`/`), `/`)) : (o = y.getLibraryName(e.name), n === `NATIVE` && (o = o.replace(`.jar`, `-${i}.jar`)), s = y.getLibraryPath(e.name, `libraries`)), c = a.url, l = a.sha1, u = a.size;
        else {
          let t = await this.getMirrorUrl(e);
          o = y.getLibraryName(e.name), n === `NATIVE` && (o = o.replace(`.jar`, `-${i}.jar`)), s = y.getLibraryPath(e.name, `libraries`), c = t.url, l = t.sha1, u = t.size
        }
        return {
          name: o,
          path: s,
          url: c,
          sha1: l,
          size: u,
          type: n,
          extra: t
        }
      });
      return (await Promise.all(i)).filter(e => e !== null)
    }
    openZip(e) {
      return new Promise((t, n) => {
        let r = setTimeout(() => n(new Error(`openZip timeout for ${e}`)), 120000);
        q.default.log(`[openZip] Opening zip: ${e}`);
        I.open(e, {
          lazyEntries: !1,
          autoClose: !1
        }, (i, a) => {
          if (i || !a) return clearTimeout(r), q.default.log(`[openZip] Failed to open: ${e}`), n(i ?? new h(g.FILE_ERROR, `Failed to open ${e}`));
          let o = [], s = 0;
          a.on(`entry`, e => {
            s++, clearTimeout(r), r = setTimeout(() => n(new Error(`openZip timeout for ${e}`)), 120000), o.push(e), q.default.log(`[openZip] Entry ${s}: ${e.fileName}`)
          }), a.on(`end`, () => (clearTimeout(r), q.default.log(`[openZip] Done: ${s} entries from ${e}`), t({
            zipfile: a,
            entries: o
          }))), a.on(`error`, e => (clearTimeout(r), q.default.log(`[openZip] Error: ${e.message}`), n(e)))
        })
      })
    }
    readEntryData(e, t) {
      return new Promise((n, r) => {
        let a = setTimeout(() => r(new Error(`readEntryData timeout for ${t.fileName}`)), 120000), s = 0;
        q.default.log(`[readEntryData] Reading: ${t.fileName} (compressed:${t.compressedSize} uncompressed:${t.uncompressedSize})`);
        e.openReadStream(t, (e, i) => {
          if (e || !i) return clearTimeout(a), q.default.log(`[readEntryData] Failed to open: ${t.fileName}`), r(e ?? new h(g.FILE_ERROR, `Failed to open read stream for ${t.fileName}`));
          let o = [];
          i.on(`data`, e => {
            s += e.length, clearTimeout(a), a = setTimeout(() => r(new Error(`readEntryData timeout for ${t.fileName}`)), 120000), o.push(e)
          }), i.on(`end`, () => (clearTimeout(a), q.default.log(`[readEntryData] Done: ${t.fileName} (${s} bytes)`), n(Buffer.concat(o)))), i.on(`error`, e => (clearTimeout(a), q.default.log(`[readEntryData] Error: ${t.fileName} - ${e.message}`), r(e)))
        })
      })
    }
    extractEntryToFile(e, t, n) {
      return new Promise((r, i) => {
        let a = setTimeout(() => i(new Error(`extractEntryToFile timeout for ${t.fileName}`)), 60000);
        q.default.log(`[extractEntryToFile] Writing: ${t.fileName} → ${n}`);
        e.openReadStream(t, (e, o) => {
          if (e || !o) return clearTimeout(a), q.default.log(`[extractEntryToFile] Failed: ${t.fileName}`), i(e ?? new h(g.FILE_ERROR, `Failed to open read stream for ${t.fileName}`));
          let l = (0, s.createWriteStream)(n);
          o.pipe(l), l.on(`close`, () => (clearTimeout(a), q.default.log(`[extractEntryToFile] Done: ${n}`), r())), l.on(`error`, e => (clearTimeout(a), q.default.log(`[extractEntryToFile] Write error: ${t.fileName} - ${e.message}`), i(e))), o.on(`error`, e => (clearTimeout(a), i(e)))
        })
      })
    }
    pipeEntryToYazl(e, t, n) {
      return new Promise((r, i) => {
        let a = setTimeout(() => i(new Error(`pipeEntryToYazl timeout for ${t.fileName}`)), 60000);
        q.default.log(`[pipeEntryToYazl] Adding: ${t.fileName}`);
        e.openReadStream(t, (e, o) => {
          if (e || !o) return clearTimeout(a), q.default.log(`[pipeEntryToYazl] Failed: ${t.fileName}`), i(e ?? new h(g.FILE_ERROR, `Failed to open read stream for ${t.fileName}`));
          n.addReadStream(o, t.fileName), o.on(`end`, () => (clearTimeout(a), r())), o.on(`error`, e => (clearTimeout(a), q.default.log(`[pipeEntryToYazl] Error: ${t.fileName} - ${e.message}`), i(e)))
        })
      })
    }
  },
  ne = class extends v {
    constructor(e, t, n) {
      super(), this.config = e, this.manifest = t, this.loader = n, this.loader.type === `QUILT` ? this.metaConfig = {
        name: `Quilt`,
        url: `https://meta.quiltmc.org`,
        apiVersion: `v3`
      } : this.metaConfig = {
        name: `Fabric`,
        url: `https://meta.fabricmc.net`,
        apiVersion: `v2`
      }
    }
    async setup() {
      let e = this.loader.type.toLowerCase(),
        t = r.default.join(this.config.root, `versions`, `${e}-${this.loader.loaderVersion}`),
        n = `${this.loader.minecraftVersion}-${e}-${this.loader.loaderVersion}.json`,
        i = r.default.join(t, n);
      (0, s.existsSync)(t) || await f.default.mkdir(t, {
        recursive: !0
      });
      let a = `${this.metaConfig.url}/${this.metaConfig.apiVersion}/versions/loader/${this.manifest.id}/${this.loader.loaderVersion}/profile/json`,
        o;
      try {
        let e = await fetch(a);
        if (!e.ok) {
          let t = await e.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch ${this.metaConfig.name} loader manifest: HTTP ${e.status} ${t}`)
        }
        o = await e.json()
      } catch (e) {
        if ((0, s.existsSync)(i)) {
          let e = await f.default.readFile(i, `utf-8`);
          o = JSON.parse(e)
        } else throw e instanceof h ? e : new h(g.FETCH_ERROR, `Failed to fetch ${this.metaConfig.name} loader manifest: ${e instanceof Error?e.message:e}`)
      }
      let c = [];
      o.id = `${this.loader.minecraftVersion}-${e}-${this.loader.loaderVersion}`, await f.default.writeFile(i, JSON.stringify(o, null, 2)), c.push({
        name: n,
        path: r.default.relative(this.config.root, t),
        url: a,
        type: `OTHER`
      });
      let l = await this.formatLibraries(o.libraries);
      return c.push(...l), {
        loaderManifest: o,
        installProfile: null,
        libraries: l,
        files: c
      }
    }
    async formatLibraries(e) {
      let t = e.map(async e => {
        let t = y.getLibraryName(e.name),
          n = y.getLibraryPath(e.name, `libraries`),
          r = this.loader.type === `QUILT` ? `https://maven.quiltmc.org/repository/release/` : `https://maven.fabricmc.net/`,
          i = `${e.url??r}${y.getLibraryPath(e.name).replaceAll(`\\`,`/`)}${t}`,
          a = await y.getRemoteFileSize(i, `Failed to get size for library ${t}`);
        return {
          name: t,
          path: n,
          url: i,
          sha1: await y.getRemoteFileSha1(i, `Failed to get SHA1 for library ${t}`),
          size: a,
          type: `LIBRARY`,
          extra: `LOADER`
        }
      });
      return await Promise.all(t)
    }
  },
  H = class extends v {
    constructor(e, t, n) {
      super(), this.config = e, this.manifest = t, this.loader = n
    }
    async setupLoader() {
      let e = {
        loaderManifest: null,
        installProfile: null,
        libraries: [],
        files: []
      };
      if (this.loader.type === `FORGE` || this.loader.type === `NEOFORGE`) {
        let t = new V(this.config, this.manifest, this.loader);
        t.forwardEvents(this), e = await t.setup()
      } else if (this.loader.type === `FABRIC` || this.loader.type === `QUILT`) {
        let t = new ne(this.config, this.manifest, this.loader);
        t.forwardEvents(this), e = await t.setup()
      }
      return e
    }
    async patchLoader(e) {
      if ((this.loader.type === `FORGE` || this.loader.type === `NEOFORGE`) && e) {
        let t = new R(this.config, this.manifest, this.loader, e);
        return t.forwardEvents(this), {
          files: await t.patch()
        }
      }
      return {
        files: []
      }
    }
  },
  U = class {
    constructor(e, t) {
      this.config = e, this.manifest = t, this.loaderManifest = null, this.loader = null
    }
    getArgs(e, t, n = null, r) {
      this.loaderManifest = n, this.loader = t;
      let i = this.getJvmArgs(e, r),
        a = this.getMainClass(),
        o = this.getMinecraftArgs();
      return [...i, a, ...o]
    }
    getJvmArgs(e, t) {
      let n = r.default.join(this.config.root, `bin`, this.manifest.id).replaceAll(`\\`, `/`),
        i = r.default.join(this.config.root, `libraries`).replaceAll(`\\`, `/`),
        a = this.getClasspath(e),
        o = [...this.config.java?.args || []];
      return t && (o.push(`-Djava.net.preferIPv4Stack=true`), o.push(`-javaagent:${t.injectorPath}=${t.authServerUrl}`)), this.manifest.arguments?.jvm ? [...this.manifest.arguments.jvm, ...this.loaderManifest?.arguments?.jvm || []].forEach(e => {
        typeof e == `string` ? o.push(e) : e.rules && y.isArgAllowed(e) && (typeof e.value == `string` ? o.push(e.value) : o.push(...e.value))
      }) : (o.push("-Djava.library.path=${natives_directory}"), o.push("-Dminecraft.launcher.brand=${launcher_name}"), o.push("-Dminecraft.launcher.version=${launcher_version}"), o.push("-Dminecraft.client.jar=${jar_path}"), o.push(`-cp`), o.push("${classpath}"), y.getOS() === `win` && +y.getOSVersion().split(`.`)[0] >= 10 && (o.push(`-Dos.name=Windows 10`), o.push(`-Dos.version=10.0`)), y.getOS() === `win` && o.push(`-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump`), y.getOS() === `mac` && o.push(`-XstartOnFirstThread`), y.getArch() === `32` && o.push(`-Xss1M`)), o.push(...this.getLog4jArgs()), o.push("-Xmx${max_memory}M"), o.push("-Xms${min_memory}M"), o.push(`-Dfml.ignoreInvalidMinecraftCertificates=true`), o.map(e => e.replaceAll("${natives_directory}", n).replaceAll("${library_directory}", i).replaceAll("${launcher_name}", `${this.config.root}-launcher`).replaceAll("${launcher_version}", `2`).replaceAll("${version_name}", this.manifest.id).replaceAll("${jar_path}", r.default.join(this.config.root, `versions`, this.manifest.id, `${this.manifest.id}.jar`).replaceAll(`\\`, `/`)).replaceAll("${classpath}", a).replaceAll("${max_memory}", this.config.memory.max + ``).replaceAll("${min_memory}", this.config.memory.min + ``).replaceAll("${classpath_separator}", r.default.delimiter))
    }
    getLog4jArgs() {
      let e = [];
      return this.manifest.id === `1.18` || this.manifest.id.startsWith(`1.17`) ? e.push(`-Dlog4j2.formatMsgNoLookups=true`) : +this.manifest.id.split(`.`)[1] <= 16 && +this.manifest.id.split(`.`)[1] >= 12 ? e.push(`-Dlog4j.configurationFile=log4j2_112-116.xml`) : +this.manifest.id.split(`.`)[1] <= 11 && +this.manifest.id.split(`.`)[1] >= 7 && e.push(`-Dlog4j.configurationFile=log4j2_17-111.xml`), e
    }
    getMinecraftArgs() {
      let e = y.sanitizeSlug(this.config.storage === `shared` && this.config.slug ? this.config.slug : ``),
        t = r.default.join(this.config.root, e).replaceAll(`\\`, `/`),
        n = this.manifest.assets === `legacy` || this.manifest.assets === `pre-1.6` ? r.default.join(this.config.root, `resources`).replaceAll(`\\`, `/`) : r.default.join(this.config.root, `assets`).replaceAll(`\\`, `/`),
        i = [...this.config.minecraft?.args || []];
      this.manifest.arguments?.game ? [...this.manifest.arguments.game, ...this.loaderManifest?.arguments?.game || []].forEach(e => {
        typeof e == `string` ? i.push(e) : e.rules && y.isArgAllowed(e) && (typeof e.value == `string` ? i.push(e.value) : i.push(...e.value))
      }) : this.manifest.minecraftArguments && i.push(...(this.loaderManifest?.minecraftArguments || this.manifest.minecraftArguments).split(` `)), this.config.window.fullscreen ? i.push(`--fullscreen`) : (i.push(`--width`), i.push("${resolution_width}"), i.push(`--height`), i.push("${resolution_height}"));
      let a = [],
        o = new Set;
      for (let e = 0; e < i.length; e++) {
        let t = i[e],
          n = i[e + 1],
          r = t.startsWith(`--`) || t.startsWith(`-D`),
          s = r && n && !n.startsWith(`-`) ? `${t}=${n}` : t;
        o.has(s) || (o.add(s), a.push(t), r && n && !n.startsWith(`-`) && (a.push(n), e++))
      }
      return a.map(e => e.replaceAll("${clientid}", this.config.account.clientToken || this.config.account.accessToken).replaceAll("${auth_xuid}", this.config.account.xbox?.xuid || this.config.account.accessToken).replaceAll("${auth_player_name}", this.config.account.name).replaceAll("${auth_uuid}", this.config.account.uuid).replaceAll("${auth_access_token}", this.config.account.accessToken).replaceAll("${user_type}", this.manifest.id.startsWith(`1.16`) && this.config.account.meta.type === `msa` ? `Xbox` : this.config.account.meta.type === `yggdrasil` ? `Mojang` : this.config.account.meta.type).replaceAll("${version_name}", this.manifest.id).replaceAll("${game_directory}", t).replaceAll("${assets_root}", n).replaceAll("${assets_index_name}", this.manifest.assetIndex.id).replaceAll("${version_type}", this.manifest.type).replaceAll("${resolution_width}", this.config.window.width + ``).replaceAll("${resolution_height}", this.config.window.height + ``).replaceAll("${auth_session}", this.config.account.accessToken).replaceAll("${user_properties}", JSON.stringify(this.config.account.userProperties || {})).replaceAll("${game_assets}", n))
    }
    getClasspath(e) {
      let t = [];
      e = [...new Set(e)];
      for (let n = 0; n < e.length; n++) {
        let i = e[n];
        if (i.extra === `INSTALL` || i.type !== `LIBRARY` || e.find((e, t) => n === t || e.extra === `INSTALL` ? !1 : y.isNewer(i, e) === !0)) continue;
        let a = r.default.join(this.config.root, i.path, i.name).replaceAll(`\\`, `/`);
        t.push(a)
      }
      return [...new Set(t)].join(r.default.delimiter)
    }
    getMainClass() {
      return this.loaderManifest?.mainClass ?? this.manifest.mainClass
    }
  },
  W = {
    FORGE: {
      name: `Forge`,
      mavenUrl: `https://maven.minecraftforge.net`,
      group: `net.minecraftforge`,
      artifact: `forge`,
      promotionsUrl: `https://files.minecraftforge.net/maven/net/minecraftforge/forge/promotions_slim.json`
    },
    NEOFORGE: {
      name: `NeoForge`,
      mavenUrl: `https://maven.neoforged.net/releases`,
      group: `net.neoforged`,
      artifact: `neoforge`,
      promotionsUrl: null
    }
  },
  re = new class {
    async getLoader(e) {
      if (!e.minecraft.version && !e.url) return {
        type: `VANILLA`,
        minecraftVersion: `latest_release`,
        loaderVersion: `latest_release`
      };
      if (!e.minecraft.version && e.url) try {
        let t = await fetch(`${e.url}/api/loader/${e.slug??``}`);
        if (!t.ok) {
          let e = await t.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch loader info: HTTP ${t.status} ${e}`)
        }
        return await t.json()
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Failed to fetch loader info: ${e instanceof Error?e.message:e}`)
      } else {
        if (e.minecraft.loader?.loader === `vanilla`) return {
          type: `VANILLA`,
          minecraftVersion: e.minecraft.version ?? `latest_release`,
          loaderVersion: e.minecraft.loader.version ?? e.minecraft.version ?? `latest_release`
        };
        if (e.minecraft.loader?.loader === `forge`) {
          let t = await this.getForgeLikeFile(`FORGE`, e.minecraft.loader.version);
          return {
            type: `FORGE`,
            minecraftVersion: e.minecraft.version,
            loaderVersion: e.minecraft.loader.version,
            format: t.format,
            file: t.file,
            updatedAt: new Date
          }
        }
        if (e.minecraft.loader?.loader === `neoforge`) {
          let t = await this.getForgeLikeFile(`NEOFORGE`, e.minecraft.loader.version);
          return {
            type: `NEOFORGE`,
            minecraftVersion: e.minecraft.version,
            loaderVersion: e.minecraft.loader.version,
            format: t.format,
            file: t.file,
            updatedAt: new Date
          }
        }
        if (e.minecraft.loader?.loader === `fabric`) return {
          type: `FABRIC`,
          minecraftVersion: e.minecraft.version,
          loaderVersion: e.minecraft.loader.version,
          format: `CLIENT`
        };
        if (e.minecraft.loader?.loader === `quilt`) return {
          type: `QUILT`,
          minecraftVersion: e.minecraft.version,
          loaderVersion: e.minecraft.loader.version,
          format: `CLIENT`
        };
        throw new h(g.CONFIG_ERROR, `Invalid loader type`)
      }
    }
    async getForgeLikeFile(e, t) {
      let n = W[e],
        r = `installer`,
        i = `jar`;
      if (e === `FORGE`) {
        let e = `https://files.minecraftforge.net/net/minecraftforge/forge/${t}/meta.json`,
          n = await fetch(e);
        if (!n.ok) {
          let e = await n.text();
          throw new h(g.FETCH_ERROR, `Failed to fetch Forge meta: HTTP ${n.status} ${e}`)
        }
        let a = (await n.json()).classifiers;
        r = this.getFormat(a), i = Object.keys(a[r])[0]
      }
      let a = `${n.mavenUrl}/${n.group.replace(/\./g,`/`)}/${n.artifact}/${t}/${n.artifact}-${t}-${r.toLowerCase()}.${i}`,
        o = `${n.artifact}-${t}.${i}`,
        s = `versions/${n.artifact}-${t}/`,
        c = await y.getRemoteFileSize(a, `Failed to fetch ForgeLike artifact size`),
        l = await y.getRemoteFileSha1(`${a}.sha1`, `Failed to fetch ForgeLike artifact SHA1`);
      return {
        format: this.getTypedFormat(r),
        file: {
          name: o,
          path: s,
          url: a,
          size: c,
          sha1: l,
          type: `OTHER`
        }
      }
    }
    getFormat(e) {
      return e.installer ? `installer` : e.client ? `client` : `universal`
    }
    getTypedFormat(e) {
      switch (e) {
        case `installer`:
          return `INSTALLER`;
        case `client`:
          return `CLIENT`;
        default:
          return `UNIVERSAL`
      }
    }
  },
  ie = class extends v {
    constructor(e) {
      super();
      let t = {
        ...e,
        slug: void 0
      };
      t.minecraft = this.setMinecraft(t), t.slug = this.setSlug(t), t.url = this.setUrl(t), t.storage = this.setStorage(t), t.root = this.setRoot(t), t.cleaning = this.setCleaning(t), t.account = this.setAccount(t), t.java = this.setJava(t), t.window = this.setWindow(t), t.memory = this.setMemory(t), this.config = {
        url: t.url,
        slug: t.slug,
        storage: t.storage,
        root: t.root,
        minecraft: t.minecraft,
        cleaning: t.cleaning,
        account: t.account,
        java: t.java,
        window: t.window,
        memory: t.memory
      }
    }
    async launch() {
      let e = await re.getLoader(this.config),
        t = await k.getMinecraftManifest(this.config, e);
      this.config.minecraft.version = t.id;
      let n = new ee(this.config, t, e),
        r = new H(this.config, t, e),
        i = new U(this.config, t),
        a = new A(this.config.root),
        o = new L(this.config.root),
        s = new j(this.config);
      n.forwardEvents(this), r.forwardEvents(this), a.forwardEvents(this), o.forwardEvents(this), s.forwardEvents(this), this.emit(`launch_compute_download`);
      let c = await n.getJava(),
        l = await n.getModpack(),
        u = await n.getLibraries(),
        d = await n.getAssets(),
        f = await n.getInjector(),
        p = await n.getLog4j(),
        m = await a.getFilesToDownload(c.java),
        h = await a.getFilesToDownload(l.modpack),
        g = await a.getFilesToDownload(u.libraries),
        _ = await a.getFilesToDownload(d.assets),
        v = await a.getFilesToDownload(f.injector),
        y = await a.getFilesToDownload(p.log4j),
        b = [...m, ...h, ...g, ..._, ...v, ...y];
      this.emit(`launch_download`, {
        total: {
          amount: b.length,
          size: b.reduce((e, t) => e + t.size, 0)
        }
      }), await a.download(m, !0), await a.download(h, !0), await a.download(g, !0), await a.download(_, !0), await a.download(v, !0), await a.download(y, !0), this.emit(`launch_install_loader`, e);
      let x;
      for (let _r = 0; _r < 3; _r++) {
        try {
          x = await r.setupLoader();
          break
        } catch (err) {
          if (_r >= 2) throw err;
          if (err instanceof h && err.message?.includes(`Corrupted zip`)) {
            q.default.log(`[Launch] Corrupted installer, re-downloading (attempt ${_r + 2})...`);
            await a.download([e.file], !0);
            continue
          }
          throw err
        }
      }
      await a.download(x.libraries), this.emit(`launch_extract_natives`);
      let S = await n.extractNatives([...u.libraries, ...x.libraries]);
      this.emit(`launch_copy_assets`);
      let C = await n.copyAssets();
      this.emit(`launch_check_java`), await s.check(this.config.java.absolutePath, t.javaVersion?.majorVersion ?? 8), this.emit(`launch_patch_loader`);
      let w = await r.patchLoader(x.installProfile);
      this.emit(`launch_clean`);
      let T = [...c.files, ...l.files, ...u.files, ...d.files, ...f.files, ...p.files, ...S.files, ...C.files, ...x.files, ...w.files];
      await o.clean(T, this.config.cleaning.ignored, !this.config.cleaning.enabled), this.emit(`launch_launch`, {
        version: t.id,
        type: e.type,
        loaderVersion: e.loaderVersion
      });
      let E = this.config.account.meta.type === `yggdrasil` && f.injector[0] ? {
          injectorPath: f.injector[0].path + f.injector[0].name,
          authServerUrl: this.config.account.meta.url
        } : void 0,
        D = i.getArgs([...x.libraries, ...u.libraries], e, x.loaderManifest, E),
        O = D.map((e, t) => t === D.findIndex(e => e === `--accessToken`) + 1 ? `**********` : e);
      this.emit(`launch_debug`, `Launching Minecraft with args: ${O.join(` `)}`), await this.run(this.config.java.absolutePath.replace("${X}", t.javaVersion?.majorVersion.toString() ?? `8`), D)
    }
    setMinecraft(e) {
      let t = !!(e.profile?.slug && e.profile.slug !== `` && e.profile.slug === y.sanitizeSlug(e.profile.slug)),
        n = t && e.profile?.minecraft?.version ? e.profile.minecraft : null,
        r = e.minecraft?.version ? e.minecraft : null,
        i = n || r;
      if (e.profile && !t) {
        let t = e.url ? `EML AdminTool default profile` : `latest Minecraft version`;
        r && (t = `Minecraft config`), console.warn(`Warning: Invalid profile. Launching with ${t}.`)
      }
      if (!i) {
        let t = e.url ? void 0 : `latest_release`;
        return {
          version: t,
          loader: t ? {
            loader: `vanilla`,
            version: t
          } : void 0,
          modpackUrl: void 0,
          args: e.minecraft?.args || []
        }
      }
      let a = i.version,
        o, s = i.loader;
      if (!s || s.loader === `vanilla`) o = {
        loader: `vanilla`,
        version: a
      };
      else {
        if (!s.version) throw new h(g.CONFIG_ERROR, `You must provide a loader version in the config when using a loader different from vanilla.`);
        o = {
          loader: s.loader,
          version: s.version
        }
      }
      let c = t && e.profile?.minecraft?.args ? e.profile.minecraft.args : e.minecraft?.args || [];
      return {
        version: a,
        loader: o,
        modpackUrl: i.modpackUrl,
        args: c
      }
    }
    setSlug(e) {
      if (e.profile?.slug && e.profile.slug !== `` && e.profile.slug === y.sanitizeSlug(e.profile.slug)) return e.profile.slug
    }
    setUrl(e) {
      if (!e.minecraft?.version && e.url) return e.url
    }
    setStorage(e) {
      return e.storage === `shared` ? `shared` : e.storage === `isolated` ? `isolated` : e.storageMode === `shared` ? `shared` : `isolated`
    }
    setRoot(e) {
      if (!e.root && !e.serverId) throw new h(g.CONFIG_ERROR, `You must provide a root in the config to set the game folder.`);
      return e.root ||= e.serverId, y.getRootFolder(e)
    }
    setCleaning(e) {
      let t = [`crash-reports/`, `logs/`, `resourcepacks/`, `resources/`, `saves/`, `shaderpacks/`, `config/`, `options.txt`, `optionsof.txt`, `servers.dat`, `hotbar.nbt`],
        n = !0,
        r = t;
      return n = e.cleaning?.enabled === void 0 ? e.cleaning?.clean === void 0 ? !0 : e.cleaning.clean : e.cleaning.enabled, e.storage === `shared` && n && console.warn(`Warning: You are using shared storage mode with cleaning enabled. This may cause issues as the launcher will delete shared assets and libraries when launching different profiles. It is recommended to disable cleaning when using shared storage mode.`), e.cleaning?.ignored && (r = e.cleaning.ignored), {
        enabled: n,
        ignored: r
      }
    }
    setAccount(e) {
      return e.account?.meta.type === `crack` && console.warn(`Warning: You are using a cracked account (offline mode). This authentication method is not secure and is not recommended. Use it only for testing purposes.`), e.account
    }
    setJava(e) {
      let t = `auto`,
        n, i = [];
      return e.java?.install === `manual` ? (t = `manual`, n = e.java.absolutePath ? e.java.absolutePath : e.java.relativePath ? r.default.join(e.root, e.java.relativePath) : `java`) : (t = `auto`, n = r.default.join(e.root, `runtime`, "jre-${X}", `bin`, `java`)), e.java?.args && (i = e.java.args), {
        install: t,
        absolutePath: n,
        args: i
      }
    }
    setWindow(e) {
      let t = 854,
        n = 480,
        r = !1;
      return e.window?.width && e.window.width > 100 && (t = e.window.width), e.window?.height && e.window.height > 100 && (n = e.window.height), e.window?.fullscreen && (r = e.window.fullscreen), {
        width: t,
        height: n,
        fullscreen: r
      }
    }
    setMemory(e) {
      let t = 512,
        n = 1023;
      return e.memory?.min && e.memory.min > 128 && (t = e.memory.min), e.memory?.max && e.memory.max > t && (n = e.memory.max), {
        min: t,
        max: n
      }
    }
    async run(e, t) {
      return new Promise((n, r) => {
        let i = (0, m.spawn)(e, t, {
          cwd: this.config.root,
          detached: !0
        });
        i.unref(), i.stdout.on(`data`, e => this.emit(`launch_data`, e.toString(`utf8`).replace(/\n$/, ``))), i.stderr.on(`data`, e => this.emit(`launch_data`, e.toString(`utf8`).replace(/\n$/, ``))), i.on(`error`, r), i.on(`close`, e => {
          this.emit(`launch_close`, e ?? -1), n()
        })
      })
    }
  },
  ae = class {
    constructor(e) {
      this.url = `${e}/api`
    }
    async getProfiles() {
      try {
        let e = await fetch(`${this.url}/profiles`);
        if (!e.ok) {
          let t = await e.text();
          throw new h(g.FETCH_ERROR, `Error while fetching profiles: HTTP ${e.status} ${t}`)
        }
        return (await e.json()).profiles ?? []
      } catch (e) {
        throw e instanceof h ? e : new h(g.FETCH_ERROR, `Error while fetching profiles: ${e instanceof Error?e.message:e}`)
      }
    }
  },
  oe = e.t(((e, t) => {
    var n = require(`fs`),
      r = require(`path`);
    t.exports = {
      findAndReadPackageJson: i,
      tryReadJsonAt: a
    };

    function i() {
      return a(c()) || a(s()) || a(process.resourcesPath, `app.asar`) || a(process.resourcesPath, `app`) || a(process.cwd()) || {
        name: void 0,
        version: void 0
      }
    }

    function a(...e) {
      if (e[0]) try {
        let t = o(`package.json`, r.join(...e));
        if (!t) return;
        let i = JSON.parse(n.readFileSync(t, `utf8`)),
          a = i?.productName || i?.name;
        return !a || a.toLowerCase() === `electron` ? void 0 : a ? {
          name: a,
          version: i?.version
        } : void 0
      } catch {
        return
      }
    }

    function o(e, t) {
      let i = t;
      for (;;) {
        let t = r.parse(i),
          a = t.root,
          o = t.dir;
        if (n.existsSync(r.join(i, e))) return r.resolve(r.join(i, e));
        if (i === a) return null;
        i = o
      }
    }

    function s() {
      let e = process.argv.filter(e => e.indexOf(`--user-data-dir=`) === 0);
      return e.length === 0 || typeof e[0] != `string` ? null : e[0].replace(`--user-data-dir=`, ``)
    }

    function c() {
      try {
        return require.main?.filename
      } catch {
        return
      }
    }
  })),
  se = e.t(((e, t) => {
    var n = require(`child_process`),
      r = require(`os`),
      i = require(`path`),
      a = oe();
    t.exports = class {
      appName = void 0;
      appPackageJson = void 0;
      platform = process.platform;
      getAppLogPath(e = this.getAppName()) {
        return this.platform === `darwin` ? i.join(this.getSystemPathHome(), `Library/Logs`, e) : i.join(this.getAppUserDataPath(e), `logs`)
      }
      getAppName() {
        let e = this.appName || this.getAppPackageJson()?.name;
        if (!e) throw Error(`electron-log can't determine the app name. It tried these methods:
1. Use \`electron.app.name\`
2. Use productName or name from the nearest package.json\`
You can also set it through log.transports.file.setAppName()`);
        return e
      }
      getAppPackageJson() {
        return typeof this.appPackageJson != `object` && (this.appPackageJson = a.findAndReadPackageJson()), this.appPackageJson
      }
      getAppUserDataPath(e = this.getAppName()) {
        return e ? i.join(this.getSystemPathAppData(), e) : void 0
      }
      getAppVersion() {
        return this.getAppPackageJson()?.version
      }
      getElectronLogPath() {
        return this.getAppLogPath()
      }
      getMacOsVersion() {
        let e = Number(r.release().split(`.`)[0]);
        return e <= 19 ? `10.${e-4}` : e - 9
      }
      getOsVersion() {
        let e = r.type().replace(`_`, ` `),
          t = r.release();
        return e === `Darwin` && (e = `macOS`, t = this.getMacOsVersion()), `${e} ${t}`
      }
      getPathVariables() {
        let e = this.getAppName(),
          t = this.getAppVersion(),
          n = this;
        return {
          appData: this.getSystemPathAppData(),
          appName: e,
          appVersion: t,
          get electronDefaultDir() {
            return n.getElectronLogPath()
          },
          home: this.getSystemPathHome(),
          libraryDefaultDir: this.getAppLogPath(e),
          libraryTemplate: this.getAppLogPath(`{appName}`),
          temp: this.getSystemPathTemp(),
          userData: this.getAppUserDataPath(e)
        }
      }
      getSystemPathAppData() {
        let e = this.getSystemPathHome();
        switch (this.platform) {
          case `darwin`:
            return i.join(e, `Library/Application Support`);
          case `win32`:
            return process.env.APPDATA || i.join(e, `AppData/Roaming`);
          default:
            return process.env.XDG_CONFIG_HOME || i.join(e, `.config`)
        }
      }
      getSystemPathHome() {
        return r.homedir?.() || process.env.HOME
      }
      getSystemPathTemp() {
        return r.tmpdir()
      }
      getVersions() {
        return {
          app: `${this.getAppName()} ${this.getAppVersion()}`,
          electron: void 0,
          os: this.getOsVersion()
        }
      }
      isDev() {
        return process.env.NODE_ENV === `development` || process.env.ELECTRON_IS_DEV === `1`
      }
      isElectron() {
        return !!process.versions.electron
      }
      onAppEvent(e, t) {}
      onAppReady(e) {
        e()
      }
      onEveryWebContentsEvent(e, t) {}
      onIpc(e, t) {}
      onIpcInvoke(e, t) {}
      openUrl(e, t = console.error) {
        let r = {
          darwin: `open`,
          win32: `start`,
          linux: `xdg-open`
        } [process.platform] || `xdg-open`;
        n.exec(`${r} ${e}`, {}, e => {
          e && t(e)
        })
      }
      setAppName(e) {
        this.appName = e
      }
      setPlatform(e) {
        this.platform = e
      }
      setPreloadFileForSessions({
        filePath: e,
        includeFutureSession: t = !0,
        getSessions: n = () => []
      }) {}
      sendIpc(e, t) {}
      showErrorBox(e, t) {}
    }
  })),
  ce = e.t(((e, t) => {
    var n = require(`path`),
      r = se();
    t.exports = class extends r {
      electron = void 0;
      constructor({
        electron: e
      } = {}) {
        super(), this.electron = e
      }
      getAppName() {
        let e;
        try {
          e = this.appName || this.electron.app?.name || this.electron.app?.getName()
        } catch {}
        return e || super.getAppName()
      }
      getAppUserDataPath(e) {
        return this.getPath(`userData`) || super.getAppUserDataPath(e)
      }
      getAppVersion() {
        let e;
        try {
          e = this.electron.app?.getVersion()
        } catch {}
        return e || super.getAppVersion()
      }
      getElectronLogPath() {
        return this.getPath(`logs`) || super.getElectronLogPath()
      }
      getPath(e) {
        try {
          return this.electron.app?.getPath(e)
        } catch {
          return
        }
      }
      getVersions() {
        return {
          app: `${this.getAppName()} ${this.getAppVersion()}`,
          electron: `Electron ${process.versions.electron}`,
          os: this.getOsVersion()
        }
      }
      getSystemPathAppData() {
        return this.getPath(`appData`) || super.getSystemPathAppData()
      }
      isDev() {
        return this.electron.app?.isPackaged === void 0 ? typeof process.execPath == `string` ? n.basename(process.execPath).toLowerCase().startsWith(`electron`) : super.isDev() : !this.electron.app.isPackaged
      }
      onAppEvent(e, t) {
        return this.electron.app?.on(e, t), () => {
          this.electron.app?.off(e, t)
        }
      }
      onAppReady(e) {
        this.electron.app?.isReady() ? e() : this.electron.app?.once ? this.electron.app?.once(`ready`, e) : e()
      }
      onEveryWebContentsEvent(e, t) {
        return this.electron.webContents?.getAllWebContents()?.forEach(n => {
          n.on(e, t)
        }), this.electron.app?.on(`web-contents-created`, n), () => {
          this.electron.webContents?.getAllWebContents().forEach(n => {
            n.off(e, t)
          }), this.electron.app?.off(`web-contents-created`, n)
        };

        function n(n, r) {
          r.on(e, t)
        }
      }
      onIpc(e, t) {
        this.electron.ipcMain?.on(e, t)
      }
      onIpcInvoke(e, t) {
        this.electron.ipcMain?.handle?.(e, t)
      }
      openUrl(e, t = console.error) {
        this.electron.shell?.openExternal(e).catch(t)
      }
      setPreloadFileForSessions({
        filePath: e,
        includeFutureSession: t = !0,
        getSessions: n = () => [this.electron.session?.defaultSession]
      }) {
        for (let e of n().filter(Boolean)) r(e);
        t && this.onAppEvent(`session-created`, e => {
          r(e)
        });

        function r(t) {
          typeof t.registerPreloadScript == `function` ? t.registerPreloadScript({
            filePath: e,
            id: `electron-log-preload`,
            type: `frame`
          }) : t.setPreloads([...t.getPreloads(), e])
        }
      }
      sendIpc(e, t) {
        this.electron.BrowserWindow?.getAllWindows()?.forEach(n => {
          n.webContents?.isDestroyed() === !1 && n.webContents?.isCrashed() === !1 && n.webContents.send(e, t)
        })
      }
      showErrorBox(e, t) {
        this.electron.dialog?.showErrorBox(e, t)
      }
    }
  })),
  le = e.t(((e, t) => {
    var n = {};
    try {
      n = require(`electron`)
    } catch {}
    n.ipcRenderer && r(n), typeof t == `object` && (t.exports = r);

    function r({
      contextBridge: e,
      ipcRenderer: t
    }) {
      if (!t) return;
      t.on(`__ELECTRON_LOG_IPC__`, (e, t) => {
        window.postMessage({
          cmd: `message`,
          ...t
        })
      }), t.invoke(`__ELECTRON_LOG__`, {
        cmd: `getOptions`
      }).catch(e => console.error(Error(`electron-log isn't initialized in the main process. Please call log.initialize() before. ${e.message}`)));
      let n = {
        sendToMain(e) {
          try {
            t.send(`__ELECTRON_LOG__`, e)
          } catch (n) {
            console.error(`electronLog.sendToMain `, n, `data:`, e), t.send(`__ELECTRON_LOG__`, {
              cmd: `errorHandler`,
              error: {
                message: n?.message,
                stack: n?.stack
              },
              errorName: `sendToMain`
            })
          }
        },
        log(...e) {
          n.sendToMain({
            data: e,
            level: `info`
          })
        }
      };
      for (let e of [`error`, `warn`, `info`, `verbose`, `debug`, `silly`]) n[e] = (...t) => n.sendToMain({
        data: t,
        level: e
      });
      if (e && process.contextIsolated) try {
        e.exposeInMainWorld(`__electronLog`, n)
      } catch {}
      typeof window == `object` ? window.__electronLog = n : __electronLog = n
    }
  })),
  ue = e.t(((e, t) => {
    var n = require(`fs`),
      r = require(`os`),
      i = require(`path`),
      a = le(),
      o = !1,
      s = !1;
    t.exports = {
      initialize({
        externalApi: e,
        getSessions: t,
        includeFutureSession: n,
        logger: r,
        preload: i = !0,
        spyRendererConsole: a = !1
      }) {
        e.onAppReady(() => {
          try {
            i && c({
              externalApi: e,
              getSessions: t,
              includeFutureSession: n,
              logger: r,
              preloadOption: i
            }), a && l({
              externalApi: e,
              logger: r
            })
          } catch (e) {
            r.warn(e)
          }
        })
      }
    };

    function c({
      externalApi: e,
      getSessions: t,
      includeFutureSession: s,
      logger: c,
      preloadOption: l
    }) {
      let u = typeof l == `string` ? l : void 0;
      if (o) {
        c.warn(Error(`log.initialize({ preload }) already called`).stack);
        return
      }
      o = !0;
      try {
        u = i.resolve(__dirname, `../renderer/electron-log-preload.js`)
      } catch {}
      if (!u || !n.existsSync(u)) {
        u = i.join(e.getAppUserDataPath() || r.tmpdir(), `electron-log-preload.js`);
        let t = `
      try {
        (${a.toString()})(require('electron'));
      } catch(e) {
        console.error(e);
      }
    `;
        n.writeFileSync(u, t, `utf8`)
      }
      e.setPreloadFileForSessions({
        filePath: u,
        includeFutureSession: s,
        getSessions: t
      })
    }

    function l({
      externalApi: e,
      logger: t
    }) {
      if (s) {
        t.warn(Error(`log.initialize({ spyRendererConsole }) already called`).stack);
        return
      }
      s = !0;
      let n = [`debug`, `info`, `warn`, `error`];
      e.onEveryWebContentsEvent(`console-message`, (e, r, i) => {
        t.processMessage({
          data: [i],
          level: n[r],
          variables: {
            processType: `renderer`
          }
        })
      })
    }
  })),
  de = e.t(((e, t) => {
    t.exports = n;

    function n(e) {
      return Object.defineProperties(t, {
        defaultLabel: {
          value: ``,
          writable: !0
        },
        labelPadding: {
          value: !0,
          writable: !0
        },
        maxLabelLength: {
          value: 0,
          writable: !0
        },
        labelLength: {
          get() {
            switch (typeof t.labelPadding) {
              case `boolean`:
                return t.labelPadding ? t.maxLabelLength : 0;
              case `number`:
                return t.labelPadding;
              default:
                return 0
            }
          }
        }
      });

      function t(n) {
        t.maxLabelLength = Math.max(t.maxLabelLength, n.length);
        let r = {};
        for (let t of e.levels) r[t] = (...r) => e.logData(r, {
          level: t,
          scope: n
        });
        return r.log = r.info, r
      }
    }
  })),
  fe = e.t(((e, t) => {
    t.exports = class {
      constructor({
        processMessage: e
      }) {
        this.processMessage = e, this.buffer = [], this.enabled = !1, this.begin = this.begin.bind(this), this.commit = this.commit.bind(this), this.reject = this.reject.bind(this)
      }
      addMessage(e) {
        this.buffer.push(e)
      }
      begin() {
        this.enabled = []
      }
      commit() {
        this.enabled = !1, this.buffer.forEach(e => this.processMessage(e)), this.buffer = []
      }
      reject() {
        this.enabled = !1, this.buffer = []
      }
    }
  })),
  pe = e.t(((e, t) => {
    var n = de(),
      r = fe();
    t.exports = class e {
      static instances = {};
      dependencies = {};
      errorHandler = null;
      eventLogger = null;
      functions = {};
      hooks = [];
      isDev = !1;
      levels = null;
      logId = null;
      scope = null;
      transports = {};
      variables = {};
      constructor({
        allowUnknownLevel: t = !1,
        dependencies: i = {},
        errorHandler: a,
        eventLogger: o,
        initializeFn: s,
        isDev: c = !1,
        levels: l = [`error`, `warn`, `info`, `verbose`, `debug`, `silly`],
        logId: u,
        transportFactories: d = {},
        variables: f
      } = {}) {
        this.addLevel = this.addLevel.bind(this), this.create = this.create.bind(this), this.initialize = this.initialize.bind(this), this.logData = this.logData.bind(this), this.processMessage = this.processMessage.bind(this), this.allowUnknownLevel = t, this.buffering = new r(this), this.dependencies = i, this.initializeFn = s, this.isDev = c, this.levels = l, this.logId = u, this.scope = n(this), this.transportFactories = d, this.variables = f || {};
        for (let e of this.levels) this.addLevel(e, !1);
        this.log = this.info, this.functions.log = this.log, this.errorHandler = a, a?.setOptions({
          ...i,
          logFn: this.error
        }), this.eventLogger = o, o?.setOptions({
          ...i,
          logger: this
        });
        for (let [e, t] of Object.entries(d)) this.transports[e] = t(this, i);
        e.instances[u] = this
      }
      static getInstance({
        logId: e
      }) {
        return this.instances[e] || this.instances.default
      }
      addLevel(e, t = this.levels.length) {
        t !== !1 && this.levels.splice(t, 0, e), this[e] = (...t) => this.logData(t, {
          level: e
        }), this.functions[e] = this[e]
      }
      catchErrors(e) {
        return this.processMessage({
          data: [`log.catchErrors is deprecated. Use log.errorHandler instead`],
          level: `warn`
        }, {
          transports: [`console`]
        }), this.errorHandler.startCatching(e)
      }
      create(t) {
        return typeof t == `string` && (t = {
          logId: t
        }), new e({
          dependencies: this.dependencies,
          errorHandler: this.errorHandler,
          initializeFn: this.initializeFn,
          isDev: this.isDev,
          transportFactories: this.transportFactories,
          variables: {
            ...this.variables
          },
          ...t
        })
      }
      compareLevels(e, t, n = this.levels) {
        let r = n.indexOf(e),
          i = n.indexOf(t);
        return i === -1 || r === -1 ? !0 : i <= r
      }
      initialize(e = {}) {
        this.initializeFn({
          logger: this,
          ...this.dependencies,
          ...e
        })
      }
      logData(e, t = {}) {
        this.buffering.enabled ? this.buffering.addMessage({
          data: e,
          date: new Date,
          ...t
        }) : this.processMessage({
          data: e,
          ...t
        })
      }
      processMessage(e, {
        transports: t = this.transports
      } = {}) {
        if (e.cmd === `errorHandler`) {
          this.errorHandler.handle(e.error, {
            errorName: e.errorName,
            processType: `renderer`,
            showDialog: !!e.showDialog
          });
          return
        }
        let n = e.level;
        this.allowUnknownLevel || (n = this.levels.includes(e.level) ? e.level : `info`);
        let r = {
          date: new Date,
          logId: this.logId,
          ...e,
          level: n,
          variables: {
            ...this.variables,
            ...e.variables
          }
        };
        for (let [n, i] of this.transportEntries(t))
          if (!(typeof i != `function` || i.level === !1) && this.compareLevels(i.level, e.level)) try {
            let e = this.hooks.reduce((e, t) => e && t(e, i, n), r);
            e && i({
              ...e,
              data: [...e.data]
            })
          } catch (e) {
            this.processInternalErrorFn(e)
          }
      }
      processInternalErrorFn(e) {}
      transportEntries(e = this.transports) {
        return (Array.isArray(e) ? e : Object.entries(e)).map(e => {
          switch (typeof e) {
            case `string`:
              return this.transports[e] ? [e, this.transports[e]] : null;
            case `function`:
              return [e.name, e];
            default:
              return Array.isArray(e) ? e : null
          }
        }).filter(Boolean)
      }
    }
  })),
  me = e.t(((e, t) => {
    var n = class {
      externalApi = void 0;
      isActive = !1;
      logFn = void 0;
      onError = void 0;
      showDialog = !0;
      constructor({
        externalApi: e,
        logFn: t = void 0,
        onError: n = void 0,
        showDialog: r = void 0
      } = {}) {
        this.createIssue = this.createIssue.bind(this), this.handleError = this.handleError.bind(this), this.handleRejection = this.handleRejection.bind(this), this.setOptions({
          externalApi: e,
          logFn: t,
          onError: n,
          showDialog: r
        }), this.startCatching = this.startCatching.bind(this), this.stopCatching = this.stopCatching.bind(this)
      }
      handle(e, {
        logFn: t = this.logFn,
        onError: n = this.onError,
        processType: i = `browser`,
        showDialog: a = this.showDialog,
        errorName: o = ``
      } = {}) {
        e = r(e);
        try {
          if (typeof n == `function`) {
            let t = this.externalApi?.getVersions() || {},
              r = this.createIssue;
            if (n({
                createIssue: r,
                error: e,
                errorName: o,
                processType: i,
                versions: t
              }) === !1) return
          }
          o ? t(o, e) : t(e), a && !o.includes(`rejection`) && this.externalApi && this.externalApi.showErrorBox(`A JavaScript error occurred in the ${i} process`, e.stack)
        } catch {
          console.error(e)
        }
      }
      setOptions({
        externalApi: e,
        logFn: t,
        onError: n,
        showDialog: r
      }) {
        typeof e == `object` && (this.externalApi = e), typeof t == `function` && (this.logFn = t), typeof n == `function` && (this.onError = n), typeof r == `boolean` && (this.showDialog = r)
      }
      startCatching({
        onError: e,
        showDialog: t
      } = {}) {
        this.isActive || (this.isActive = !0, this.setOptions({
          onError: e,
          showDialog: t
        }), process.on(`uncaughtException`, this.handleError), process.on(`unhandledRejection`, this.handleRejection))
      }
      stopCatching() {
        this.isActive = !1, process.removeListener(`uncaughtException`, this.handleError), process.removeListener(`unhandledRejection`, this.handleRejection)
      }
      createIssue(e, t) {
        this.externalApi?.openUrl(`${e}?${new URLSearchParams(t).toString()}`)
      }
      handleError(e) {
        this.handle(e, {
          errorName: `Unhandled`
        })
      }
      handleRejection(e) {
        let t = e instanceof Error ? e : Error(JSON.stringify(e));
        this.handle(t, {
          errorName: `Unhandled rejection`
        })
      }
    };

    function r(e) {
      if (e instanceof Error) return e;
      if (e && typeof e == `object`) {
        if (e.message) return Object.assign(Error(e.message), e);
        try {
          return Error(JSON.stringify(e))
        } catch (t) {
          return Error(`Couldn't normalize error ${String(e)}: ${t}`)
        }
      }
      return Error(`Can't normalize error ${String(e)}`)
    }
    t.exports = n
  })),
  he = e.t(((e, t) => {
    t.exports = class {
      disposers = [];
      format = `{eventSource}#{eventName}:`;
      formatters = {
        app: {
          "certificate-error": ({
            args: e
          }) => this.arrayToObject(e.slice(1, 4), [`url`, `error`, `certificate`]),
          "child-process-gone": ({
            args: e
          }) => e.length === 1 ? e[0] : e,
          "render-process-gone": ({
            args: [e, t]
          }) => t && typeof t == `object` ? {
            ...t,
            ...this.getWebContentsDetails(e)
          } : []
        },
        webContents: {
          "console-message": ({
            args: [e, t, n, r]
          }) => {
            if (!(e < 3)) return {
              message: t,
              source: `${r}:${n}`
            }
          },
          "did-fail-load": ({
            args: e
          }) => this.arrayToObject(e, [`errorCode`, `errorDescription`, `validatedURL`, `isMainFrame`, `frameProcessId`, `frameRoutingId`]),
          "did-fail-provisional-load": ({
            args: e
          }) => this.arrayToObject(e, [`errorCode`, `errorDescription`, `validatedURL`, `isMainFrame`, `frameProcessId`, `frameRoutingId`]),
          "plugin-crashed": ({
            args: e
          }) => this.arrayToObject(e, [`name`, `version`]),
          "preload-error": ({
            args: e
          }) => this.arrayToObject(e, [`preloadPath`, `error`])
        }
      };
      events = {
        app: {
          "certificate-error": !0,
          "child-process-gone": !0,
          "render-process-gone": !0
        },
        webContents: {
          "did-fail-load": !0,
          "did-fail-provisional-load": !0,
          "plugin-crashed": !0,
          "preload-error": !0,
          unresponsive: !0
        }
      };
      externalApi = void 0;
      level = `error`;
      scope = ``;
      constructor(e = {}) {
        this.setOptions(e)
      }
      setOptions({
        events: e,
        externalApi: t,
        level: n,
        logger: r,
        format: i,
        formatters: a,
        scope: o
      }) {
        typeof e == `object` && (this.events = e), typeof t == `object` && (this.externalApi = t), typeof n == `string` && (this.level = n), typeof r == `object` && (this.logger = r), (typeof i == `string` || typeof i == `function`) && (this.format = i), typeof a == `object` && (this.formatters = a), typeof o == `string` && (this.scope = o)
      }
      startLogging(e = {}) {
        this.setOptions(e), this.disposeListeners();
        for (let e of this.getEventNames(this.events.app)) this.disposers.push(this.externalApi.onAppEvent(e, (...t) => {
          this.handleEvent({
            eventSource: `app`,
            eventName: e,
            handlerArgs: t
          })
        }));
        for (let e of this.getEventNames(this.events.webContents)) this.disposers.push(this.externalApi.onEveryWebContentsEvent(e, (...t) => {
          this.handleEvent({
            eventSource: `webContents`,
            eventName: e,
            handlerArgs: t
          })
        }))
      }
      stopLogging() {
        this.disposeListeners()
      }
      arrayToObject(e, t) {
        let n = {};
        return t.forEach((t, r) => {
          n[t] = e[r]
        }), e.length > t.length && (n.unknownArgs = e.slice(t.length)), n
      }
      disposeListeners() {
        this.disposers.forEach(e => e()), this.disposers = []
      }
      formatEventLog({
        eventName: e,
        eventSource: t,
        handlerArgs: n
      }) {
        let [r, ...i] = n;
        if (typeof this.format == `function`) return this.format({
          args: i,
          event: r,
          eventName: e,
          eventSource: t
        });
        let a = this.formatters[t]?.[e],
          o = i;
        if (typeof a == `function` && (o = a({
            args: i,
            event: r,
            eventName: e,
            eventSource: t
          })), !o) return;
        let s = {};
        return Array.isArray(o) ? s.args = o : typeof o == `object` && Object.assign(s, o), t === `webContents` && Object.assign(s, this.getWebContentsDetails(r?.sender)), [this.format.replace(`{eventSource}`, t === `app` ? `App` : `WebContents`).replace(`{eventName}`, e), s]
      }
      getEventNames(e) {
        return !e || typeof e != `object` ? [] : Object.entries(e).filter(([e, t]) => t).map(([e]) => e)
      }
      getWebContentsDetails(e) {
        if (!e?.loadURL) return {};
        try {
          return {
            webContents: {
              id: e.id,
              url: e.getURL()
            }
          }
        } catch {
          return {}
        }
      }
      handleEvent({
        eventName: e,
        eventSource: t,
        handlerArgs: n
      }) {
        let r = this.formatEventLog({
          eventName: e,
          eventSource: t,
          handlerArgs: n
        });
        r && (this.scope ? this.logger.scope(this.scope) : this.logger)?.[this.level]?.(...r)
      }
    }
  })),
  G = e.t(((e, t) => {
    t.exports = {
      transform: n
    };

    function n({
      logger: e,
      message: t,
      transport: n,
      initialData: r = t?.data || [],
      transforms: i = n?.transforms
    }) {
      return i.reduce((r, i) => typeof i == `function` ? i({
        data: r,
        logger: e,
        message: t,
        transport: n
      }) : r, r)
    }
  })),
  ge = e.t(((e, t) => {
    var {
      transform: n
    } = G();
    t.exports = {
      concatFirstStringElements: r,
      formatScope: a,
      formatText: s,
      formatVariables: o,
      timeZoneFromOffset: i,
      format({
        message: e,
        logger: t,
        transport: r,
        data: i = e?.data
      }) {
        switch (typeof r.format) {
          case `string`:
            return n({
              message: e,
              logger: t,
              transforms: [o, a, s],
              transport: r,
              initialData: [r.format, ...i]
            });
          case `function`:
            return r.format({
              data: i,
              level: e?.level || `info`,
              logger: t,
              message: e,
              transport: r
            });
          default:
            return i
        }
      }
    };

    function r({
      data: e
    }) {
      return typeof e[0] != `string` || typeof e[1] != `string` || e[0].match(/%[1cdfiOos]/) ? e : [`${e[0]} ${e[1]}`, ...e.slice(2)]
    }

    function i(e) {
      let t = Math.abs(e);
      return `${e>0?`-`:`+`}${Math.floor(t/60).toString().padStart(2,`0`)}:${(t%60).toString().padStart(2,`0`)}`
    }

    function a({
      data: e,
      logger: t,
      message: n
    }) {
      let {
        defaultLabel: r,
        labelLength: i
      } = t?.scope || {}, a = e[0], o = n.scope;
      o ||= r;
      let s;
      return s = o === `` ? i > 0 ? ``.padEnd(i + 3) : `` : typeof o == `string` ? ` (${o})`.padEnd(i + 3) : ``, e[0] = a.replace(`{scope}`, s), e
    }

    function o({
      data: e,
      message: t
    }) {
      let n = e[0];
      if (typeof n != `string`) return e;
      n = n.replace(`{level}]`, `${t.level}]`.padEnd(6, ` `));
      let r = t.date || new Date;
      return e[0] = n.replace(/\{(\w+)}/g, (e, n) => {
        switch (n) {
          case `level`:
            return t.level || `info`;
          case `logId`:
            return t.logId;
          case `y`:
            return r.getFullYear().toString(10);
          case `m`:
            return (r.getMonth() + 1).toString(10).padStart(2, `0`);
          case `d`:
            return r.getDate().toString(10).padStart(2, `0`);
          case `h`:
            return r.getHours().toString(10).padStart(2, `0`);
          case `i`:
            return r.getMinutes().toString(10).padStart(2, `0`);
          case `s`:
            return r.getSeconds().toString(10).padStart(2, `0`);
          case `ms`:
            return r.getMilliseconds().toString(10).padStart(3, `0`);
          case `z`:
            return i(r.getTimezoneOffset());
          case `iso`:
            return r.toISOString();
          default:
            return t.variables?.[n] || e
        }
      }).trim(), e
    }

    function s({
      data: e
    }) {
      let t = e[0];
      if (typeof t != `string`) return e;
      if (t.lastIndexOf(`{text}`) === t.length - 6) return e[0] = t.replace(/\s?{text}/, ``), e[0] === `` && e.shift(), e;
      let n = t.split(`{text}`),
        r = [];
      return n[0] !== `` && r.push(n[0]), r = r.concat(e.slice(1)), n[1] !== `` && r.push(n[1]), r
    }
  })),
  K = e.t(((e, t) => {
    var n = require(`util`);
    t.exports = {
      serialize: i,
      maxDepth({
        data: e,
        transport: n,
        depth: r = n?.depth ?? 6
      }) {
        if (!e) return e;
        if (r < 1) return Array.isArray(e) ? `[array]` : typeof e == `object` && e ? `[object]` : e;
        if (Array.isArray(e)) return e.map(e => t.exports.maxDepth({
          data: e,
          depth: r - 1
        }));
        if (typeof e != `object` || e && typeof e.toISOString == `function`) return e;
        if (e === null) return null;
        if (e instanceof Error) return e;
        let i = {};
        for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && (i[n] = t.exports.maxDepth({
          data: e[n],
          depth: r - 1
        }));
        return i
      },
      toJSON({
        data: e
      }) {
        return JSON.parse(JSON.stringify(e, r()))
      },
      toString({
        data: e,
        transport: t
      }) {
        let i = t?.inspectOptions || {},
          a = e.map(e => {
            if (e !== void 0) try {
              let t = JSON.stringify(e, r(), `  `);
              return t === void 0 ? void 0 : JSON.parse(t)
            } catch {
              return e
            }
          });
        return n.formatWithOptions(i, ...a)
      }
    };

    function r(e = {}) {
      let t = new WeakSet;
      return function(n, r) {
        if (typeof r == `object` && r) {
          if (t.has(r)) return;
          t.add(r)
        }
        return i(n, r, e)
      }
    }

    function i(e, t, n = {}) {
      let r = n?.serializeMapAndSet !== !1;
      return t instanceof Error ? t.stack : t && (typeof t == `function` ? `[function] ${t.toString()}` : t instanceof Date ? t.toISOString() : r && t instanceof Map && Object.fromEntries ? Object.fromEntries(t) : r && t instanceof Set && Array.from ? Array.from(t) : t)
    }
  })),
  _e = e.t(((e, t) => {
    t.exports = {
      transformStyles: a,
      applyAnsiStyles({
        data: e
      }) {
        return a(e, r, i)
      },
      removeStyles({
        data: e
      }) {
        return a(e, () => ``)
      }
    };
    var n = {
      unset: `\x1B[0m`,
      black: `\x1B[30m`,
      red: `\x1B[31m`,
      green: `\x1B[32m`,
      yellow: `\x1B[33m`,
      blue: `\x1B[34m`,
      magenta: `\x1B[35m`,
      cyan: `\x1B[36m`,
      white: `\x1B[37m`,
      gray: `\x1B[90m`
    };

    function r(e) {
      return n[e.replace(/color:\s*(\w+).*/, `$1`).toLowerCase()] || ``
    }

    function i(e) {
      return e + n.unset
    }

    function a(e, t, n) {
      let r = {};
      return e.reduce((e, i, a, o) => {
        if (r[a]) return e;
        if (typeof i == `string`) {
          let e = a,
            s = !1;
          i = i.replace(/%[1cdfiOos]/g, n => {
            if (e += 1, n !== `%c`) return n;
            let a = o[e];
            return typeof a == `string` ? (r[e] = !0, s = !0, t(a, i)) : n
          }), s && n && (i = n(i))
        }
        return e.push(i), e
      }, [])
    }
  })),
  ve = e.t(((e, t) => {
    var {
      concatFirstStringElements: n,
      format: r
    } = ge(), {
      maxDepth: i,
      toJSON: a
    } = K(), {
      applyAnsiStyles: o,
      removeStyles: s
    } = _e(), {
      transform: c
    } = G(), l = {
      error: console.error,
      warn: console.warn,
      info: console.info,
      verbose: console.info,
      debug: console.debug,
      silly: console.debug,
      log: console.log
    };
    t.exports = d;
    var u = `%c{h}:{i}:{s}.{ms}{scope}%c ${process.platform===`win32`?`>`:`›`} {text}`;
    Object.assign(d, {
      DEFAULT_FORMAT: u
    });

    function d(e) {
      return Object.assign(t, {
        colorMap: {
          error: `red`,
          warn: `yellow`,
          info: `cyan`,
          verbose: `unset`,
          debug: `gray`,
          silly: `gray`,
          default: `unset`
        },
        format: u,
        level: `silly`,
        transforms: [f, r, m, n, i, a],
        useStyles: process.env.FORCE_STYLES,
        writeFn({
          message: e
        }) {
          (l[e.level] || l.info)(...e.data)
        }
      });

      function t(n) {
        let r = c({
          logger: e,
          message: n,
          transport: t
        });
        t.writeFn({
          message: {
            ...n,
            data: r
          }
        })
      }
    }

    function f({
      data: e,
      message: t,
      transport: n
    }) {
      return typeof n.format != `string` || !n.format.includes(`%c`) ? e : [`color:${h(t.level,n)}`, `color:unset`, ...e]
    }

    function p(e, t) {
      if (typeof e == `boolean`) return e;
      let n = t === `error` || t === `warn` ? process.stderr : process.stdout;
      return n && n.isTTY
    }

    function m(e) {
      let {
        message: t,
        transport: n
      } = e;
      return (p(n.useStyles, t.level) ? o : s)(e)
    }

    function h(e, t) {
      return t.colorMap[e] || t.colorMap.default
    }
  })),
  ye = e.t(((e, t) => {
    var n = require(`events`),
      r = require(`fs`),
      i = require(`os`);
    t.exports = class extends n {
      asyncWriteQueue = [];
      bytesWritten = 0;
      hasActiveAsyncWriting = !1;
      path = null;
      initialSize = void 0;
      writeOptions = null;
      writeAsync = !1;
      constructor({
        path: e,
        writeOptions: t = {
          encoding: `utf8`,
          flag: `a`,
          mode: 438
        },
        writeAsync: n = !1
      }) {
        super(), this.path = e, this.writeOptions = t, this.writeAsync = n
      }
      get size() {
        return this.getSize()
      }
      clear() {
        try {
          return r.writeFileSync(this.path, ``, {
            mode: this.writeOptions.mode,
            flag: `w`
          }), this.reset(), !0
        } catch (e) {
          return e.code === `ENOENT` ? !0 : (this.emit(`error`, e, this), !1)
        }
      }
      crop(e) {
        try {
          let t = a(this.path, e || 4096);
          this.clear(), this.writeLine(`[log cropped]${i.EOL}${t}`)
        } catch (e) {
          this.emit(`error`, Error(`Couldn't crop file ${this.path}. ${e.message}`), this)
        }
      }
      getSize() {
        if (this.initialSize === void 0) try {
          this.initialSize = r.statSync(this.path).size
        } catch {
          this.initialSize = 0
        }
        return this.initialSize + this.bytesWritten
      }
      increaseBytesWrittenCounter(e) {
        this.bytesWritten += Buffer.byteLength(e, this.writeOptions.encoding)
      }
      isNull() {
        return !1
      }
      nextAsyncWrite() {
        let e = this;
        if (this.hasActiveAsyncWriting || this.asyncWriteQueue.length === 0) return;
        let t = this.asyncWriteQueue.join(``);
        this.asyncWriteQueue = [], this.hasActiveAsyncWriting = !0, r.writeFile(this.path, t, this.writeOptions, n => {
          e.hasActiveAsyncWriting = !1, n ? e.emit(`error`, Error(`Couldn't write to ${e.path}. ${n.message}`), this) : e.increaseBytesWrittenCounter(t), e.nextAsyncWrite()
        })
      }
      reset() {
        this.initialSize = void 0, this.bytesWritten = 0
      }
      toString() {
        return this.path
      }
      writeLine(e) {
        if (e += i.EOL, this.writeAsync) {
          this.asyncWriteQueue.push(e), this.nextAsyncWrite();
          return
        }
        try {
          r.writeFileSync(this.path, e, this.writeOptions), this.increaseBytesWrittenCounter(e)
        } catch (e) {
          this.emit(`error`, Error(`Couldn't write to ${this.path}. ${e.message}`), this)
        }
      }
    };

    function a(e, t) {
      let n = Buffer.alloc(t),
        i = r.statSync(e),
        a = Math.min(i.size, t),
        o = Math.max(0, i.size - t),
        s = r.openSync(e, `r`),
        c = r.readSync(s, n, 0, a, o);
      return r.closeSync(s), n.toString(`utf8`, 0, c)
    }
  })),
  be = e.t(((e, t) => {
    var n = ye();
    t.exports = class extends n {
      clear() {}
      crop() {}
      getSize() {
        return 0
      }
      isNull() {
        return !0
      }
      writeLine() {}
    }
  })),
  xe = e.t(((e, t) => {
    var n = require(`events`),
      r = require(`fs`),
      i = require(`path`),
      a = ye(),
      o = be();
    t.exports = class extends n {
      store = {};
      constructor() {
        super(), this.emitError = this.emitError.bind(this)
      }
      provide({
        filePath: e,
        writeOptions: t = {},
        writeAsync: n = !1
      }) {
        let r;
        try {
          if (e = i.resolve(e), this.store[e]) return this.store[e];
          r = this.createFile({
            filePath: e,
            writeOptions: t,
            writeAsync: n
          })
        } catch (t) {
          r = new o({
            path: e
          }), this.emitError(t, r)
        }
        return r.on(`error`, this.emitError), this.store[e] = r, r
      }
      createFile({
        filePath: e,
        writeOptions: t,
        writeAsync: n
      }) {
        return this.testFileWriting({
          filePath: e,
          writeOptions: t
        }), new a({
          path: e,
          writeOptions: t,
          writeAsync: n
        })
      }
      emitError(e, t) {
        this.emit(`error`, e, t)
      }
      testFileWriting({
        filePath: e,
        writeOptions: t
      }) {
        r.mkdirSync(i.dirname(e), {
          recursive: !0
        }), r.writeFileSync(e, ``, {
          flag: `a`,
          mode: t.mode
        })
      }
    }
  })),
  Se = e.t(((e, t) => {
    var n = require(`fs`),
      r = require(`os`),
      i = require(`path`),
      a = xe(),
      {
        transform: o
      } = G(),
      {
        removeStyles: s
      } = _e(),
      {
        format: c,
        concatFirstStringElements: l
      } = ge(),
      {
        toString: u
      } = K();
    t.exports = f;
    var d = new a;

    function f(e, {
      registry: t = d,
      externalApi: a
    } = {}) {
      let f;
      return t.listenerCount(`error`) < 1 && t.on(`error`, (e, t) => {
        g(`Can't write to ${t}`, e)
      }), Object.assign(m, {
        fileName: p(e.variables.processType),
        format: `[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}]{scope} {text}`,
        getFile: _,
        inspectOptions: {
          depth: 5
        },
        level: `silly`,
        maxSize: 1024 ** 2,
        readAllLogs: v,
        sync: !0,
        transforms: [s, c, l, u],
        writeOptions: {
          flag: `a`,
          mode: 438,
          encoding: `utf8`
        },
        archiveLogFn(e) {
          let t = e.toString(),
            r = i.parse(t);
          try {
            n.renameSync(t, i.join(r.dir, `${r.name}.old${r.ext}`))
          } catch (t) {
            g(`Could not rotate log`, t);
            let n = Math.round(m.maxSize / 4);
            e.crop(Math.min(n, 256 * 1024))
          }
        },
        resolvePathFn(e) {
          return i.join(e.libraryDefaultDir, e.fileName)
        },
        setAppName(t) {
          e.dependencies.externalApi.setAppName(t)
        }
      });

      function m(t) {
        let n = _(t);
        m.maxSize > 0 && n.size > m.maxSize && (m.archiveLogFn(n), n.reset());
        let r = o({
          logger: e,
          message: t,
          transport: m
        });
        n.writeLine(r)
      }

      function h() {
        f || (f = Object.create(Object.prototype, {
          ...Object.getOwnPropertyDescriptors(a.getPathVariables()),
          fileName: {
            get() {
              return m.fileName
            },
            enumerable: !0
          }
        }), typeof m.archiveLog == `function` && (m.archiveLogFn = m.archiveLog, g(`archiveLog is deprecated. Use archiveLogFn instead`)), typeof m.resolvePath == `function` && (m.resolvePathFn = m.resolvePath, g(`resolvePath is deprecated. Use resolvePathFn instead`)))
      }

      function g(t, n = null, r = `error`) {
        let i = [`electron-log.transports.file: ${t}`];
        n && i.push(n), e.transports.console({
          data: i,
          date: new Date,
          level: r
        })
      }

      function _(e) {
        h();
        let n = m.resolvePathFn(f, e);
        return t.provide({
          filePath: n,
          writeAsync: !m.sync,
          writeOptions: m.writeOptions
        })
      }

      function v({
        fileFilter: e = e => e.endsWith(`.log`)
      } = {}) {
        h();
        let t = i.dirname(m.resolvePathFn(f));
        return n.existsSync(t) ? n.readdirSync(t).map(e => i.join(t, e)).filter(e).map(e => {
          try {
            return {
              path: e,
              lines: n.readFileSync(e, `utf8`).split(r.EOL)
            }
          } catch {
            return null
          }
        }).filter(Boolean) : []
      }
    }

    function p(e = process.type) {
      switch (e) {
        case `renderer`:
          return `renderer.log`;
        case `worker`:
          return `worker.log`;
        default:
          return `main.log`
      }
    }
  })),
  Ce = e.t(((e, t) => {
    var {
      maxDepth: n,
      toJSON: r
    } = K(), {
      transform: i
    } = G();
    t.exports = a;

    function a(e, {
      externalApi: t
    }) {
      return Object.assign(a, {
        depth: 3,
        eventId: `__ELECTRON_LOG_IPC__`,
        level: e.isDev ? `silly` : !1,
        transforms: [r, n]
      }), t?.isElectron() ? a : void 0;

      function a(n) {
        n?.variables?.processType !== `renderer` && t?.sendIpc(a.eventId, {
          ...n,
          data: i({
            logger: e,
            message: n,
            transport: a
          })
        })
      }
    }
  })),
  we = e.t(((e, t) => {
    var n = require(`http`),
      r = require(`https`),
      {
        transform: i
      } = G(),
      {
        removeStyles: a
      } = _e(),
      {
        toJSON: o,
        maxDepth: s
      } = K();
    t.exports = c;

    function c(e) {
      return Object.assign(t, {
        client: {
          name: `electron-application`
        },
        depth: 6,
        level: !1,
        requestOptions: {},
        transforms: [a, o, s],
        makeBodyFn({
          message: e
        }) {
          return JSON.stringify({
            client: t.client,
            data: e.data,
            date: e.date.getTime(),
            level: e.level,
            scope: e.scope,
            variables: e.variables
          })
        },
        processErrorFn({
          error: n
        }) {
          e.processMessage({
            data: [`electron-log: can't POST ${t.url}`, n],
            level: `warn`
          }, {
            transports: [`console`, `file`]
          })
        },
        sendRequestFn({
          serverUrl: e,
          requestOptions: t,
          body: i
        }) {
          let a = (e.startsWith(`https:`) ? r : n).request(e, {
            method: `POST`,
            ...t,
            headers: {
              "Content-Type": `application/json`,
              "Content-Length": i.length,
              ...t.headers
            }
          });
          return a.write(i), a.end(), a
        }
      });

      function t(n) {
        if (!t.url) return;
        let r = t.makeBodyFn({
            logger: e,
            message: {
              ...n,
              data: i({
                logger: e,
                message: n,
                transport: t
              })
            },
            transport: t
          }),
          a = t.sendRequestFn({
            serverUrl: t.url,
            requestOptions: t.requestOptions,
            body: Buffer.from(r, `utf8`)
          });
        a.on(`error`, r => t.processErrorFn({
          error: r,
          logger: e,
          message: n,
          request: a,
          transport: t
        }))
      }
    }
  })),
  Te = e.t(((e, t) => {
    var n = pe(),
      r = me(),
      i = he(),
      a = ve(),
      o = Se(),
      s = Ce(),
      c = we();
    t.exports = l;

    function l({
      dependencies: e,
      initializeFn: t
    }) {
      let l = new n({
        dependencies: e,
        errorHandler: new r,
        eventLogger: new i,
        initializeFn: t,
        isDev: e.externalApi?.isDev(),
        logId: `default`,
        transportFactories: {
          console: a,
          file: o,
          ipc: s,
          remote: c
        },
        variables: {
          processType: `main`
        }
      });
      return l.default = l, l.Logger = n, l.processInternalErrorFn = e => {
        l.transports.console.writeFn({
          message: {
            data: [`Unhandled electron-log error`, e],
            level: `error`
          }
        })
      }, l
    }
  })),
  Ee = e.t(((e, t) => {
    var n = require(`electron`),
      r = ce(),
      {
        initialize: i
      } = ue(),
      a = Te(),
      o = new r({
        electron: n
      }),
      s = a({
        dependencies: {
          externalApi: o
        },
        initializeFn: i
      });
    t.exports = s, o.onIpc(`__ELECTRON_LOG__`, (e, t) => {
      t.scope && s.Logger.getInstance(t).scope(t.scope);
      let n = new Date(t.date);
      c({
        ...t,
        date: n.getTime() ? n : new Date
      })
    }), o.onIpcInvoke(`__ELECTRON_LOG__`, (e, {
      cmd: t = ``,
      logId: n
    }) => {
      switch (t) {
        case `getOptions`:
          return {
            levels: s.Logger.getInstance({
              logId: n
            }).levels, logId: n
          };
        default:
          return c({
            data: [`Unknown cmd '${t}'`],
            level: `error`
          }), {}
      }
    });

    function c(e) {
      s.Logger.getInstance(e)?.processMessage(e)
    }
  })),
  De = e.t(((e, t) => {
    t.exports = Ee()
  })),
  q = e.n(De()),
  J = n.join(t.app.getPath(`userData`), `session.json`);

function Oe() {
  let e = new _(`https://airfieldz.fr`);
  t.ipcMain.handle(`auth:login`, async (t, n, r, i) => {
    try {
      let t = await e.auth(n, r, i);
      let sessionData = {
        ...t,
        savedEmail: n,
        savedPassword: r
      };
      return o.writeFileSync(J, JSON.stringify(sessionData)), {
        success: !0,
        account: t
      }
    } catch (e) {
      return e.code === `TWOFA_CODE_REQUIRED` ? {
        success: !1,
        twoFA: !0
      } : (q.default.error(`Failed to login:`, e), {
        success: !1,
        error: e.message ?? `Unknown error`
      })
    }
  }), t.ipcMain.handle(`auth:refresh`, async () => {
    if (!o.existsSync(J)) return {
      success: !1
    };
    try {
      let t = o.readFileSync(J, `utf-8`),
        n = JSON.parse(t);
      if (!n?.uuid) return {
        success: !1
      };
      let r = await e.verify(n);
      let refreshData = {
        ...r,
        savedEmail: n.savedEmail,
        savedPassword: n.savedPassword
      };
      return o.writeFileSync(J, JSON.stringify(refreshData)), {
        success: !0,
        account: r
      }
    } catch (err) {
      q.default.error(`Failed to refresh session:`, err);
      try {
        let saved = JSON.parse(o.readFileSync(J, `utf-8`));
        if (saved?.savedEmail && saved?.savedPassword) {
          q.default.log(`Attempting auto re-login with saved credentials...`);
          let newLogin = await e.auth(saved.savedEmail, saved.savedPassword);
          let sessionData = {
            ...newLogin,
            savedEmail: saved.savedEmail,
            savedPassword: saved.savedPassword
          };
          return o.writeFileSync(J, JSON.stringify(sessionData)), {
            success: !0,
            account: newLogin
          }
        }
      } catch (relogErr) {
        q.default.error(`Auto re-login failed:`, relogErr)
      }
      o.unlinkSync(J);
      return {
        success: !1,
        error: err.message
      }
    }
  }), t.ipcMain.handle(`auth:logout`, async () => {
    try {
      if (o.existsSync(J)) {
        let t = o.readFileSync(J, `utf-8`),
          n = JSON.parse(t);
        await e.logout(n), o.unlinkSync(J)
      }
      return {
        success: !0
      }
    } catch (e) {
      return q.default.error(`Failed to logout:`, e), o.existsSync(J) && o.unlinkSync(J), {
        success: !0
      }
    }
  })
}
var Y = `https://launcher.airfieldz.fr`;

function ke(e) {
  t.ipcMain.handle(`game:launch`, (n, r) => {
    let {
      account: i,
      settings: a,
      profileSlug: o
    } = r, s = a.java === `system` ? {
      install: `manual`,
      absolutePath: `java`
    } : {
      install: `auto`
    };
    q.default.log(`Launching`), console.log(a.memory);
    let c = new ie({
      url: Y,
      root: `airfieldz`,
      profile: {
        slug: o
      },
      account: i,
      cleaning: {
        enabled: !0,
        ignored: [`crash-reports/`, `logs/`, `resourcepacks/`, `resources/`, `saves/`, `shaderpacks/`, `config/`, `options.txt`, `optionsof.txt`, `servers.dat`, `hotbar.nbt`]
      },
      java: s,
      memory: {
        min: a.memory.min * 1024,
        max: a.memory.max * 1024
      },
      window: {
        width: a.resolution.width,
        height: a.resolution.height,
        fullscreen: a.resolution.fullscreen
      }
    });
    c.on(`launch_compute_download`, () => {
      q.default.log(`Computing download...`), e.webContents.send(`game:launch_compute_download`)
    }), c.on(`launch_download`, t => {
      q.default.log(`Downloading ${t.total.amount} files (${t.total.size} B).`), e.webContents.send(`game:launch_download`, t)
    }), c.on(`download_progress`, t => {
      e.webContents.send(`game:download_progress`, t)
    }), c.on(`download_error`, t => {
      q.default.error(`Error downloading ${t.filename}: ${t.message}`), e.webContents.send(`game:download_error`, t)
    }), c.on(`download_end`, t => {
      q.default.log(`Downloaded ${t.downloaded.amount} files.`), e.webContents.send(`game:download_end`, t)
    }), c.on(`launch_install_loader`, t => {
      q.default.log(`Installing loader ${t.type} ${t.loaderVersion}...`), e.webContents.send(`game:launch_install_loader`, t)
    }), c.on(`launch_extract_natives`, () => {
      q.default.log(`Extracting natives...`), e.webContents.send(`game:launch_extract_natives`)
    }), c.on(`extract_progress`, t => {
      q.default.log(`Extracted ${t.filename}.`), e.webContents.send(`game:extract_progress`, t)
    }), c.on(`extract_end`, t => {
      q.default.log(`Extracted ${t.amount} files.`), e.webContents.send(`game:extract_end`, t)
    }), c.on(`launch_copy_assets`, () => {
      q.default.log(`Copying assets...`), e.webContents.send(`game:launch_copy_assets`)
    }), c.on(`copy_progress`, t => {
      q.default.log(`Copied ${t.filename} to ${t.dest}.`), e.webContents.send(`game:copy_progress`, t)
    }), c.on(`copy_end`, t => {
      q.default.log(`Copied ${t.amount} files.`), e.webContents.send(`game:copy_end`, t)
    }), c.on(`launch_patch_loader`, () => {
      q.default.log(`Patching loader...`), e.webContents.send(`game:launch_patch_loader`)
    }), c.on(`patch_progress`, t => {
      e.webContents.send(`game:patch_progress`, t)
    }), c.on(`patch_error`, t => {
      q.default.error(`Error patching ${t.filename}: ${t.message}`), e.webContents.send(`game:patch_error`, t)
    }), c.on(`patch_end`, t => {
      q.default.log(`Patched ${t.amount} files.`), e.webContents.send(`game:patch_end`, t)
    }), c.on(`launch_check_java`, () => {
      q.default.log(`Checking Java...`), e.webContents.send(`game:launch_check_java`)
    }), c.on(`java_info`, t => {
      q.default.log(`Using Java ${t.version} ${t.arch}`), e.webContents.send(`game:java_info`, t)
    }), c.on(`launch_clean`, () => {
      q.default.log(`Cleaning game directory...`), e.webContents.send(`game:launch_clean`)
    }), c.on(`clean_progress`, t => {
      e.webContents.send(`game:clean_progress`, t)
    }), c.on(`clean_end`, t => {
      q.default.log(`Cleaned ${t.amount} files.`), e.webContents.send(`game:clean_end`, t)
    }), c.on(`launch_launch`, n => {
      q.default.log(`Launching Minecraft ${n.version} (${n.type}${n.loaderVersion?` ${n.loaderVersion}`:``})...`), e.webContents.send(`game:launch_launch`, n), a.launcherAction === `close` ? setTimeout(() => t.app.quit(), 5e3) : a.launcherAction === `hide` && setTimeout(() => e.minimize(), 5e3), e.webContents.send(`game:launched`)
    }), c.on(`launch_data`, t => {
      q.default.log(t), e.webContents.send(`game:launch_data`, t)
    }), c.on(`launch_close`, t => {
      q.default.log(`Closed with code ${t}.`), e.webContents.send(`game:launch_close`, t)
    }), c.on(`launch_debug`, t => {
      e.webContents.send(`game:launch_debug`, t)
    }), c.on(`patch_debug`, t => {
      e.webContents.send(`game:patch_debug`, t)
    });
    try {
      c.launch().catch(e => q.default.error(`[LAUNCH] Async error:`, e?.message ?? e))
    } catch (e) {
      q.default.error(`[LAUNCH] Sync error:`, e?.message ?? e)
    }
  })
}
var X = n.join(t.app.getPath(`userData`), `settings.json`),
  Z = {
    java: `bundled`,
    memory: {
      min: 1,
      max: 4
    },
    resolution: {
      width: 1280,
      height: 720,
      fullscreen: !1
    },
    launcherAction: `close`
  };

function Ae() {
  t.ipcMain.handle(`settings:get`, async () => {
    try {
      if (!o.existsSync(X)) return o.writeFileSync(X, JSON.stringify(Z, null, 2)), Z;
      let e = o.readFileSync(X, `utf-8`);
      return {
        ...Z,
        ...JSON.parse(e)
      }
    } catch (e) {
      return q.default.error(`Error reading settings:`, e), Z
    }
  }), t.ipcMain.handle(`settings:set`, async (e, t) => {
    try {
      return o.writeFileSync(X, JSON.stringify(t, null, 2)), !0
    } catch (e) {
      return q.default.error(`Error writing settings:`, e), !1
    }
  }), t.ipcMain.handle(`system:info`, async () => {
    let e = c.totalmem(),
      n = Math.round(e / 1024 / 1024 / 1024),
      {
        width: r,
        height: i
      } = t.screen.getPrimaryDisplay().workAreaSize;
    return {
      totalMem: n,
      resolution: {
        width: r,
        height: i
      },
      version: t.app.getVersion()
    }
  }), t.ipcMain.handle(`settings:pick_java`, async () => (await t.dialog.showOpenDialog({
    properties: [`openFile`],
    filters: [{
      name: `Java Executable`,
      extensions: [`exe`, `bin`, ``]
    }]
  })).filePaths[0] ?? null)
}

function je() {
  t.ipcMain.handle(`server:status`, async (e, t, n = 25565) => {
    try {
      return await new E(t, n, `modern`, 774).getStatus()
    } catch (e) {
      return q.default.error(`Failed to get server status:`, e), null
    }
  })
}

function Me() {
  t.ipcMain.handle(`news:get_news`, async () => {
    try {
      return await new S(Y).getNews()
    } catch (e) {
      return q.default.error(`Failed to fetch news:`, e), []
    }
  }), t.ipcMain.handle(`news:get_categories`, async () => {
    try {
      return await new S(Y).getCategories()
    } catch (e) {
      return q.default.error(`Failed to fetch news:`, e), []
    }
  })
}

function Ne() {
  t.ipcMain.handle(`background:get`, async () => {
    let e = new C(Y);
    try {
      return await e.getBackground()
    } catch (e) {
      return q.default.error(`Failed to fetch background:`, e), null
    }
  })
}

function Pe() {
  t.ipcMain.handle(`maintenance:get`, async () => {
    let e = new x(Y);
    try {
      let t = await e.getMaintenance();
      return t?.startTime && new Date(t.startTime) <= new Date ? t : null
    } catch (e) {
      return q.default.error(`Failed to fetch maintenance:`, e), null
    }
  })
}
var Q = null;

function Fe(e) {
  Q || (Q = new b(Y), Q.on(`download_progress`, t => {
    e.webContents.send(`bootstraps:download_progress`, t)
  }), Q.on(`download_end`, t => {
    e.webContents.send(`bootstraps:download_end`, t)
  }), Q.on(`bootstraps_error`, t => {
    e.webContents.send(`bootstraps:error`, t)
  })), t.ipcMain.handle(`bootstraps:check`, async () => {
    try {
      return await Q?.checkForUpdate()
    } catch (e) {
      return q.default.error(`Error checking for bootstraps update`, e), {
        updateAvailable: !1
      }
    }
  }), t.ipcMain.handle(`bootstraps:download`, async () => await Q?.download()), t.ipcMain.handle(`bootstraps:install`, async () => await Q?.runUpdate())
}

function Ie() {
  t.ipcMain.handle(`profiles:get`, async () => {
    let e = new ae(Y);
    try {
      let t = await e.getProfiles();
      return [t.find(e => e.isDefault), ...t.filter(e => !e.isDefault)]
    } catch (e) {
      return q.default.error(`Failed to fetch profiles:`, e), null
    }
  })
}
var Le = `AirfieldZ`,
  Re = `#121212`,
  $ = null;
process.env.VITE_DEV_SERVER_URL && t.app.setName(Le);

function ze() {
  t.nativeTheme.themeSource = `dark`, $ = new t.BrowserWindow({
    width: 1280,
    height: 720,
    minWidth: 1e3,
    minHeight: 700,
    title: Le,
    autoHideMenuBar: !0,
    backgroundColor: Re,
    show: !1,
    icon: n.default.join(__dirname, `../build/icon.png`),
    webPreferences: {
      preload: n.default.join(__dirname, `preload.js`),
      nodeIntegration: !1,
      contextIsolation: !0,
      devTools: !0
    }
  }), $.webContents.setWindowOpenHandler(({
    url: e
  }) => ((e.startsWith(`https:`) || e.startsWith(`http:`)) && t.shell.openExternal(e), {
    action: `deny`
  })), $.once(`ready-to-show`, () => {
    $?.show()
  }), process.env.VITE_DEV_SERVER_URL ? $.loadURL(process.env.VITE_DEV_SERVER_URL) : $.loadFile(n.default.join(__dirname, `../dist/index.html`))
}

function Be() {
  t.app.setAboutPanelOptions({
    applicationName: Le,
    applicationVersion: t.app.getVersion(),
    version: `Build 2026.1`,
    copyright: `Copyright © 2026 AirfieldZ`,
    credits: `Developed with EML Lib & Electron`,
    iconPath: n.default.join(__dirname, `../build/icon.png`)
  });
  let e = [...process.platform === `darwin` ? [{
      label: t.app.name,
      submenu: [{
        role: `about`
      }, {
        type: `separator`
      }, {
        role: `services`
      }, {
        type: `separator`
      }, {
        role: `hide`
      }, {
        role: `hideOthers`
      }, {
        role: `unhide`
      }, {
        type: `separator`
      }, {
        role: `quit`
      }]
    }] : [], {
      label: `File`,
      submenu: [{
        role: `close`
      }]
    }, {
      label: `View`,
      submenu: [{
        role: `reload`
      }, {
        role: `forceReload`
      }, {
        role: `toggleDevTools`
      }, {
        type: `separator`
      }, {
        role: `togglefullscreen`
      }]
    }],
    r = t.Menu.buildFromTemplate(e);
  t.Menu.setApplicationMenu(r)
}
t.app.whenReady().then(() => {
  q.default.initialize(), Be(), ze(), $ && (Oe($), Ie(), je(), Me(), Ne(), Pe(), Fe($), ke($), Ae())
}), t.app.on(`window-all-closed`, () => {
  t.app.quit()
});