import { PHPResponse as we, LatestSupportedPHPVersion as Le, loadPHPRuntime as me, FSHelpers as B, __private__dont__use as k } from "@php-wasm/universal";
import * as E from "comlink";
import { jspi as ye } from "wasm-feature-detect";
import { logger as b } from "@php-wasm/logger";
import { Semaphore as ge, joinPaths as se } from "@php-wasm/util";
import { journalFSEvents as Ke } from "@php-wasm/fs-journal";
function _t(s, e = void 0) {
  ie();
  const t = s instanceof Worker ? s : E.windowEndpoint(s, e), r = E.wrap(t), n = x(r);
  return new Proxy(n, {
    get: (i, _) => _ === "isConnected" ? async () => {
      for (; ; )
        try {
          await Ie(r.isConnected(), 200);
          break;
        } catch {
        }
    } : r[_]
  });
}
async function Ie(s, e) {
  return new Promise((t, r) => {
    setTimeout(r, e), s.then(t);
  });
}
function at(s, e) {
  ie();
  const t = Promise.resolve();
  let r, n;
  const i = new Promise((c, S) => {
    r = c, n = S;
  }), _ = x(s), a = new Proxy(_, {
    get: (c, S) => S === "isConnected" ? () => t : S === "isReady" ? () => i : S in c ? c[S] : e == null ? void 0 : e[S]
  });
  return E.expose(
    a,
    typeof window < "u" ? E.windowEndpoint(self.parent) : void 0
  ), [r, n, a];
}
let F = !1;
function ie() {
  if (F)
    return;
  F = !0, E.transferHandlers.set("EVENT", {
    canHandle: (t) => t instanceof CustomEvent,
    serialize: (t) => [
      {
        detail: t.detail
      },
      []
    ],
    deserialize: (t) => t
  }), E.transferHandlers.set("FUNCTION", {
    canHandle: (t) => typeof t == "function",
    serialize(t) {
      const { port1: r, port2: n } = new MessageChannel();
      return E.expose(t, r), [n, [n]];
    },
    deserialize(t) {
      return t.start(), E.wrap(t);
    }
  }), E.transferHandlers.set("PHPResponse", {
    canHandle: (t) => typeof t == "object" && t !== null && "headers" in t && "bytes" in t && "errors" in t && "exitCode" in t && "httpStatusCode" in t,
    serialize(t) {
      return [t.toRawData(), []];
    },
    deserialize(t) {
      return we.fromRawData(t);
    }
  });
  const s = E.transferHandlers.get("throw"), e = s == null ? void 0 : s.serialize;
  s.serialize = ({ value: t }) => {
    const r = e({ value: t });
    return t.response && (r[0].value.response = t.response), t.source && (r[0].value.source = t.source), r;
  };
}
function x(s) {
  return new Proxy(s, {
    get(e, t) {
      switch (typeof e[t]) {
        case "function":
          return (...r) => e[t](...r);
        case "object":
          return e[t] === null ? e[t] : x(e[t]);
        case "undefined":
        case "number":
        case "string":
          return e[t];
        default:
          return E.proxy(e[t]);
      }
    }
  });
}
async function De(s = Le) {
  if (await ye())
    switch (s) {
      case "8.3":
        return await import("./php/jspi/php_8_3.js");
      case "8.2":
        return await import("./php/jspi/php_8_2.js");
      case "8.1":
        return await import("./php/jspi/php_8_1.js");
      case "8.0":
        return await import("./php/jspi/php_8_0.js");
      case "7.4":
        return await import("./php/jspi/php_7_4.js");
      case "7.3":
        return await import("./php/jspi/php_7_3.js");
      case "7.2":
        return await import("./php/jspi/php_7_2.js");
      case "7.1":
        return await import("./php/jspi/php_7_1.js");
      case "7.0":
        return await import("./php/jspi/php_7_0.js");
    }
  else
    switch (s) {
      case "8.3":
        return await import("./php/asyncify/php_8_3.js");
      case "8.2":
        return await import("./php/asyncify/php_8_2.js");
      case "8.1":
        return await import("./php/asyncify/php_8_1.js");
      case "8.0":
        return await import("./php/asyncify/php_8_0.js");
      case "7.4":
        return await import("./php/asyncify/php_7_4.js");
      case "7.3":
        return await import("./php/asyncify/php_7_3.js");
      case "7.2":
        return await import("./php/asyncify/php_7_2.js");
      case "7.1":
        return await import("./php/asyncify/php_7_1.js");
      case "7.0":
        return await import("./php/asyncify/php_7_0.js");
    }
  throw new Error(`Unsupported PHP version ${s}`);
}
function p(s) {
  return Object.fromEntries(Object.entries(s).map(([e, t]) => [t, e]));
}
function h(s) {
  let e = 0;
  s.forEach((n) => e += n.length);
  const t = new Uint8Array(e);
  let r = 0;
  return s.forEach((n) => {
    t.set(n, r), r += n.length;
  }), t;
}
function P(s) {
  return h(s.map((e) => new Uint8Array(e))).buffer;
}
function I(s) {
  return new Uint8Array([s >> 8 & 255, s & 255]);
}
function m(s) {
  return new Uint8Array([
    s >> 16 & 255,
    s >> 8 & 255,
    s & 255
  ]);
}
function G(s) {
  const e = new ArrayBuffer(8);
  return new DataView(e).setBigUint64(0, BigInt(s), !1), new Uint8Array(e);
}
class g {
  constructor(e) {
    this.buffer = e, this.offset = 0, this.view = new DataView(e);
  }
  readUint8() {
    const e = this.view.getUint8(this.offset);
    return this.offset += 1, e;
  }
  readUint16() {
    const e = this.view.getUint16(this.offset);
    return this.offset += 2, e;
  }
  readUint32() {
    const e = this.view.getUint32(this.offset);
    return this.offset += 4, e;
  }
  readUint8Array(e) {
    const t = this.buffer.slice(this.offset, this.offset + e);
    return this.offset += e, new Uint8Array(t);
  }
  isFinished() {
    return this.offset >= this.buffer.byteLength;
  }
}
class v {
  constructor(e) {
    this.offset = 0, this.buffer = new ArrayBuffer(e), this.uint8Array = new Uint8Array(this.buffer), this.view = new DataView(this.buffer);
  }
  writeUint8(e) {
    this.view.setUint8(this.offset, e), this.offset += 1;
  }
  writeUint16(e) {
    this.view.setUint16(this.offset, e), this.offset += 2;
  }
  writeUint32(e) {
    this.view.setUint32(this.offset, e), this.offset += 4;
  }
  writeUint8Array(e) {
    this.uint8Array.set(e, this.offset), this.offset += e.length;
  }
}
const R = {
  server_name: 0,
  max_fragment_length: 1,
  client_certificate_url: 2,
  trusted_ca_keys: 3,
  truncated_hmac: 4,
  status_request: 5,
  user_mapping: 6,
  client_authz: 7,
  server_authz: 8,
  cert_type: 9,
  supported_groups: 10,
  ec_point_formats: 11,
  srp: 12,
  signature_algorithms: 13,
  use_srtp: 14,
  heartbeat: 15,
  application_layer_protocol_negotiation: 16,
  status_request_v2: 17,
  signed_certificate_timestamp: 18,
  client_certificate_type: 19,
  server_certificate_type: 20,
  padding: 21,
  encrypt_then_mac: 22,
  extended_master_secret: 23,
  token_binding: 24,
  cached_info: 25,
  tls_its: 26,
  compress_certificate: 27,
  record_size_limit: 28,
  pwd_protect: 29,
  pwo_clear: 30,
  password_salt: 31,
  ticket_pinning: 32,
  tls_cert_with_extern_psk: 33,
  delegated_credential: 34,
  session_ticket: 35,
  TLMSP: 36,
  TLMSP_proxying: 37,
  TLMSP_delegate: 38,
  supported_ekt_ciphers: 39,
  pre_shared_key: 41,
  early_data: 42,
  supported_versions: 43,
  cookie: 44,
  psk_key_exchange_modes: 45,
  reserved: 46,
  certificate_authorities: 47,
  oid_filters: 48,
  post_handshake_auth: 49,
  signature_algorithms_cert: 50,
  key_share: 51,
  transparency_info: 52,
  connection_id: 54
}, We = p(R), _e = {
  host_name: 0
}, be = p(_e);
class ae {
  static decodeFromClient(e) {
    const t = new DataView(e.buffer);
    let r = 0;
    const n = t.getUint16(r);
    r += 2;
    const i = [];
    for (; r < n + 2; ) {
      const _ = e[r];
      r += 1;
      const a = t.getUint16(r);
      r += 2;
      const c = e.slice(r, r + a);
      switch (r += a, _) {
        case _e.host_name:
          i.push({
            name_type: be[_],
            name: {
              host_name: new TextDecoder().decode(c)
            }
          });
          break;
        default:
          throw new Error(`Unsupported name type ${_}`);
      }
    }
    return { server_name_list: i };
  }
  /**
   * Encode the server_name extension
   *
   * +------------------------------------+
   * | Extension Type (server_name) [2B]  |
   * | 0x00 0x00                          |
   * +------------------------------------+
   * | Extension Length             [2B]  |
   * | 0x00 0x00                          |
   * +------------------------------------+
   */
  static encodeForClient(e) {
    if (e != null && e.server_name_list.length)
      throw new Error(
        "Encoding non-empty lists for ClientHello is not supported yet. Only empty lists meant for ServerHello are supported today."
      );
    const t = new v(4);
    return t.writeUint16(R.server_name), t.writeUint16(0), t.uint8Array;
  }
}
const oe = {
  TLS1_CK_PSK_WITH_RC4_128_SHA: 138,
  TLS1_CK_PSK_WITH_3DES_EDE_CBC_SHA: 139,
  TLS1_CK_PSK_WITH_AES_128_CBC_SHA: 140,
  TLS1_CK_PSK_WITH_AES_256_CBC_SHA: 141,
  TLS1_CK_DHE_PSK_WITH_RC4_128_SHA: 142,
  TLS1_CK_DHE_PSK_WITH_3DES_EDE_CBC_SHA: 143,
  TLS1_CK_DHE_PSK_WITH_AES_128_CBC_SHA: 144,
  TLS1_CK_DHE_PSK_WITH_AES_256_CBC_SHA: 145,
  TLS1_CK_RSA_PSK_WITH_RC4_128_SHA: 146,
  TLS1_CK_RSA_PSK_WITH_3DES_EDE_CBC_SHA: 147,
  TLS1_CK_RSA_PSK_WITH_AES_128_CBC_SHA: 148,
  TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA: 149,
  TLS1_CK_PSK_WITH_AES_128_GCM_SHA256: 168,
  TLS1_CK_PSK_WITH_AES_256_GCM_SHA384: 169,
  TLS1_CK_DHE_PSK_WITH_AES_128_GCM_SHA256: 170,
  TLS1_CK_DHE_PSK_WITH_AES_256_GCM_SHA384: 171,
  TLS1_CK_RSA_PSK_WITH_AES_128_GCM_SHA256: 172,
  TLS1_CK_RSA_PSK_WITH_AES_256_GCM_SHA384: 173,
  TLS1_CK_PSK_WITH_AES_128_CBC_SHA256: 174,
  TLS1_CK_PSK_WITH_AES_256_CBC_SHA384: 175,
  TLS1_CK_PSK_WITH_NULL_SHA256: 176,
  TLS1_CK_PSK_WITH_NULL_SHA384: 177,
  TLS1_CK_DHE_PSK_WITH_AES_128_CBC_SHA256: 178,
  TLS1_CK_DHE_PSK_WITH_AES_256_CBC_SHA384: 179,
  TLS1_CK_DHE_PSK_WITH_NULL_SHA256: 180,
  TLS1_CK_DHE_PSK_WITH_NULL_SHA384: 181,
  TLS1_CK_RSA_PSK_WITH_AES_128_CBC_SHA256: 182,
  TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA384: 183,
  TLS1_CK_RSA_PSK_WITH_NULL_SHA256: 184,
  TLS1_CK_RSA_PSK_WITH_NULL_SHA384: 185,
  TLS1_CK_PSK_WITH_NULL_SHA: 44,
  TLS1_CK_DHE_PSK_WITH_NULL_SHA: 45,
  TLS1_CK_RSA_PSK_WITH_NULL_SHA: 46,
  TLS1_CK_RSA_WITH_AES_128_SHA: 47,
  TLS1_CK_DH_DSS_WITH_AES_128_SHA: 48,
  TLS1_CK_DH_RSA_WITH_AES_128_SHA: 49,
  TLS1_CK_DHE_DSS_WITH_AES_128_SHA: 50,
  TLS1_CK_DHE_RSA_WITH_AES_128_SHA: 51,
  TLS1_CK_ADH_WITH_AES_128_SHA: 52,
  TLS1_CK_RSA_WITH_AES_256_SHA: 53,
  TLS1_CK_DH_DSS_WITH_AES_256_SHA: 54,
  TLS1_CK_DH_RSA_WITH_AES_256_SHA: 55,
  TLS1_CK_DHE_DSS_WITH_AES_256_SHA: 56,
  TLS1_CK_DHE_RSA_WITH_AES_256_SHA: 57,
  TLS1_CK_ADH_WITH_AES_256_SHA: 58,
  TLS1_CK_RSA_WITH_NULL_SHA256: 59,
  TLS1_CK_RSA_WITH_AES_128_SHA256: 60,
  TLS1_CK_RSA_WITH_AES_256_SHA256: 61,
  TLS1_CK_DH_DSS_WITH_AES_128_SHA256: 62,
  TLS1_CK_DH_RSA_WITH_AES_128_SHA256: 63,
  TLS1_CK_DHE_DSS_WITH_AES_128_SHA256: 64,
  TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA: 65,
  TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA: 66,
  TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA: 67,
  TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA: 68,
  TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: 69,
  TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA: 70,
  TLS1_CK_DHE_RSA_WITH_AES_128_SHA256: 103,
  TLS1_CK_DH_DSS_WITH_AES_256_SHA256: 104,
  TLS1_CK_DH_RSA_WITH_AES_256_SHA256: 105,
  TLS1_CK_DHE_DSS_WITH_AES_256_SHA256: 106,
  TLS1_CK_DHE_RSA_WITH_AES_256_SHA256: 107,
  TLS1_CK_ADH_WITH_AES_128_SHA256: 108,
  TLS1_CK_ADH_WITH_AES_256_SHA256: 109,
  TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA: 132,
  TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA: 133,
  TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA: 134,
  TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA: 135,
  TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: 136,
  TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA: 137,
  TLS1_CK_RSA_WITH_SEED_SHA: 150,
  TLS1_CK_DH_DSS_WITH_SEED_SHA: 151,
  TLS1_CK_DH_RSA_WITH_SEED_SHA: 152,
  TLS1_CK_DHE_DSS_WITH_SEED_SHA: 153,
  TLS1_CK_DHE_RSA_WITH_SEED_SHA: 154,
  TLS1_CK_ADH_WITH_SEED_SHA: 155,
  TLS1_CK_RSA_WITH_AES_128_GCM_SHA256: 156,
  TLS1_CK_RSA_WITH_AES_256_GCM_SHA384: 157,
  TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256: 158,
  TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384: 159,
  TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256: 160,
  TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384: 161,
  TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256: 162,
  TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384: 163,
  TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256: 164,
  TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384: 165,
  TLS1_CK_ADH_WITH_AES_128_GCM_SHA256: 166,
  TLS1_CK_ADH_WITH_AES_256_GCM_SHA384: 167,
  TLS1_CK_RSA_WITH_AES_128_CCM: 49308,
  TLS1_CK_RSA_WITH_AES_256_CCM: 49309,
  TLS1_CK_DHE_RSA_WITH_AES_128_CCM: 49310,
  TLS1_CK_DHE_RSA_WITH_AES_256_CCM: 49311,
  TLS1_CK_RSA_WITH_AES_128_CCM_8: 49312,
  TLS1_CK_RSA_WITH_AES_256_CCM_8: 49313,
  TLS1_CK_DHE_RSA_WITH_AES_128_CCM_8: 49314,
  TLS1_CK_DHE_RSA_WITH_AES_256_CCM_8: 49315,
  TLS1_CK_PSK_WITH_AES_128_CCM: 49316,
  TLS1_CK_PSK_WITH_AES_256_CCM: 49317,
  TLS1_CK_DHE_PSK_WITH_AES_128_CCM: 49318,
  TLS1_CK_DHE_PSK_WITH_AES_256_CCM: 49319,
  TLS1_CK_PSK_WITH_AES_128_CCM_8: 49320,
  TLS1_CK_PSK_WITH_AES_256_CCM_8: 49321,
  TLS1_CK_DHE_PSK_WITH_AES_128_CCM_8: 49322,
  TLS1_CK_DHE_PSK_WITH_AES_256_CCM_8: 49323,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM: 49324,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM: 49325,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM_8: 49326,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM_8: 49327,
  TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA256: 186,
  TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: 187,
  TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: 188,
  TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: 189,
  TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: 190,
  TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA256: 191,
  TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA256: 192,
  TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: 193,
  TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: 194,
  TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: 195,
  TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: 196,
  TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA256: 197,
  TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA: 49153,
  TLS1_CK_ECDH_ECDSA_WITH_RC4_128_SHA: 49154,
  TLS1_CK_ECDH_ECDSA_WITH_DES_192_CBC3_SHA: 49155,
  TLS1_CK_ECDH_ECDSA_WITH_AES_128_CBC_SHA: 49156,
  TLS1_CK_ECDH_ECDSA_WITH_AES_256_CBC_SHA: 49157,
  TLS1_CK_ECDHE_ECDSA_WITH_NULL_SHA: 49158,
  TLS1_CK_ECDHE_ECDSA_WITH_RC4_128_SHA: 49159,
  TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA: 49160,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: 49161,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: 49162,
  TLS1_CK_ECDH_RSA_WITH_NULL_SHA: 49163,
  TLS1_CK_ECDH_RSA_WITH_RC4_128_SHA: 49164,
  TLS1_CK_ECDH_RSA_WITH_DES_192_CBC3_SHA: 49165,
  TLS1_CK_ECDH_RSA_WITH_AES_128_CBC_SHA: 49166,
  TLS1_CK_ECDH_RSA_WITH_AES_256_CBC_SHA: 49167,
  TLS1_CK_ECDHE_RSA_WITH_NULL_SHA: 49168,
  TLS1_CK_ECDHE_RSA_WITH_RC4_128_SHA: 49169,
  TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA: 49170,
  TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA: 49171,
  TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA: 49172,
  TLS1_CK_ECDH_anon_WITH_NULL_SHA: 49173,
  TLS1_CK_ECDH_anon_WITH_RC4_128_SHA: 49174,
  TLS1_CK_ECDH_anon_WITH_DES_192_CBC3_SHA: 49175,
  TLS1_CK_ECDH_anon_WITH_AES_128_CBC_SHA: 49176,
  TLS1_CK_ECDH_anon_WITH_AES_256_CBC_SHA: 49177,
  TLS1_CK_SRP_SHA_WITH_3DES_EDE_CBC_SHA: 49178,
  TLS1_CK_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA: 49179,
  TLS1_CK_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA: 49180,
  TLS1_CK_SRP_SHA_WITH_AES_128_CBC_SHA: 49181,
  TLS1_CK_SRP_SHA_RSA_WITH_AES_128_CBC_SHA: 49182,
  TLS1_CK_SRP_SHA_DSS_WITH_AES_128_CBC_SHA: 49183,
  TLS1_CK_SRP_SHA_WITH_AES_256_CBC_SHA: 49184,
  TLS1_CK_SRP_SHA_RSA_WITH_AES_256_CBC_SHA: 49185,
  TLS1_CK_SRP_SHA_DSS_WITH_AES_256_CBC_SHA: 49186,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256: 49187,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384: 49188,
  TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256: 49189,
  TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384: 49190,
  TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256: 49191,
  TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384: 49192,
  TLS1_CK_ECDH_RSA_WITH_AES_128_SHA256: 49193,
  TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384: 49194,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: 49195,
  TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: 49196,
  TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: 49197,
  TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: 49198,
  TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256: 49199,
  TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384: 49200,
  TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256: 49201,
  TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384: 49202,
  TLS1_CK_ECDHE_PSK_WITH_RC4_128_SHA: 49203,
  TLS1_CK_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA: 49204,
  TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA: 49205,
  TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA: 49206,
  TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA256: 49207,
  TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA384: 49208,
  TLS1_CK_ECDHE_PSK_WITH_NULL_SHA: 49209,
  TLS1_CK_ECDHE_PSK_WITH_NULL_SHA256: 49210,
  TLS1_CK_ECDHE_PSK_WITH_NULL_SHA384: 49211,
  TLS1_CK_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: 49266,
  TLS1_CK_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: 49267,
  TLS1_CK_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: 49268,
  TLS1_CK_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: 49269,
  TLS1_CK_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: 49270,
  TLS1_CK_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: 49271,
  TLS1_CK_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: 49272,
  TLS1_CK_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: 49273,
  TLS1_CK_PSK_WITH_CAMELLIA_128_CBC_SHA256: 49300,
  TLS1_CK_PSK_WITH_CAMELLIA_256_CBC_SHA384: 49301,
  TLS1_CK_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: 49302,
  TLS1_CK_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: 49303,
  TLS1_CK_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256: 49304,
  TLS1_CK_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384: 49305,
  TLS1_CK_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: 49306,
  TLS1_CK_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: 49307,
  TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305: 52392,
  TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: 52393,
  TLS1_CK_DHE_RSA_WITH_CHACHA20_POLY1305: 52394,
  TLS1_CK_PSK_WITH_CHACHA20_POLY1305: 52395,
  TLS1_CK_ECDHE_PSK_WITH_CHACHA20_POLY1305: 52396,
  TLS1_CK_DHE_PSK_WITH_CHACHA20_POLY1305: 52397,
  TLS1_CK_RSA_PSK_WITH_CHACHA20_POLY1305: 52398
}, j = p(oe), ce = {
  secp256r1: 23,
  secp384r1: 24,
  secp521r1: 25,
  x25519: 29,
  x448: 30
}, $ = p(ce);
class Se {
  /**
   * +--------------------------------------------------+
   * | Payload Length                            [2B]   |
   * +--------------------------------------------------+
   * | Supported Groups List Length              [2B]   |
   * +--------------------------------------------------+
   * | Supported Group 1                         [2B]   |
   * +--------------------------------------------------+
   * | Supported Group 2                         [2B]   |
   * +--------------------------------------------------+
   * | ...                                              |
   * +--------------------------------------------------+
   * | Supported Group n                         [2B]   |
   * +--------------------------------------------------+
   */
  static decodeFromClient(e) {
    const t = new g(e.buffer);
    t.readUint16();
    const r = [];
    for (; !t.isFinished(); ) {
      const n = t.readUint16();
      n in $ && r.push($[n]);
    }
    return r;
  }
  /**
   * +--------------------------------------------------+
   * | Extension Type (supported_groups)         [2B]   |
   * | 0x00 0x0A                                        |
   * +--------------------------------------------------+
   * | Extension Length                          [2B]   |
   * +--------------------------------------------------+
   * | Selected Group                            [2B]   |
   * +--------------------------------------------------+
   */
  static encodeForClient(e) {
    const t = new v(6);
    return t.writeUint16(R.supported_groups), t.writeUint16(2), t.writeUint16(ce[e]), t.uint8Array;
  }
}
const Ce = {
  uncompressed: 0,
  ansiX962_compressed_prime: 1,
  ansiX962_compressed_char2: 2
}, V = p(Ce);
class le {
  /**
   * +--------------------------------------------------+
   * | Payload Length                            [2B]   |
   * +--------------------------------------------------+
   * | EC Point Formats Length                   [1B]   |
   * +--------------------------------------------------+
   * | EC Point Format 1                         [1B]   |
   * +--------------------------------------------------+
   * | EC Point Format 2                         [1B]   |
   * +--------------------------------------------------+
   * | ...                                              |
   * +--------------------------------------------------+
   * | EC Point Format n                         [1B]   |
   * +--------------------------------------------------+
   */
  static decodeFromClient(e) {
    const t = new g(e.buffer), r = t.readUint8(), n = [];
    for (let i = 0; i < r; i++) {
      const _ = t.readUint8();
      _ in V && n.push(V[_]);
    }
    return n;
  }
  /**
   * Encode the ec_point_formats extension
   *
   * +--------------------------------------------------+
   * | Extension Type (ec_point_formats)         [2B]   |
   * | 0x00 0x0B                                        |
   * +--------------------------------------------------+
   * | Body Length                               [2B]   |
   * +--------------------------------------------------+
   * | EC Point Format Length                    [1B]   |
   * +--------------------------------------------------+
   * | EC Point Format                           [1B]   |
   * +--------------------------------------------------+
   */
  static encodeForClient(e) {
    const t = new v(6);
    return t.writeUint16(R.ec_point_formats), t.writeUint16(2), t.writeUint8(1), t.writeUint8(Ce[e]), t.uint8Array;
  }
}
const N = {
  anonymous: 0,
  rsa: 1,
  dsa: 2,
  ecdsa: 3
}, z = p(N), O = {
  none: 0,
  md5: 1,
  sha1: 2,
  sha224: 3,
  sha256: 4,
  sha384: 5,
  sha512: 6
}, Y = p(O);
class Ae {
  /**
   * Binary layout:
   *
   * +------------------------------------+
   * | Payload Length              [2B]   |
   * +------------------------------------+
   * | Hash Algorithm 1            [1B]   |
   * | Signature Algorithm 1       [1B]   |
   * +------------------------------------+
   * | Hash Algorithm 2            [1B]   |
   * | Signature Algorithm 2       [1B]   |
   * +------------------------------------+
   * | ...                                |
   * +------------------------------------+
   */
  static decodeFromClient(e) {
    const t = new g(e.buffer);
    t.readUint16();
    const r = [];
    for (; !t.isFinished(); ) {
      const n = t.readUint8(), i = t.readUint8();
      if (!z[i]) {
        b.warn(`Unknown signature algorithm: ${i}`);
        continue;
      }
      if (!Y[n]) {
        b.warn(`Unknown hash algorithm: ${n}`);
        continue;
      }
      r.push({
        algorithm: z[i],
        hash: Y[n]
      });
    }
    return r;
  }
  /**
   * +--------------------------------------------------+
   * | Extension Type (signature_algorithms)     [2B]   |
   * | 0x00 0x0D                                        |
   * +--------------------------------------------------+
   * | Body Length                               [2B]   |
   * +--------------------------------------------------+
   * | Hash Algorithm                            [1B]   |
   * | Signature Algorithm                       [1B]   |
   * +--------------------------------------------------+
   */
  static encodeforClient(e, t) {
    const r = new v(6);
    return r.writeUint16(R.signature_algorithms), r.writeUint16(2), r.writeUint8(O[e]), r.writeUint8(N[t]), r.uint8Array;
  }
}
const J = {
  server_name: ae,
  signature_algorithms: Ae,
  supported_groups: Se,
  ec_point_formats: le
};
function Re(s) {
  const e = new g(s.buffer), t = [];
  for (; !e.isFinished(); ) {
    const r = e.offset, n = e.readUint16(), i = We[n], _ = e.readUint16(), a = e.readUint8Array(_);
    if (!(i in J))
      continue;
    const c = J[i];
    t.push({
      type: i,
      data: c.decodeFromClient(a),
      raw: s.slice(r, r + 4 + _)
    });
  }
  return t;
}
async function M(s, e, t, r) {
  const n = P([e, t]), i = await crypto.subtle.importKey(
    "raw",
    s,
    { name: "HMAC", hash: { name: "SHA-256" } },
    !1,
    ["sign"]
  );
  let _ = n;
  const a = [];
  for (; P(a).byteLength < r; ) {
    _ = await X(i, _);
    const S = P([_, n]), l = await X(i, S);
    a.push(l);
  }
  return P(a).slice(0, r);
}
async function X(s, e) {
  return await crypto.subtle.sign(
    { name: "HMAC", hash: "SHA-256" },
    s,
    e
  );
}
var ue = /* @__PURE__ */ ((s) => (s[s.Null = 0] = "Null", s[s.Deflate = 1] = "Deflate", s))(ue || {});
const Pe = {
  Warning: 1,
  Fatal: 2
}, he = p(Pe), Be = {
  CloseNotify: 0,
  UnexpectedMessage: 10,
  BadRecordMac: 20,
  DecryptionFailed: 21,
  RecordOverflow: 22,
  DecompressionFailure: 30,
  HandshakeFailure: 40,
  NoCertificate: 41,
  BadCertificate: 42,
  UnsupportedCertificate: 43,
  CertificateRevoked: 44,
  CertificateExpired: 45,
  CertificateUnknown: 46,
  IllegalParameter: 47,
  UnknownCa: 48,
  AccessDenied: 49,
  DecodeError: 50,
  DecryptError: 51,
  ExportRestriction: 60,
  ProtocolVersion: 70,
  InsufficientSecurity: 71,
  InternalError: 80,
  UserCanceled: 90,
  NoRenegotiation: 100,
  UnsupportedExtension: 110
}, He = p(Be), C = {
  ChangeCipherSpec: 20,
  Alert: 21,
  Handshake: 22,
  ApplicationData: 23
};
var d = /* @__PURE__ */ ((s) => (s[s.HelloRequest = 0] = "HelloRequest", s[s.ClientHello = 1] = "ClientHello", s[s.ServerHello = 2] = "ServerHello", s[s.Certificate = 11] = "Certificate", s[s.ServerKeyExchange = 12] = "ServerKeyExchange", s[s.CertificateRequest = 13] = "CertificateRequest", s[s.ServerHelloDone = 14] = "ServerHelloDone", s[s.CertificateVerify = 15] = "CertificateVerify", s[s.ClientKeyExchange = 16] = "ClientKeyExchange", s[s.Finished = 20] = "Finished", s))(d || {});
const Ue = {
  /**
   * Indicates the elliptic curve domain parameters are
   * conveyed verbosely, and the underlying finite field is a prime
   * field.
   */
  ExplicitPrime: 1,
  /**
   * Indicates the elliptic curve domain parameters are
   * conveyed verbosely, and the underlying finite field is a
   * characteristic-2 field.
   */
  ExplicitChar2: 2,
  /**
   * Indicates that a named curve is used.  This option
   * SHOULD be used when applicable.
   */
  NamedCurve: 3
  /**
   * Values 248 through 255 are reserved for private use.
   */
}, ve = {
  sect163k1: 1,
  sect163r1: 2,
  sect163r2: 3,
  sect193r1: 4,
  sect193r2: 5,
  sect233k1: 6,
  sect233r1: 7,
  sect239k1: 8,
  sect283k1: 9,
  sect283r1: 10,
  sect409k1: 11,
  sect409r1: 12,
  secp256k1: 22,
  secp256r1: 23,
  secp384r1: 24,
  secp521r1: 25,
  arbitrary_explicit_prime_curves: 65281,
  arbitrary_explicit_char2_curves: 65282
};
class Z extends Error {
}
const U = new Uint8Array([3, 3]), Me = crypto.subtle.generateKey(
  {
    name: "ECDH",
    namedCurve: "P-256"
    // Use secp256r1 curve
  },
  !0,
  // Extractable
  ["deriveKey", "deriveBits"]
  // Key usage
);
class xe {
  constructor() {
    this.receivedRecordSequenceNumber = 0, this.sentRecordSequenceNumber = 0, this.closed = !1, this.receivedBytesBuffer = new Uint8Array(), this.receivedTLSRecords = [], this.partialTLSMessages = {}, this.handshakeMessages = [], this.MAX_CHUNK_SIZE = 1024 * 16, this.clientEnd = {
      // We don't need to chunk the encrypted data.
      // OpenSSL already done that for us.
      upstream: new TransformStream(),
      downstream: new TransformStream()
    }, this.clientDownstreamWriter = this.clientEnd.downstream.writable.getWriter(), this.clientUpstreamReader = this.clientEnd.upstream.readable.getReader(), this.serverEnd = {
      upstream: new TransformStream(),
      /**
       * Chunk the data before encrypting it. The
       * TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 cipher suite
       * only supports up to 16KB of data per record.
       *
       * This will spread some messages across multiple records,
       * but TLS supports it so that's fine.
       */
      downstream: Ne(this.MAX_CHUNK_SIZE)
    }, this.serverUpstreamWriter = this.serverEnd.upstream.writable.getWriter();
    const e = this;
    this.serverEnd.downstream.readable.pipeTo(
      new WritableStream({
        async write(t) {
          await e.writeTLSRecord(
            C.ApplicationData,
            t
          );
        },
        async abort(t) {
          e.clientDownstreamWriter.releaseLock(), e.clientEnd.downstream.writable.abort(t), e.close();
        },
        close() {
          e.close();
        }
      })
    ).catch(() => {
    });
  }
  /**
   * Marks this connections as closed and closes all the associated
   * streams.
   */
  async close() {
    if (!this.closed) {
      this.closed = !0;
      try {
        await this.clientDownstreamWriter.close();
      } catch {
      }
      try {
        await this.clientUpstreamReader.cancel();
      } catch {
      }
      try {
        await this.serverUpstreamWriter.close();
      } catch {
      }
      try {
        await this.clientEnd.upstream.readable.cancel();
      } catch {
      }
      try {
        await this.clientEnd.downstream.writable.close();
      } catch {
      }
    }
  }
  /**
   * TLS handshake as per RFC 5246.
   *
   * https://datatracker.ietf.org/doc/html/rfc5246#section-7.4
   */
  async TLSHandshake(e, t) {
    const r = await this.readNextHandshakeMessage(
      d.ClientHello
    );
    if (!r.body.cipher_suites.length)
      throw new Error(
        "Client did not propose any supported cipher suites."
      );
    const n = crypto.getRandomValues(new Uint8Array(32));
    await this.writeTLSRecord(
      C.Handshake,
      K.serverHello(
        r.body,
        n,
        ue.Null
      )
    ), await this.writeTLSRecord(
      C.Handshake,
      K.certificate(t)
    );
    const i = await Me, _ = r.body.random, a = await K.ECDHEServerKeyExchange(
      _,
      n,
      i,
      e
    );
    await this.writeTLSRecord(C.Handshake, a), await this.writeTLSRecord(
      C.Handshake,
      K.serverHelloDone()
    );
    const c = await this.readNextHandshakeMessage(
      d.ClientKeyExchange
    );
    await this.readNextMessage(C.ChangeCipherSpec), this.sessionKeys = await this.deriveSessionKeys({
      clientRandom: _,
      serverRandom: n,
      serverPrivateKey: i.privateKey,
      clientPublicKey: await crypto.subtle.importKey(
        "raw",
        c.body.exchange_keys,
        { name: "ECDH", namedCurve: "P-256" },
        !1,
        []
      )
    }), await this.readNextHandshakeMessage(d.Finished), await this.writeTLSRecord(
      C.ChangeCipherSpec,
      K.changeCipherSpec()
    ), await this.writeTLSRecord(
      C.Handshake,
      await K.createFinishedMessage(
        this.handshakeMessages,
        this.sessionKeys.masterSecret
      )
    ), this.handshakeMessages = [], this.pollForClientMessages();
  }
  /**
   * Derives the session keys from the random values and the
   * pre-master secret – as per RFC 5246.
   */
  async deriveSessionKeys({
    clientRandom: e,
    serverRandom: t,
    serverPrivateKey: r,
    clientPublicKey: n
  }) {
    const i = await crypto.subtle.deriveBits(
      {
        name: "ECDH",
        public: n
      },
      r,
      256
      // Length of the derived secret (256 bits for P-256)
    ), _ = new Uint8Array(
      await M(
        i,
        new TextEncoder().encode("master secret"),
        h([e, t]),
        48
      )
    ), a = await M(
      _,
      new TextEncoder().encode("key expansion"),
      h([t, e]),
      // Client key, server key, client IV, server IV
      16 + 16 + 4 + 4
    ), c = new g(a), S = c.readUint8Array(16), l = c.readUint8Array(16), A = c.readUint8Array(4), u = c.readUint8Array(4);
    return {
      masterSecret: _,
      clientWriteKey: await crypto.subtle.importKey(
        "raw",
        S,
        { name: "AES-GCM" },
        !1,
        ["encrypt", "decrypt"]
      ),
      serverWriteKey: await crypto.subtle.importKey(
        "raw",
        l,
        { name: "AES-GCM" },
        !1,
        ["encrypt", "decrypt"]
      ),
      clientIV: A,
      serverIV: u
    };
  }
  async readNextHandshakeMessage(e) {
    const t = await this.readNextMessage(C.Handshake);
    if (t.msg_type !== e)
      throw new Error(`Expected ${e} message`);
    return t;
  }
  async readNextMessage(e) {
    let t, r = !1;
    do
      t = await this.readNextTLSRecord(e), r = await this.accumulateUntilMessageIsComplete(
        t
      );
    while (r === !1);
    const n = f.TLSMessage(
      t.type,
      r
    );
    return t.type === C.Handshake && this.handshakeMessages.push(t.fragment), n;
  }
  async readNextTLSRecord(e) {
    for (; ; ) {
      for (let i = 0; i < this.receivedTLSRecords.length; i++) {
        const _ = this.receivedTLSRecords[i];
        if (_.type === C.Alert)
          throw new Error(
            `Alert message received: ${he[_.fragment[0]]} ${He[_.fragment[1]]}`
          );
        if (_.type === e)
          return this.receivedTLSRecords.splice(i, 1), this.sessionKeys && _.type !== C.ChangeCipherSpec && (_.fragment = await this.decryptData(
            _.type,
            _.fragment
          )), _;
      }
      const t = await this.pollBytes(5), r = t[3] << 8 | t[4], n = {
        type: t[0],
        version: {
          major: t[1],
          minor: t[2]
        },
        length: r,
        fragment: await this.pollBytes(r)
      };
      this.receivedTLSRecords.push(n);
    }
  }
  /**
   * Returns the requested number of bytes from the client.
   * Waits for the bytes to arrive if necessary.
   */
  async pollBytes(e) {
    for (; this.receivedBytesBuffer.length < e; ) {
      const { value: r, done: n } = await this.clientUpstreamReader.read();
      if (n)
        throw await this.close(), new Z("TLS connection closed");
      if (this.receivedBytesBuffer = h([
        this.receivedBytesBuffer,
        r
      ]), this.receivedBytesBuffer.length >= e)
        break;
      await new Promise((i) => setTimeout(i, 100));
    }
    const t = this.receivedBytesBuffer.slice(0, e);
    return this.receivedBytesBuffer = this.receivedBytesBuffer.slice(e), t;
  }
  /**
   * Listens for all incoming messages and passes them to the
   * server handler.
   */
  async pollForClientMessages() {
    try {
      for (; ; ) {
        const e = await this.readNextMessage(
          C.ApplicationData
        );
        this.serverUpstreamWriter.write(e.body);
      }
    } catch (e) {
      if (e instanceof Z)
        return;
      throw e;
    }
  }
  /**
   * Decrypts data in a TLS 1.2-compliant manner using
   * the AES-GCM algorithm.
   */
  async decryptData(e, t) {
    const r = this.sessionKeys.clientIV, n = t.slice(0, 8), i = new Uint8Array([...r, ...n]), _ = await crypto.subtle.decrypt(
      {
        name: "AES-GCM",
        iv: i,
        additionalData: new Uint8Array([
          ...G(this.receivedRecordSequenceNumber),
          e,
          ...U,
          // Payload length without IV and tag
          ...I(t.length - 8 - 16)
        ]),
        tagLength: 128
      },
      this.sessionKeys.clientWriteKey,
      // Payload without the explicit IV
      t.slice(8)
    );
    return ++this.receivedRecordSequenceNumber, new Uint8Array(_);
  }
  async accumulateUntilMessageIsComplete(e) {
    this.partialTLSMessages[e.type] = h([
      this.partialTLSMessages[e.type] || new Uint8Array(),
      e.fragment
    ]);
    const t = this.partialTLSMessages[e.type];
    switch (e.type) {
      case C.Handshake: {
        if (t.length < 4)
          return !1;
        const r = t[1] << 8 | t[2];
        if (t.length < 3 + r)
          return !1;
        break;
      }
      case C.Alert: {
        if (t.length < 2)
          return !1;
        break;
      }
      case C.ChangeCipherSpec:
      case C.ApplicationData:
        break;
      default:
        throw new Error(`TLS: Unsupported record type ${e.type}`);
    }
    return delete this.partialTLSMessages[e.type], t;
  }
  /**
   * Passes a TLS record to the client.
   *
   * Accepts unencrypted data and ensures it gets encrypted
   * if needed before sending it to the client. The encryption
   * only kicks in after the handshake is complete.
   */
  async writeTLSRecord(e, t) {
    e === C.Handshake && this.handshakeMessages.push(t), this.sessionKeys && e !== C.ChangeCipherSpec && (t = await this.encryptData(e, t));
    const r = U, n = t.length, i = new Uint8Array(5);
    i[0] = e, i[1] = r[0], i[2] = r[1], i[3] = n >> 8 & 255, i[4] = n & 255;
    const _ = h([i, t]);
    this.clientDownstreamWriter.write(_);
  }
  /**
   * Encrypts data in a TLS 1.2-compliant manner using
   * the AES-GCM algorithm.
   */
  async encryptData(e, t) {
    const r = this.sessionKeys.serverIV, n = crypto.getRandomValues(new Uint8Array(8)), i = new Uint8Array([...r, ...n]), _ = new Uint8Array([
      ...G(this.sentRecordSequenceNumber),
      e,
      ...U,
      // Payload length without IV and tag
      ...I(t.length)
    ]), a = await crypto.subtle.encrypt(
      {
        name: "AES-GCM",
        iv: i,
        additionalData: _,
        tagLength: 128
      },
      this.sessionKeys.serverWriteKey,
      t
    );
    return ++this.sentRecordSequenceNumber, h([
      n,
      new Uint8Array(a)
    ]);
  }
}
class f {
  static TLSMessage(e, t) {
    switch (e) {
      case C.Handshake:
        return f.clientHandshake(t);
      case C.Alert:
        return f.alert(t);
      case C.ChangeCipherSpec:
        return f.changeCipherSpec();
      case C.ApplicationData:
        return f.applicationData(t);
      default:
        throw new Error(`TLS: Unsupported TLS record type ${e}`);
    }
  }
  /**
   * Parses the cipher suites from the server hello message.
   *
   * The cipher suites are encoded as a list of 2-byte values.
   *
   * Binary layout:
   *
   * +----------------------------+
   * | Cipher Suites Length       |  2 bytes
   * +----------------------------+
   * | Cipher Suite 1             |  2 bytes
   * +----------------------------+
   * | Cipher Suite 2             |  2 bytes
   * +----------------------------+
   * | ...                        |
   * +----------------------------+
   * | Cipher Suite n             |  2 bytes
   * +----------------------------+
   *
   * The full list of supported cipher suites values is available at:
   *
   * https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4
   */
  static parseCipherSuites(e) {
    const t = new g(e);
    t.readUint16();
    const r = [];
    for (; !t.isFinished(); ) {
      const n = t.readUint16();
      n in j && r.push(j[n]);
    }
    return r;
  }
  static applicationData(e) {
    return {
      type: C.ApplicationData,
      body: e
    };
  }
  static changeCipherSpec() {
    return {
      type: C.ChangeCipherSpec,
      body: new Uint8Array()
    };
  }
  static alert(e) {
    return {
      type: C.Alert,
      level: he[e[0]],
      description: He[e[1]]
    };
  }
  static clientHandshake(e) {
    const t = e[0], r = e[1] << 16 | e[2] << 8 | e[3], n = e.slice(4);
    let i;
    switch (t) {
      case d.HelloRequest:
        i = f.clientHelloRequestPayload();
        break;
      case d.ClientHello:
        i = f.clientHelloPayload(n);
        break;
      case d.ClientKeyExchange:
        i = f.clientKeyExchangePayload(n);
        break;
      case d.Finished:
        i = f.clientFinishedPayload(n);
        break;
      default:
        throw new Error(`Invalid handshake type ${t}`);
    }
    return {
      type: C.Handshake,
      msg_type: t,
      length: r,
      body: i
    };
  }
  static clientHelloRequestPayload() {
    return {};
  }
  /**
   *	Offset  Size    Field
   *	(bytes) (bytes)
   *	+------+------+---------------------------+
   *	| 0000 |  1   | Handshake Type (1 = ClientHello)
   *	+------+------+---------------------------+
   *	| 0001 |  3   | Length of ClientHello
   *	+------+------+---------------------------+
   *	| 0004 |  2   | Protocol Version
   *	+------+------+---------------------------+
   *	| 0006 |  32  | Client Random
   *	|      |      | (4 bytes timestamp +
   *	|      |      |  28 bytes random)
   *	+------+------+---------------------------+
   *	| 0038 |  1   | Session ID Length
   *	+------+------+---------------------------+
   *	| 0039 |  0+  | Session ID (variable)
   *	|      |      | (0-32 bytes)
   *	+------+------+---------------------------+
   *	| 003A*|  2   | Cipher Suites Length
   *	+------+------+---------------------------+
   *	| 003C*|  2+  | Cipher Suites
   *	|      |      | (2 bytes each)
   *	+------+------+---------------------------+
   *	| xxxx |  1   | Compression Methods Length
   *	+------+------+---------------------------+
   *	| xxxx |  1+  | Compression Methods
   *	|      |      | (1 byte each)
   *	+------+------+---------------------------+
   *	| xxxx |  2   | Extensions Length
   *	+------+------+---------------------------+
   *	| xxxx |  2   | Extension Type
   *	+------+------+---------------------------+
   *	| xxxx |  2   | Extension Length
   *	+------+------+---------------------------+
   *	| xxxx |  v   | Extension Data
   *	+------+------+---------------------------+
   *	|      |      | (Additional extensions...)
   *	+------+------+---------------------------+
   */
  static clientHelloPayload(e) {
    const t = new g(e.buffer), r = {
      client_version: t.readUint8Array(2),
      /**
       * Technically this consists of a GMT timestamp
       * and 28 random bytes, but we don't need to
       * parse this further.
       */
      random: t.readUint8Array(32)
    }, n = t.readUint8();
    r.session_id = t.readUint8Array(n);
    const i = t.readUint16();
    r.cipher_suites = f.parseCipherSuites(
      t.readUint8Array(i).buffer
    );
    const _ = t.readUint8();
    r.compression_methods = t.readUint8Array(
      _
    );
    const a = t.readUint16();
    return r.extensions = Re(
      t.readUint8Array(a)
    ), r;
  }
  /**
   * Binary layout:
   *
   *	+------------------------------------+
   *	| ECDH Client Public Key Length [1B] |
   *	+------------------------------------+
   *	| ECDH Client Public Key   [variable]|
   *	+------------------------------------+
   */
  static clientKeyExchangePayload(e) {
    return {
      // Skip the first byte, which is the length of the public key
      exchange_keys: e.slice(1, e.length)
    };
  }
  static clientFinishedPayload(e) {
    return {
      verify_data: e
    };
  }
}
function Ne(s) {
  return new TransformStream({
    transform(e, t) {
      for (; e.length > 0; )
        t.enqueue(e.slice(0, s)), e = e.slice(s);
    }
  });
}
class K {
  static certificate(e) {
    const t = [];
    for (const i of e)
      t.push(m(i.byteLength)), t.push(new Uint8Array(i));
    const r = h(t), n = new Uint8Array([
      ...m(r.byteLength),
      ...r
    ]);
    return new Uint8Array([
      d.Certificate,
      ...m(n.length),
      ...n
    ]);
  }
  /*
   * Byte layout of the ServerKeyExchange message:
   *
   * +-----------------------------------+
   * |    ServerKeyExchange Message      |
   * +-----------------------------------+
   * | Handshake type (1 byte)           |
   * +-----------------------------------+
   * | Length (3 bytes)                  |
   * +-----------------------------------+
   * | Curve Type (1 byte)               |
   * +-----------------------------------+
   * | Named Curve (2 bytes)             |
   * +-----------------------------------+
   * | EC Point Format (1 byte)          |
   * +-----------------------------------+
   * | Public Key Length (1 byte)        |
   * +-----------------------------------+
   * | Public Key (variable)             |
   * +-----------------------------------+
   * | Signature Algorithm (2 bytes)     |
   * +-----------------------------------+
   * | Signature Length (2 bytes)        |
   * +-----------------------------------+
   * | Signature (variable)              |
   * +-----------------------------------+
   *
   * @param clientRandom - 32 bytes from ClientHello
   * @param serverRandom - 32 bytes from ServerHello
   * @param ecdheKeyPair - ECDHE key pair
   * @param rsaPrivateKey - RSA private key for signing
   * @returns
   */
  static async ECDHEServerKeyExchange(e, t, r, n) {
    const i = new Uint8Array(
      await crypto.subtle.exportKey("raw", r.publicKey)
    ), _ = new Uint8Array([
      // Curve type (1 byte)
      Ue.NamedCurve,
      // Curve name (2 bytes)
      ...I(ve.secp256r1),
      // Public key length (1 byte)
      i.byteLength,
      // Public key (65 bytes, uncompressed format)
      ...i
    ]), a = await crypto.subtle.sign(
      {
        name: "RSASSA-PKCS1-v1_5",
        hash: "SHA-256"
      },
      n,
      new Uint8Array([...e, ...t, ..._])
    ), c = new Uint8Array(a), S = new Uint8Array([
      O.sha256,
      N.rsa
    ]), l = new Uint8Array([
      ..._,
      ...S,
      ...I(c.length),
      ...c
    ]);
    return new Uint8Array([
      d.ServerKeyExchange,
      ...m(l.length),
      ...l
    ]);
  }
  /**
   * +------------------------------------+
   * | Content Type (Handshake)     [1B]  |
   * | 0x16                               |
   * +------------------------------------+
   * | Version (TLS 1.2)            [2B]  |
   * | 0x03 0x03                          |
   * +------------------------------------+
   * | Length                       [2B]  |
   * +------------------------------------+
   * | Handshake Type (ServerHello) [1B]  |
   * | 0x02                               |
   * +------------------------------------+
   * | Handshake Length             [3B]  |
   * +------------------------------------+
   * | Server Version               [2B]  |
   * +------------------------------------+
   * | Server Random               [32B]  |
   * +------------------------------------+
   * | Session ID Length            [1B]  |
   * +------------------------------------+
   * | Session ID             [0-32B]     |
   * +------------------------------------+
   * | Cipher Suite                 [2B]  |
   * +------------------------------------+
   * | Compression Method           [1B]  |
   * +------------------------------------+
   * | Extensions Length            [2B]  |
   * +------------------------------------+
   * | Extension: ec_point_formats        |
   * |   Type (0x00 0x0B)           [2B]  |
   * |   Length                     [2B]  |
   * |   EC Point Formats Length    [1B]  |
   * |   EC Point Format            [1B]  |
   * +------------------------------------+
   * | Other Extensions...                |
   * +------------------------------------+
   */
  static serverHello(e, t, r) {
    const n = e.extensions.map((a) => {
      switch (a.type) {
        case "server_name":
          return ae.encodeForClient();
        case "supported_groups":
          return Se.encodeForClient(
            "secp256r1"
          );
        case "ec_point_formats":
          return le.encodeForClient(
            "uncompressed"
          );
        case "signature_algorithms":
          return Ae.encodeforClient(
            "sha256",
            "rsa"
          );
      }
    }).filter((a) => a !== void 0), i = h(n), _ = new Uint8Array([
      // Version field – 0x03, 0x03 means TLS 1.2
      ...U,
      ...t,
      e.session_id.length,
      ...e.session_id,
      ...I(oe.TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256),
      r,
      // Extensions length (2 bytes)
      ...I(i.length),
      ...i
    ]);
    return new Uint8Array([
      d.ServerHello,
      ...m(_.length),
      ..._
    ]);
  }
  static serverHelloDone() {
    return new Uint8Array([d.ServerHelloDone, ...m(0)]);
  }
  /**
   * Server finished message.
   * The structure is defined in:
   * https://datatracker.ietf.org/doc/html/rfc5246#section-7.4.9
   *
   * struct {
   *     opaque verify_data[verify_data_length];
   * } Finished;
   *
   * verify_data
   *    PRF(master_secret, finished_label, Hash(handshake_messages))
   *       [0..verify_data_length-1];
   *
   * finished_label
   *    For Finished messages sent by the client, the string
   *    "client finished".  For Finished messages sent by the server,
   *    the string "server finished".
   */
  static async createFinishedMessage(e, t) {
    const r = await crypto.subtle.digest(
      "SHA-256",
      h(e)
    ), n = new Uint8Array(
      await M(
        t,
        new TextEncoder().encode("server finished"),
        r,
        // verify_data length. TLS 1.2 specifies 12 bytes for verify_data
        12
      )
    );
    return new Uint8Array([
      d.Finished,
      ...m(n.length),
      ...n
    ]);
  }
  static changeCipherSpec() {
    return new Uint8Array([1]);
  }
}
function Oe(s, e) {
  return qe.generateCertificate(s, e);
}
function ot(s) {
  return `-----BEGIN CERTIFICATE-----
${fe(
    de(s.buffer)
  )}
-----END CERTIFICATE-----`;
}
async function ct(s) {
  const e = await crypto.subtle.exportKey("pkcs8", s);
  return `-----BEGIN PRIVATE KEY-----
${fe(
    de(e)
  )}
-----END PRIVATE KEY-----`;
}
class qe {
  static async generateCertificate(e, t) {
    const r = await crypto.subtle.generateKey(
      {
        name: "RSASSA-PKCS1-v1_5",
        hash: "SHA-256",
        modulusLength: 2048,
        publicExponent: new Uint8Array([1, 0, 1])
      },
      !0,
      // extractable
      ["sign", "verify"]
    ), n = await this.signingRequest(
      e,
      r.publicKey
    ), i = await this.sign(
      n,
      (t == null ? void 0 : t.privateKey) ?? r.privateKey
    );
    return {
      keyPair: r,
      certificate: i,
      tbsCertificate: n,
      tbsDescription: e
    };
  }
  static async sign(e, t) {
    const r = await crypto.subtle.sign(
      {
        name: "RSASSA-PKCS1-v1_5",
        hash: "SHA-256"
      },
      t,
      e.buffer
    );
    return o.sequence([
      new Uint8Array(e.buffer),
      this.signatureAlgorithm("sha256WithRSAEncryption"),
      o.bitString(new Uint8Array(r))
    ]);
  }
  static async signingRequest(e, t) {
    const r = [];
    return e.keyUsage && r.push(this.keyUsage(e.keyUsage)), e.extKeyUsage && r.push(this.extKeyUsage(e.extKeyUsage)), e.subjectAltNames && r.push(this.subjectAltName(e.subjectAltNames)), e.nsCertType && r.push(this.nsCertType(e.nsCertType)), e.basicConstraints && r.push(
      this.basicConstraints(e.basicConstraints)
    ), o.sequence([
      this.version(e.version),
      this.serialNumber(e.serialNumber),
      this.signatureAlgorithm(e.signatureAlgorithm),
      this.distinguishedName(e.issuer ?? e.subject),
      this.validity(e.validity),
      this.distinguishedName(e.subject),
      await this.subjectPublicKeyInfo(t),
      this.extensions(r)
    ]);
  }
  static version(e = 2) {
    return o.ASN1(
      160,
      o.integer(new Uint8Array([e]))
    );
  }
  static serialNumber(e = crypto.getRandomValues(new Uint8Array(4))) {
    return o.integer(e);
  }
  static signatureAlgorithm(e = "sha256WithRSAEncryption") {
    return o.sequence([
      o.objectIdentifier(w(e)),
      o.null()
    ]);
  }
  static async subjectPublicKeyInfo(e) {
    return new Uint8Array(await crypto.subtle.exportKey("spki", e));
  }
  static extensions(e) {
    return o.ASN1(163, o.sequence(e));
  }
  static distinguishedName(e) {
    const t = [];
    for (const [r, n] of Object.entries(e)) {
      const i = [
        o.objectIdentifier(w(r))
      ];
      switch (r) {
        case "countryName":
          i.push(o.printableString(n));
          break;
        default:
          i.push(o.utf8String(n));
      }
      t.push(o.set([o.sequence(i)]));
    }
    return o.sequence(t);
  }
  static validity(e) {
    return o.sequence([
      o.ASN1(
        H.UTCTime,
        new TextEncoder().encode(
          ee((e == null ? void 0 : e.notBefore) ?? /* @__PURE__ */ new Date())
        )
      ),
      o.ASN1(
        H.UTCTime,
        new TextEncoder().encode(
          ee(
            (e == null ? void 0 : e.notAfter) ?? Fe(/* @__PURE__ */ new Date(), 10)
          )
        )
      )
    ]);
  }
  static basicConstraints({
    ca: e = !0,
    pathLenConstraint: t = void 0
  }) {
    const r = [o.boolean(e)];
    return t !== void 0 && r.push(
      o.integer(new Uint8Array([t]))
    ), o.sequence([
      o.objectIdentifier(w("basicConstraints")),
      o.octetString(o.sequence(r))
    ]);
  }
  static keyUsage(e) {
    const t = new Uint8Array([0]);
    return e != null && e.digitalSignature && (t[0] |= 1), e != null && e.nonRepudiation && (t[0] |= 2), e != null && e.keyEncipherment && (t[0] |= 4), e != null && e.dataEncipherment && (t[0] |= 8), e != null && e.keyAgreement && (t[0] |= 16), e != null && e.keyCertSign && (t[0] |= 32), e != null && e.cRLSign && (t[0] |= 64), e != null && e.encipherOnly && (t[0] |= 128), e != null && e.decipherOnly && (t[0] |= 64), o.sequence([
      o.objectIdentifier(w("keyUsage")),
      o.boolean(!0),
      // Critical
      o.octetString(o.bitString(t))
    ]);
  }
  static extKeyUsage(e = {}) {
    return o.sequence([
      o.objectIdentifier(w("extKeyUsage")),
      o.boolean(!0),
      // Critical
      o.octetString(
        o.sequence(
          Object.entries(e).map(([t, r]) => r ? o.objectIdentifier(
            w(t)
          ) : o.null())
        )
      )
    ]);
  }
  static nsCertType(e) {
    const t = new Uint8Array([0]);
    return e.client && (t[0] |= 1), e.server && (t[0] |= 2), e.email && (t[0] |= 4), e.objsign && (t[0] |= 8), e.sslCA && (t[0] |= 16), e.emailCA && (t[0] |= 32), e.objCA && (t[0] |= 64), o.sequence([
      o.objectIdentifier(w("nsCertType")),
      o.octetString(t)
    ]);
  }
  static subjectAltName(e) {
    var i, _;
    const t = ((i = e.dnsNames) == null ? void 0 : i.map((a) => {
      const c = o.ia5String(a);
      return o.contextSpecific(2, c);
    })) || [], r = ((_ = e.ipAddresses) == null ? void 0 : _.map((a) => {
      const c = o.ia5String(a);
      return o.contextSpecific(7, c);
    })) || [], n = o.octetString(
      o.sequence([...t, ...r])
    );
    return o.sequence([
      o.objectIdentifier(w("subjectAltName")),
      o.boolean(!0),
      n
    ]);
  }
}
const ke = {
  // Algorithm OIDs
  "1.2.840.113549.1.1.1": "rsaEncryption",
  "1.2.840.113549.1.1.4": "md5WithRSAEncryption",
  "1.2.840.113549.1.1.5": "sha1WithRSAEncryption",
  "1.2.840.113549.1.1.7": "RSAES-OAEP",
  "1.2.840.113549.1.1.8": "mgf1",
  "1.2.840.113549.1.1.9": "pSpecified",
  "1.2.840.113549.1.1.10": "RSASSA-PSS",
  "1.2.840.113549.1.1.11": "sha256WithRSAEncryption",
  "1.2.840.113549.1.1.12": "sha384WithRSAEncryption",
  "1.2.840.113549.1.1.13": "sha512WithRSAEncryption",
  "1.3.101.112": "EdDSA25519",
  "1.2.840.10040.4.3": "dsa-with-sha1",
  "1.3.14.3.2.7": "desCBC",
  "1.3.14.3.2.26": "sha1",
  "1.3.14.3.2.29": "sha1WithRSASignature",
  "2.16.840.1.101.3.4.2.1": "sha256",
  "2.16.840.1.101.3.4.2.2": "sha384",
  "2.16.840.1.101.3.4.2.3": "sha512",
  "2.16.840.1.101.3.4.2.4": "sha224",
  "2.16.840.1.101.3.4.2.5": "sha512-224",
  "2.16.840.1.101.3.4.2.6": "sha512-256",
  "1.2.840.113549.2.2": "md2",
  "1.2.840.113549.2.5": "md5",
  // pkcs#7 content types
  "1.2.840.113549.1.7.1": "data",
  "1.2.840.113549.1.7.2": "signedData",
  "1.2.840.113549.1.7.3": "envelopedData",
  "1.2.840.113549.1.7.4": "signedAndEnvelopedData",
  "1.2.840.113549.1.7.5": "digestedData",
  "1.2.840.113549.1.7.6": "encryptedData",
  // pkcs#9 oids
  "1.2.840.113549.1.9.1": "emailAddress",
  "1.2.840.113549.1.9.2": "unstructuredName",
  "1.2.840.113549.1.9.3": "contentType",
  "1.2.840.113549.1.9.4": "messageDigest",
  "1.2.840.113549.1.9.5": "signingTime",
  "1.2.840.113549.1.9.6": "counterSignature",
  "1.2.840.113549.1.9.7": "challengePassword",
  "1.2.840.113549.1.9.8": "unstructuredAddress",
  "1.2.840.113549.1.9.14": "extensionRequest",
  "1.2.840.113549.1.9.20": "friendlyName",
  "1.2.840.113549.1.9.21": "localKeyId",
  "1.2.840.113549.1.9.22.1": "x509Certificate",
  // pkcs#12 safe bags
  "1.2.840.113549.1.12.10.1.1": "keyBag",
  "1.2.840.113549.1.12.10.1.2": "pkcs8ShroudedKeyBag",
  "1.2.840.113549.1.12.10.1.3": "certBag",
  "1.2.840.113549.1.12.10.1.4": "crlBag",
  "1.2.840.113549.1.12.10.1.5": "secretBag",
  "1.2.840.113549.1.12.10.1.6": "safeContentsBag",
  // password-based-encryption for pkcs#12
  "1.2.840.113549.1.5.13": "pkcs5PBES2",
  "1.2.840.113549.1.5.12": "pkcs5PBKDF2",
  "1.2.840.113549.1.12.1.1": "pbeWithSHAAnd128BitRC4",
  "1.2.840.113549.1.12.1.2": "pbeWithSHAAnd40BitRC4",
  "1.2.840.113549.1.12.1.3": "pbeWithSHAAnd3-KeyTripleDES-CBC",
  "1.2.840.113549.1.12.1.4": "pbeWithSHAAnd2-KeyTripleDES-CBC",
  "1.2.840.113549.1.12.1.5": "pbeWithSHAAnd128BitRC2-CBC",
  "1.2.840.113549.1.12.1.6": "pbewithSHAAnd40BitRC2-CBC",
  // hmac OIDs
  "1.2.840.113549.2.7": "hmacWithSHA1",
  "1.2.840.113549.2.8": "hmacWithSHA224",
  "1.2.840.113549.2.9": "hmacWithSHA256",
  "1.2.840.113549.2.10": "hmacWithSHA384",
  "1.2.840.113549.2.11": "hmacWithSHA512",
  // symmetric key algorithm oids
  "1.2.840.113549.3.7": "des-EDE3-CBC",
  "2.16.840.1.101.3.4.1.2": "aes128-CBC",
  "2.16.840.1.101.3.4.1.22": "aes192-CBC",
  "2.16.840.1.101.3.4.1.42": "aes256-CBC",
  // certificate issuer/subject OIDs
  "2.5.4.3": "commonName",
  "2.5.4.4": "surname",
  "2.5.4.5": "serialNumber",
  "2.5.4.6": "countryName",
  "2.5.4.7": "localityName",
  "2.5.4.8": "stateOrProvinceName",
  "2.5.4.9": "streetAddress",
  "2.5.4.10": "organizationName",
  "2.5.4.11": "organizationalUnitName",
  "2.5.4.12": "title",
  "2.5.4.13": "description",
  "2.5.4.15": "businessCategory",
  "2.5.4.17": "postalCode",
  "2.5.4.42": "givenName",
  "1.3.6.1.4.1.311.60.2.1.2": "jurisdictionOfIncorporationStateOrProvinceName",
  "1.3.6.1.4.1.311.60.2.1.3": "jurisdictionOfIncorporationCountryName",
  // X.509 extension OIDs
  "2.16.840.1.113730.1.1": "nsCertType",
  "2.16.840.1.113730.1.13": "nsComment",
  "2.5.29.14": "subjectKeyIdentifier",
  "2.5.29.15": "keyUsage",
  "2.5.29.17": "subjectAltName",
  "2.5.29.18": "issuerAltName",
  "2.5.29.19": "basicConstraints",
  "2.5.29.31": "cRLDistributionPoints",
  "2.5.29.32": "certificatePolicies",
  "2.5.29.35": "authorityKeyIdentifier",
  "2.5.29.37": "extKeyUsage",
  // extKeyUsage purposes
  "1.3.6.1.4.1.11129.2.4.2": "timestampList",
  "1.3.6.1.5.5.7.1.1": "authorityInfoAccess",
  "1.3.6.1.5.5.7.3.1": "serverAuth",
  "1.3.6.1.5.5.7.3.2": "clientAuth",
  "1.3.6.1.5.5.7.3.3": "codeSigning",
  "1.3.6.1.5.5.7.3.4": "emailProtection",
  "1.3.6.1.5.5.7.3.8": "timeStamping"
};
function w(s) {
  for (const [e, t] of Object.entries(ke))
    if (t === s)
      return e;
  throw new Error(`OID not found for name: ${s}`);
}
const Q = 32, H = {
  EOC: 0,
  Boolean: 1,
  Integer: 2,
  BitString: 3,
  OctetString: 4,
  Null: 5,
  OID: 6,
  ObjectDescriptor: 7,
  External: 8,
  Real: 9,
  // float
  Enumeration: 10,
  PDV: 11,
  Utf8String: 12,
  RelativeOID: 13,
  Sequence: 16 | Q,
  Set: 17 | Q,
  NumericString: 18,
  PrintableString: 19,
  T61String: 20,
  VideotexString: 21,
  IA5String: 22,
  UTCTime: 23,
  GeneralizedTime: 24,
  GraphicString: 25,
  VisibleString: 26,
  GeneralString: 28,
  UniversalString: 29,
  CharacterString: 30,
  BMPString: 31,
  Constructor: 32,
  Context: 128
};
class o {
  // Helper functions for ASN.1 DER encoding
  static length_(e) {
    if (e < 128)
      return new Uint8Array([e]);
    {
      let t = e;
      const r = [];
      for (; t > 0; )
        r.unshift(t & 255), t >>= 8;
      const n = r.length, i = new Uint8Array(1 + n);
      i[0] = 128 | n;
      for (let _ = 0; _ < n; _++)
        i[_ + 1] = r[_];
      return i;
    }
  }
  static ASN1(e, t) {
    const r = o.length_(t.length), n = new Uint8Array(1 + r.length + t.length);
    return n[0] = e, n.set(r, 1), n.set(t, 1 + r.length), n;
  }
  static integer(e) {
    if (e[0] > 127) {
      const t = new Uint8Array(e.length + 1);
      t[0] = 0, t.set(e, 1), e = t;
    }
    return o.ASN1(H.Integer, e);
  }
  static bitString(e) {
    const t = new Uint8Array([0]), r = new Uint8Array(t.length + e.length);
    return r.set(t), r.set(e, t.length), o.ASN1(H.BitString, r);
  }
  static octetString(e) {
    return o.ASN1(H.OctetString, e);
  }
  static null() {
    return o.ASN1(H.Null, new Uint8Array(0));
  }
  static objectIdentifier(e) {
    const t = e.split(".").map(Number), n = [t[0] * 40 + t[1]];
    for (let i = 2; i < t.length; i++) {
      let _ = t[i];
      const a = [];
      do
        a.unshift(_ & 127), _ >>= 7;
      while (_ > 0);
      for (let c = 0; c < a.length - 1; c++)
        a[c] |= 128;
      n.push(...a);
    }
    return o.ASN1(H.OID, new Uint8Array(n));
  }
  static utf8String(e) {
    const t = new TextEncoder().encode(e);
    return o.ASN1(H.Utf8String, t);
  }
  static printableString(e) {
    const t = new TextEncoder().encode(e);
    return o.ASN1(H.PrintableString, t);
  }
  static sequence(e) {
    return o.ASN1(H.Sequence, h(e));
  }
  static set(e) {
    return o.ASN1(H.Set, h(e));
  }
  static ia5String(e) {
    const t = new TextEncoder().encode(e);
    return o.ASN1(H.IA5String, t);
  }
  static contextSpecific(e, t, r = !1) {
    const n = (r ? 160 : 128) | e;
    return o.ASN1(n, t);
  }
  static boolean(e) {
    return o.ASN1(
      H.Boolean,
      new Uint8Array([e ? 255 : 0])
    );
  }
}
function de(s) {
  return btoa(String.fromCodePoint(...new Uint8Array(s)));
}
function fe(s) {
  var e;
  return ((e = s.match(/.{1,64}/g)) == null ? void 0 : e.join(`
`)) || s;
}
function ee(s) {
  const e = s.getUTCFullYear().toString().substr(2), t = W(s.getUTCMonth() + 1), r = W(s.getUTCDate()), n = W(s.getUTCHours()), i = W(s.getUTCMinutes()), _ = W(s.getUTCSeconds());
  return `${e}${t}${r}${n}${i}${_}Z`;
}
function W(s) {
  return s.toString().padStart(2, "0");
}
function Fe(s, e) {
  const t = new Date(s);
  return t.setUTCFullYear(t.getUTCFullYear() + e), t;
}
const Ge = (s) => ({
  websocket: {
    url: (e, t, r) => `ws://playground.internal/?${new URLSearchParams({
      host: t,
      port: r
    }).toString()}`,
    subprotocol: "binary",
    decorator: () => class extends je {
      constructor(e, t) {
        super(e, t, {
          CAroot: s.CAroot
        });
      }
    }
  }
});
class je {
  constructor(e, t, { CAroot: r, outputType: n = "messages" } = {}) {
    this.url = e, this.options = t, this.CONNECTING = 0, this.OPEN = 1, this.CLOSING = 2, this.CLOSED = 3, this.readyState = this.CONNECTING, this.binaryType = "blob", this.bufferedAmount = 0, this.extensions = "", this.protocol = "ws", this.host = "", this.port = 0, this.listeners = /* @__PURE__ */ new Map(), this.clientUpstream = new TransformStream(), this.clientUpstreamWriter = this.clientUpstream.writable.getWriter(), this.clientDownstream = new TransformStream(), this.fetchInitiated = !1, this.bufferedBytesFromClient = new Uint8Array(0);
    const i = new URL(e);
    this.host = i.searchParams.get("host"), this.port = parseInt(i.searchParams.get("port"), 10), this.binaryType = "arraybuffer", this.CAroot = r, n === "messages" && this.clientDownstream.readable.pipeTo(
      new WritableStream({
        write: (_) => {
          this.emit("message", { data: _ });
        },
        abort: () => {
          this.emit("error", new Error("ECONNREFUSED")), this.close();
        },
        close: () => {
          this.close();
        }
      })
    ).catch(() => {
    }), this.readyState = this.OPEN, this.emit("open");
  }
  on(e, t) {
    this.addEventListener(e, t);
  }
  once(e, t) {
    const r = (n) => {
      t(n), this.removeEventListener(e, r);
    };
    this.addEventListener(e, r);
  }
  addEventListener(e, t) {
    this.listeners.has(e) || this.listeners.set(e, /* @__PURE__ */ new Set()), this.listeners.get(e).add(t);
  }
  removeListener(e, t) {
    this.removeEventListener(e, t);
  }
  removeEventListener(e, t) {
    const r = this.listeners.get(e);
    r && r.delete(t);
  }
  emit(e, t = {}) {
    e === "message" ? this.onmessage(t) : e === "close" ? this.onclose(t) : e === "error" ? this.onerror(t) : e === "open" && this.onopen(t);
    const r = this.listeners.get(e);
    if (r)
      for (const n of r)
        n(t);
  }
  // Default event handlers that can be overridden by the user
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onclose(e) {
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onerror(e) {
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onmessage(e) {
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onopen(e) {
  }
  /**
   * Emscripten calls this method whenever the WASM module
   * writes bytes to the TCP socket.
   */
  send(e) {
    if (!(this.readyState === this.CLOSING || this.readyState === this.CLOSED) && (this.clientUpstreamWriter.write(new Uint8Array(e)), !this.fetchInitiated))
      switch (this.bufferedBytesFromClient = h([
        this.bufferedBytesFromClient,
        new Uint8Array(e)
      ]), Ve(this.port, this.bufferedBytesFromClient)) {
        case !1:
          return;
        case "other":
          this.emit("error", new Error("Unsupported protocol")), this.close();
          break;
        case "tls":
          this.fetchOverTLS(), this.fetchInitiated = !0;
          break;
        case "http":
          this.fetchOverHTTP(), this.fetchInitiated = !0;
          break;
      }
  }
  async fetchOverTLS() {
    if (!this.CAroot)
      throw new Error(
        "TLS protocol is only supported when the TCPOverFetchWebsocket is instantiated with a CAroot"
      );
    const e = await Oe(
      {
        subject: {
          commonName: this.host,
          organizationName: this.host,
          countryName: "US"
        },
        issuer: this.CAroot.tbsDescription.subject
      },
      this.CAroot.keyPair
    ), t = new xe();
    this.clientUpstream.readable.pipeTo(t.clientEnd.upstream.writable).catch(() => {
    }), t.clientEnd.downstream.readable.pipeTo(this.clientDownstream.writable).catch(() => {
    }), await t.TLSHandshake(e.keyPair.privateKey, [
      e.certificate,
      this.CAroot.certificate
    ]);
    const r = await y.parseHttpRequest(
      t.serverEnd.upstream.readable,
      this.host,
      "https"
    );
    try {
      await y.fetchRawResponseBytes(r).pipeTo(
        t.serverEnd.downstream.writable
      );
    } catch {
    }
  }
  async fetchOverHTTP() {
    const e = await y.parseHttpRequest(
      this.clientUpstream.readable,
      this.host,
      "http"
    );
    try {
      await y.fetchRawResponseBytes(e).pipeTo(
        this.clientDownstream.writable
      );
    } catch {
    }
  }
  close() {
    this.emit("message", { data: new Uint8Array(0) }), this.readyState = this.CLOSING, this.emit("close"), this.readyState = this.CLOSED;
  }
}
const $e = [
  "GET",
  "POST",
  "HEAD",
  "PATCH",
  "OPTIONS",
  "DELETE",
  "PUT",
  "TRACE"
];
function Ve(s, e) {
  if (e.length < 8)
    return !1;
  if (s === 443 && e[0] === C.Handshake && // TLS versions between 1.0 and 1.2
  e[1] === 3 && e[2] >= 1 && e[2] <= 3)
    return "tls";
  const r = new TextDecoder("latin1", {
    fatal: !0
  }).decode(e);
  return $e.some(
    (i) => r.startsWith(i + " ")
  ) ? "http" : "other";
}
class y {
  /**
   * Streams a HTTP response including the status line and headers.
   */
  static fetchRawResponseBytes(e) {
    return new ReadableStream({
      async start(t) {
        var _;
        let r;
        try {
          r = await fetch(e), t.enqueue(y.headersAsBytes(r));
        } catch (a) {
          t.error(a);
          return;
        }
        const n = (_ = r.body) == null ? void 0 : _.getReader();
        if (!n) {
          t.close();
          return;
        }
        const i = new TextEncoder();
        for (; ; ) {
          const { done: a, value: c } = await n.read();
          if (c && (t.enqueue(
            i.encode(`${c.length.toString(16)}\r
`)
          ), t.enqueue(c), t.enqueue(i.encode(`\r
`))), a) {
            t.enqueue(i.encode(`0\r
\r
`)), t.close();
            return;
          }
        }
      }
    });
  }
  static headersAsBytes(e) {
    const t = `HTTP/1.1 ${e.status} ${e.statusText}`, r = {};
    e.headers.forEach((_, a) => {
      r[a.toLowerCase()] = _;
    }), delete r["content-length"], r["transfer-encoding"] = "chunked";
    const n = [];
    for (const [_, a] of Object.entries(r))
      n.push(`${_}: ${a}`);
    const i = [t, ...n].join(`\r
`) + `\r
\r
`;
    return new TextEncoder().encode(i);
  }
  /**
   * Parses a raw, streamed HTTP request into a Request object
   * with known headers and a readable body stream.
   */
  static async parseHttpRequest(e, t, r) {
    let n = new Uint8Array(0), i = !1, _ = -1;
    const a = e.getReader();
    for (; _ === -1; ) {
      const { done: D, value: L } = await a.read();
      if (D) {
        i = !0;
        break;
      }
      n = h([n, L]), _ = ze(
        n,
        new Uint8Array([13, 10, 13, 10])
      );
    }
    a.releaseLock();
    const c = n.slice(0, _), S = y.parseRequestHeaders(c), l = n.slice(
      _ + 4
      /* Skip \r\n\r\n */
    );
    let A;
    if (S.method !== "GET") {
      const D = e.getReader();
      A = new ReadableStream({
        async start(L) {
          l.length > 0 && L.enqueue(l), i && L.close();
        },
        async pull(L) {
          const { done: pe, value: q } = await D.read();
          if (q && L.enqueue(q), pe) {
            L.close();
            return;
          }
        }
      });
    }
    const u = S.headers.get("Host") ?? t, T = new URL(S.path, r + "://" + u);
    return T.pathname = S.path, new Request(T.toString(), {
      method: S.method,
      headers: S.headers,
      body: A,
      // In Node.js, duplex: 'half' is required when
      // the body stream is provided.
      // @ts-expect-error
      duplex: "half"
    });
  }
  static parseRequestHeaders(e) {
    const t = new TextDecoder().decode(e), r = t.split(`
`)[0], [n, i] = r.split(" "), _ = new Headers();
    for (const a of t.split(`\r
`).slice(1)) {
      if (a === "")
        break;
      const [c, S] = a.split(": ");
      _.set(c, S);
    }
    return { method: n, path: i, headers: _ };
  }
}
function ze(s, e) {
  const t = s.length, r = e.length, n = t - r;
  for (let i = 0; i <= n; i++) {
    let _ = !0;
    for (let a = 0; a < r; a++)
      if (s[i + a] !== e[a]) {
        _ = !1;
        break;
      }
    if (_)
      return i;
  }
  return -1;
}
const Ye = () => ({
  websocket: {
    decorator: (s) => class extends s {
      constructor() {
        try {
          super();
        } catch {
        }
      }
      send() {
        return null;
      }
    }
  }
});
async function Ct(s, e = {}) {
  var n;
  const t = await De(s);
  (n = e.onPhpLoaderModuleLoaded) == null || n.call(e, t);
  const r = e.tcpOverFetch ? Ge(e.tcpOverFetch) : Ye();
  return await me(t, {
    ...e.emscriptenOptions || {},
    ...r
  });
}
function lt(s, e) {
  window.addEventListener("message", (t) => {
    t.source === s.contentWindow && (e && t.origin !== e || typeof t.data != "object" || t.data.type !== "relay" || window.parent.postMessage(t.data, "*"));
  }), window.addEventListener("message", (t) => {
    var r;
    t.source === window.parent && (typeof t.data != "object" || t.data.type !== "relay" || (r = s == null ? void 0 : s.contentWindow) == null || r.postMessage(t.data));
  });
}
async function At(s) {
  const e = new Worker(s, { type: "module" });
  return new Promise((t, r) => {
    e.onerror = (i) => {
      const _ = new Error(
        `WebWorker failed to load at ${s}. ${i.message ? `Original error: ${i.message}` : ""}`
      );
      _.filename = i.filename, r(_);
    };
    function n(i) {
      i.data === "worker-script-started" && (t(e), e.removeEventListener("message", n));
    }
    e.addEventListener("message", n);
  });
}
function ut(s, e = { initialSync: {} }) {
  return e = {
    ...e,
    initialSync: {
      ...e.initialSync,
      direction: e.initialSync.direction ?? "opfs-to-memfs"
    }
  }, async function(t, r, n) {
    return e.initialSync.direction === "opfs-to-memfs" ? (B.fileExists(r, n) && B.rmdir(r, n), B.mkdir(r, n), await Je(r, s, n)) : await Ee(
      r,
      s,
      n,
      e.initialSync.onProgress
    ), Ze(t, s, n);
  };
}
async function Je(s, e, t) {
  B.mkdir(s, t);
  const r = new ge({
    concurrency: 40
  }), n = [], i = [
    [e, t]
  ];
  for (; i.length > 0; ) {
    const [_, a] = i.pop();
    for await (const c of _.values()) {
      const S = r.run(async () => {
        const l = se(
          a,
          c.name
        );
        if (c.kind === "directory") {
          try {
            s.mkdir(l);
          } catch (A) {
            if ((A == null ? void 0 : A.errno) !== 20)
              throw b.error(A), A;
          }
          i.push([c, l]);
        } else if (c.kind === "file") {
          const A = await c.getFile(), u = new Uint8Array(await A.arrayBuffer());
          s.createDataFile(
            a,
            c.name,
            u,
            !0,
            !0,
            !0
          );
        }
        n.splice(n.indexOf(S), 1);
      });
      n.push(S);
    }
    for (; i.length === 0 && n.length > 0; )
      await Promise.any(n);
  }
}
async function Ee(s, e, t, r) {
  s.mkdirTree(t);
  const n = [];
  async function i(l, A) {
    await Promise.all(
      s.readdir(l).filter(
        (u) => u !== "." && u !== ".."
      ).map(async (u) => {
        const T = se(l, u);
        if (!Xe(s, T)) {
          n.push([A, T, u]);
          return;
        }
        const D = await A.getDirectoryHandle(u, {
          create: !0
        });
        return await i(T, D);
      })
    );
  }
  await i(t, e);
  let _ = 0;
  const a = r && et(r, 100), c = 100, S = /* @__PURE__ */ new Set();
  try {
    for (const [l, A, u] of n) {
      const T = Te(
        l,
        u,
        s,
        A
      ).then(() => {
        _++, S.delete(T), a == null || a({
          files: _,
          total: n.length
        });
      });
      S.add(T), S.size >= c && (await Promise.race(S), a == null || a({
        files: _,
        total: n.length
      }));
    }
  } finally {
    await Promise.allSettled(S);
  }
}
function Xe(s, e) {
  return s.isDir(s.lookupPath(e, { follow: !0 }).node.mode);
}
async function Te(s, e, t, r) {
  let n;
  try {
    n = t.readFile(r, {
      encoding: "binary"
    });
  } catch {
    return;
  }
  const i = await s.getFileHandle(e, { create: !0 }), _ = i.createWritable !== void 0 ? (
    // Google Chrome, Firefox, probably more browsers
    await i.createWritable()
  ) : (
    // Safari
    await i.createSyncAccessHandle()
  );
  try {
    await _.truncate(0), await _.write(n);
  } finally {
    await _.close();
  }
}
function Ze(s, e, t) {
  const r = [], n = Ke(s, t, (a) => {
    r.push(a);
  }), i = new Qe(s, e, t);
  async function _() {
    const a = await s.semaphore.acquire();
    try {
      for (; r.length; )
        await i.processEntry(r.shift());
    } finally {
      a();
    }
  }
  return s.addEventListener("request.end", _), function() {
    n(), s.removeEventListener("request.end", _);
  };
}
class Qe {
  constructor(e, t, r) {
    this.php = e, this.opfs = t, this.memfsRoot = te(r);
  }
  toOpfsPath(e) {
    return te(e.substring(this.memfsRoot.length));
  }
  async processEntry(e) {
    if (!e.path.startsWith(this.memfsRoot) || e.path === this.memfsRoot)
      return;
    const t = this.toOpfsPath(e.path), r = await ne(this.opfs, t), n = re(t);
    if (n)
      try {
        if (e.operation === "DELETE")
          try {
            await r.removeEntry(n, {
              recursive: !0
            });
          } catch {
          }
        else if (e.operation === "CREATE")
          e.nodeType === "directory" ? await r.getDirectoryHandle(n, {
            create: !0
          }) : await r.getFileHandle(n, {
            create: !0
          });
        else if (e.operation === "WRITE")
          await Te(
            r,
            n,
            this.php[k].FS,
            e.path
          );
        else if (e.operation === "RENAME" && e.toPath.startsWith(this.memfsRoot)) {
          const i = this.toOpfsPath(e.toPath), _ = await ne(
            this.opfs,
            i
          ), a = re(i);
          if (e.nodeType === "directory") {
            const c = await _.getDirectoryHandle(
              n,
              {
                create: !0
              }
            );
            await Ee(
              this.php[k].FS,
              c,
              e.toPath
            ), await r.removeEntry(n, {
              recursive: !0
            });
          } else
            (await r.getFileHandle(n)).move(_, a);
        }
      } catch (i) {
        throw b.log({ entry: e, name: n }), b.error(i), i;
      }
  }
}
function te(s) {
  return s.replace(/\/$/, "").replace(/\/\/+/g, "/");
}
function re(s) {
  return s.substring(s.lastIndexOf("/") + 1);
}
async function ne(s, e) {
  const t = e.replace(/^\/+|\/+$/g, "").replace(/\/+/, "/");
  if (!t)
    return s;
  const r = t.split("/");
  let n = s;
  for (let i = 0; i < r.length - 1; i++) {
    const _ = r[i];
    n = await n.getDirectoryHandle(_, { create: !0 });
  }
  return n;
}
function et(s, e) {
  let t = 0, r, n;
  return function(..._) {
    n = _;
    const a = Date.now() - t;
    if (r === void 0) {
      const c = Math.max(0, e - a);
      r = setTimeout(() => {
        r = void 0, t = Date.now(), s(...n);
      }, c);
    }
  };
}
export {
  ot as certificateToPEM,
  _t as consumeAPI,
  ut as createDirectoryHandleMountHandler,
  at as exposeAPI,
  Oe as generateCertificate,
  De as getPHPLoaderModule,
  Ct as loadWebRuntime,
  ct as privateKeyToPEM,
  lt as setupPostMessageRelay,
  At as spawnPHPWorkerThread
};
